无法将表单内容保存到数据库

时间:2021-10-25 13:19:17

I'm trying to save 100 characters form user in a 'microblog' minimal application. My code seems to not have any mystakes, but doesn't work. The mistake is in views.py, I can't save the foreign key to user table.

我试图在'微博'最小应用程序中保存用户100个字符。我的代码似乎没有任何mystakes,但不起作用。错误是在views.py中,我无法将外键保存到用户表。

models.py looks like this:

models.py看起来像这样:

class NewManager(models.Manager):

    def create_post(self, post, username):
 new = self.model(post=post, created_by=username)
        new.save()
        return new

class New(models.Model):

    post = models.CharField(max_length=120)
    date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User, blank=True) 
    objects = NewManager()   


class NewForm(ModelForm):

    class Meta:
          model = New
          fields = ['post']
         # widgets = {'post': Textarea(attrs={'cols': 80, 'rows': 20})

def save_new(request):

    if request.method == 'POST':
        created_by = User.objects.get(created_by = user) 
        date = request.POST.get('date', '')
        post = request.POST.get('post', '')
        new_obj = New(post=post, date=date, created_by=created_by)
        new_obj.save()
        return HttpResponseRedirect('/')
     else:
           form = NewForm()     
    return render_to_response('news/new_form.html', {'form': form},context_instance=RequestContext(request))  

I didn't mention imports here - they're done right, anyway. My mistake is in views.py. When I try to save it says:

我没有在这里提到进口 - 无论如何,他们做得对。我的错误在于views.py。当我试图保存时说:

local variable 'created_by' referenced before assignment

在赋值之前引用的局部变量'created_by'

If I put created_py as a parameter, the save needs more parameters. It is really weird.

如果我将created_py作为参数,则保存需要更多参数。这真的很奇怪。

1 个解决方案

#1


7  

You don't show the complete traceback, which would help to track down exactly where the error is happening. (I suspect this isn't the exact code you're running, or that isn't the actual error message, because as rebus mentions the error doesn't match the code.)

您没有显示完整的回溯,这将有助于准确追踪错误发生的位置。 (我怀疑这不是您正在运行的确切代码,或者不是实际的错误消息,因为当rebus提到错误与代码不匹配时。)

However, a couple of pointers. Firstly, you don't seem to be using the form to do the saving. If you did, you probably wouldn't see this error. Rather than get the values manually from the request, you should instantiate the form using request.POST and then save that. Also, you're not checking that the form is actually valid before trying to use its values. Here's what you should be doing:

但是,有几个指针。首先,您似乎没有使用该表单进行保存。如果你这样做,你可能不会看到这个错误。您应该使用request.POST实例化表单,而不是从请求手动获取值,然后保存它。此外,在尝试使用其值之前,您没有检查表单是否实际有效。这是你应该做的:

if request.method == 'POST':
    form = NewForm(request.POST)
    if form.is_valid():
        new_obj = form.save(commit=False)
        new_obj.created_by = request.user
        new_obj.save()
        return HttpResponseRedirect('/')
else:
    form = NewForm()
return render_to_response('news/new_form.html', {'form': form},
                          context_instance=RequestContext(request))  

Also, note that your manager is completely irrelevant - the default manager already defines a create method, which does exactly the same as yours.

另外,请注意您的经理完全不相关 - 默认经理已经定义了一个创建方法,它与您的完全相同。

#1


7  

You don't show the complete traceback, which would help to track down exactly where the error is happening. (I suspect this isn't the exact code you're running, or that isn't the actual error message, because as rebus mentions the error doesn't match the code.)

您没有显示完整的回溯,这将有助于准确追踪错误发生的位置。 (我怀疑这不是您正在运行的确切代码,或者不是实际的错误消息,因为当rebus提到错误与代码不匹配时。)

However, a couple of pointers. Firstly, you don't seem to be using the form to do the saving. If you did, you probably wouldn't see this error. Rather than get the values manually from the request, you should instantiate the form using request.POST and then save that. Also, you're not checking that the form is actually valid before trying to use its values. Here's what you should be doing:

但是,有几个指针。首先,您似乎没有使用该表单进行保存。如果你这样做,你可能不会看到这个错误。您应该使用request.POST实例化表单,而不是从请求手动获取值,然后保存它。此外,在尝试使用其值之前,您没有检查表单是否实际有效。这是你应该做的:

if request.method == 'POST':
    form = NewForm(request.POST)
    if form.is_valid():
        new_obj = form.save(commit=False)
        new_obj.created_by = request.user
        new_obj.save()
        return HttpResponseRedirect('/')
else:
    form = NewForm()
return render_to_response('news/new_form.html', {'form': form},
                          context_instance=RequestContext(request))  

Also, note that your manager is completely irrelevant - the default manager already defines a create method, which does exactly the same as yours.

另外,请注意您的经理完全不相关 - 默认经理已经定义了一个创建方法,它与您的完全相同。