django覆盖模型save()方法

时间:2015-03-09 11:49:29

标签: django django-models django-forms django-views

我想将request作为save()方法中的参数。

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()

而不是值2我希望传递request.user。我该怎么做。如果问题不正确,有人请更正问题。

3 个答案:

答案 0 :(得分:7)

不要在模型中这样做。在视图中执行。

profile_form = ProfileForm(request.POST)
if profile_form.is_valid():
    profile = profile_form.save(commit=False)
    profile.user = request.user
    profile.save()

答案 1 :(得分:5)

一种方法是使用crequest,如下所示:

# model
from crequest.middleware import CrequestMiddleware

class Profile(models.Model):
    # Some fields
    def save(self, *args, **kwargs):
        crequest = CrequestMiddleware.get_request() #its the current request
        if crequest.user.pk is 1:
            # Do stuff
           pass
    super(Profile,self).save(*args,**kwargs)

答案 2 :(得分:1)

你可以使用kwargs。 例如:

views.py

profile_form.save(your_arg = request)

models.py

your_var = kwargs.pop("your_arg", None) #Second argument of kwargs.pop is default value

在您的情况下,将请求作为关键字参数传递,然后在模型save()方法中使用它。