Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django override model save() method

I want to get request as a parameter in save() method.

models.py

class Profile(models.Model):
    uuid = UUIDField(auto=True)
    user = models.ForeignKey(User)
    name = models.CharField(max_length=128)
    dob = models.DateField()

    class Meta:
        db_table = 'profile'

    def save(self,*args,**kwargs):
        if not self.pk:
            self.user_id = 2  #here i need request.user instead of 2
        super(Profile,self).save(*args,**kwargs)

forms.py

class ProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        exclude = ['uuid','user']

views.py

def add(request):
    profile_form = ProfileForm(request.POST)
    profile_form.save()

Instead of the value 2 i want to pass request.user. How can i do it. If question is not correct somebody please correct the question.

like image 706
Thameem Avatar asked Dec 06 '25 02:12

Thameem


1 Answers

Don't do that in the model. Do it in the view.

profile_form = ProfileForm(request.POST)
if profile_form.is_valid():
    profile = profile_form.save(commit=False)
    profile.user = request.user
    profile.save()
like image 138
Daniel Roseman Avatar answered Dec 09 '25 18:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!