kelceyswain
kelceyswain

Reputation: 45

Updating a user model in Django when they fill out a form on a different model

I am struggling to work out how to achieve something and would appreciate someone suggesting the correct Django way to do it.

I have a custom user model which is fairly basic but includes a BooleanField which says whether they have filled out a voluntary equality and diversity form. There is a very basic model which holds the equality and diversity form data without any reference to the users which filled out each response. What I want is this, when a user fills out a valid equality and diversity form it puts True in the user model box to say they have filled out the form.

I would be massively appreciative if anyone knows the correct way to do this as I am tying myself up in knots and have got myself quite confused.

Here is a simplified version of the code:

users/models.py

class CustomUser(AbstractUser):
    # Has the user completed the EDI form?
    edi = models.BooleanField(default=False)
    def get_absolute_url(self):
        return reverse('profile', args=[str(self.username)])

equality_diversity/models.py

class EqualityDiversity(models.Model):
    age = models.CharField(max_length=8, choices=AGE_CHOICES)
    ethnicity = models.CharField(max_length=64, blank=True, null=True)
    ... (etc)

equality_diversity/views.py

class EqualityDiversityView(LoginRequiredMixin, CreateView):
    model = EqualityDiversity
    template_name = 'equality_diversity.html'
    form_class = EqualityDiversityForm
    login_url = 'login'

    success_url = '/'

    def form_valid(self, form):
        return super().form_valid(form)

Upvotes: 0

Views: 42

Answers (1)

Ahmed I. Elsayed
Ahmed I. Elsayed

Reputation: 2130

class EqualityDiversityView(LoginRequiredMixin, CreateView):
    model = EqualityDiversity
    template_name = 'equality_diversity.html'
    form_class = EqualityDiversityForm
    login_url = 'login'

    success_url = '/'

    def form_valid(self, form):
        # this is a view, You have self.request
        self.request.user.edi = True
        # apply changes to db
        self.request.user.save()
        return super().form_valid(form)  # redirects to success_url

or better

class EqualityDiversityView(LoginRequiredMixin, CreateView):
    model = EqualityDiversity
    template_name = 'equality_diversity.html'
    form_class = EqualityDiversityForm
    login_url = 'login'

    success_url = '/'

    def form_valid(self, form):
        # form.instance is an instance of the model that the form defines in META
        form.instance.edi = True
        # apply changes to db
        form.instance.save()
        return super().form_valid(form)  # redirects to success_url

Upvotes: 1

Related Questions