request.user in Django model

后端 未结 1 416
醉梦人生
醉梦人生 2021-02-15 17:03

I am using Django models to create the fields for a form. I would like to have the user\'s username automatically detected in and be filled out, this way I can hide it in my for

相关标签:
1条回答
  • 2021-02-15 17:17

    Here you haven't imported request in that model class scope. This is how you can get user:

    # model
    
    class StockTickerSymbol(models.Model):
        StockName = models.CharField(max_length=7, unique=True)
        user = models.ForeignKey(User)
    
        def save(self,**kwargs):
          if kwargs.has_key('request') and self.user is None:
                request = kwargs.pop('request')
                self.user= request.user
          super(StockTickerSymbol, self).save(**kwargs)
    
    #views:
    
    def post(self, request):
       if form.is_valid():                         
           sts=StockTickerSymbol()
           sts.StockName= form.cleaned_data['StockName']
           if form.cleaned_data['user'] is None: #null check
              sts.save(request=request)
           else:
              sts.user= form.cleaned_data['user']
              sts.save(request=request)
    

    For modelform:

    class SomeForm(forms.ModelForm):
        ...
    
        def save(self, commit=True ,*args, **kwargs):
            request = None
            if kwargs.has_key('request'):
                request = kwargs.pop('request')
            m = super(SomeForm, self).save(commit=False, *args, **kwargs)
            if m.user is None and request is not None:
                m.user= request.user
                m.save()
    

    in views:

    def post(self, request):
       if form.is_valid():  
          form.save(request=request)
          return ...
    
    0 讨论(0)
提交回复
热议问题