0

I have 2 models Profiles and Events. I want to save the number of events created by the user to the users profile, such that even if the events are deleted the record stays in the users profile

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    total_events = models.IntegerField(default=0) 

class Event(models.Model):
    user = models.ForeignKey(User, related_name='seller')
    ...

Below are my views

class CreateEvent(IsVerifiedMixin, CreateView):
    model = Event
    form_class = EventForm
    template_name = 'event/event_form.html'

    def form_valid(self, form, *args, **kwargs):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        print(self.object.user.profile.total_events) #This prints 0
        self.object.user.profile.total_events += 1
        print(self.object.user.profile.total_events) # This prints 1
        self.object.user.profile.total_events.save() # If I don't use this statement it does not save to database. But It gives me the above error
        self.object.save()
        return super().form_valid(form)

This line self.object.user.profile.total_events.save() gives me the error

How do I fix this error. I tried adding a variable and saving the variable but I still get the same error

1 Answer 1

1

total_events is an integer that's part of your Profile model.

you want to execute save on a model instance, not a model field.

self.objects.user.profile.save() should work

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.