Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving form data rewrites the same row

i can't figure out how to save my form data creating a new row, when saving it just rewrites the data using the same 'id' and trhows me an error when there are multiple rows, this is my code:

models.py:

class Submitter(models.Model):
    submitter=models.ForeignKey(User)

    def __unicode__(self):
        return self.submitter.username

class Store(models.Model):
    creator=models.ForeignKey(Submitter)
    name = models.CharField(_('name'),blank=True,max_length=30)
    st = models.CharField(_('Street'),blank=True,max_length=30)
    sub_date = models.DateField(_('Visit Date'),)

    def __str__(self):
        return u'%s-%s-%s'%(self.creator,self.name,self.sub_date)

views.py:

def StoreSave(request):    
    if request.method == 'POST':
        form = StoreForm(request.POST)
        if form.is_valid():
            submitter, dummy= Creator.objects.get_or_create(creator=request.user)
            store, created = Store.objects.get_or_create(
                submitter=submitter
            )
            store.name = form.cleaned_data['name']
            store.st = form.cleaned_data['st']
            store.visit_date = form.cleaned_data['visit_date']
            store.save()
            return HttpResponseRedirect('/user/%s/' % request.user.username)
    else:
        form = StoreForm()
    variables = RequestContext(request, {
            'form': form
    })
    return render_to_response('store/create_store.html', variables)
like image 995
user739030 Avatar asked May 05 '11 02:05

user739030


1 Answers

If you want to create a new row, create it. :-) Like

store = Store(submitter=submitter,
              name=form.cleaned_data['name'],
              st=form.cleaned_data['st'],
              store.visit_date=form.cleaned_data['visit_date'])
store.save()

Now you use get_or_create method which tries to find a row with given parameters, so that's why you updating it. And this method throws an error when there are multiple rows, yes, it's its normal behavior.

By the way it's better to place this saving code in form's method (save for example).

P. S. Just noticed you don't have visit_date field in your model, I think you meant sub_date.

like image 60
DrTyrsa Avatar answered Oct 12 '22 15:10

DrTyrsa