Cannot get this ModelForm view to save to the db, what am I doing wrong please

20 views
Skip to first unread message

MikeKJ

unread,
Dec 10, 2018, 11:41:23 AM12/10/18
to Django users

Cannot seem to get .save() to write to the db

This is the model


class Customer(models.Model):
    email = models.EmailField()
    postcode = models.CharField(max_length=10)
    def __unicode__(self):
    return self.email
    def save(self):
        self.postcode=upper(self.postcode)
        super(Customer, self).save()
 

This is the view:


class RegisterForm(ModelForm): class Meta: model = Customer def register(request): form = RegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] postcode = form.cleaned_data['postcode'] postcode = upper(postcode) try: user = Customer.objects.all().filter(email=email).filter(postcode=postcode)[:1] if user: error = "You have already registered this email address and postcode, please login." return render_to_response("customer/register_form.html", {'error': error, 'form': form, 'content': content,},context_instance=RequestContext(request)) except Customer.DoesNotExist: cust_obj = Customer(email=email, postcode=postcode) cust_obj.save() return HttpResponseRedirect('/registration-thankyou/')

Also tried

new_user = form.save(commit=False)
new_user.save()

It isn't throwing any errors just not saving to the table

Cheers for any insight/help

Matthew Pava

unread,
Dec 10, 2018, 11:58:47 AM12/10/18
to django...@googlegroups.com

It’s hard to tell with some of the spacing in your email.  Python cares deeply about spacing.

 

When initializing a form, I typically do it as so:

form = RegisterForm(request.POST or None)

 

Also, the save method on the model has several arguments that you are not passing around.

    def save(self, *args, **kwargs):
        self.postcode = self.postcode.upper()

        super(Customer, self).save(*args, **kwargs)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b55ba86d-65dd-4c33-9144-4b9a5cf15bcc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages