Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't save form content to database

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.

models.py looks like this:

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:

local variable 'created_by' referenced before assignment

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

like image 209
dana Avatar asked May 16 '10 10:05

dana


1 Answers

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.)

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:

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.

like image 144
Daniel Roseman Avatar answered Nov 09 '22 08:11

Daniel Roseman