Question

I'm trying to make am modelform that is used to send an email to change the email on a user entry, and for some reason it gives me access_emailchangeauth.user_id may not be NULL when I click submit on the form. I have no idea why.

code is below

def changeEmail(request):
    data = request.POST if request.method == 'POST' else None
    if data:
        form = ChangeEmailForm(data)
        if form.is_valid():
            form.save(user=request.user)
        else:
            a = request.user
            a = u.objects.get(username__iexact=a)
            form = UserModificationForm(instance=a)
            form2 = ChangeEmailForm()
            return render('accounts/modify.html',{'form': form, 'form2': form2, 'usr': a})

#forms.py
class ChangeEmailForm(ModelForm):
    class Meta:
        model = EmailChangeAuth
        fields = ['new_email']

    def save(self, *args, **kwargs):
        user = kwargs.pop('user')
        self.user = user
        print user
        super(ChangeEmailForm, self).save(*args, **kwargs)
#models.py

class EmailChangeAuth(models.Model):
    auth_code = UUIDField(auto=True, unique=True)
    user = models.ForeignKey(u)
    new_email = models.EmailField(max_length=256)

    def __unicode__(self):
        return unicode(self.auth_code)
Was it helpful?

Solution

Since you have not included user in the list of fields, it will not be passed on to the ModelForm's instance constructor.

Thus, what you want here is to change the user attribute of the form's instance, not the attribute on the form object itself. In .save(), change self.user to self.instance.user. That should get you going.

However, I also want to suggest that this mechanism it generally an anti-pattern: why are you not allowing user to be a field on the ModelForm if it's a required field that you populate anyway?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top