Django Forms, set an initial value to request.user

前端 未结 4 2025
攒了一身酷
攒了一身酷 2021-02-01 07:51

Is there some way to make the following possible, or should it be done elsewhere?

class JobRecordForm(forms.ModelForm):
    supervisor = forms.ModelChoiceField(
         


        
相关标签:
4条回答
  • 2021-02-01 08:23

    An Another solution with Middleware and save rewriting : With middleware solution You can call "request" everywhere.


    """ Middleware """

        # coding: utf-8 
    from django.utils.thread_support import currentThread 
    _requests = {}
    
    def get_request():
        return _requests[currentThread()]
    
    class GlobalRequestMiddleware(object):
        def process_request(self, request):  
            _requests[currentThread()] = request
    

    """ save Rewrinting """

    class Production(models.Model):
        creator = models.ForeignKey(User, related_name = "%(class)s_creator")
        creation_date = models.DateTimeField(auto_now_add = True)
        modification_date = models.DateTimeField(auto_now = True)
    
        def save(self, force_insert = False, force_update = False):
    
            self.creator = get_request().user
            super(Production, self).save(force_insert = force_insert, force_update = force_update)
            return
    
    0 讨论(0)
  • 2021-02-01 08:41

    For a complete answer, here's the CBV solution:

    class MyFormView(TemplateView, FormMixin):
        def get_initial(self):
            self.initial.update({'your_field': self.request.user})
            return super(MyFormView, self).get_initial()
    
    0 讨论(0)
  • 2021-02-01 08:43

    If you do this in your view.py instead:

    form = JobRecordForm( initial={'supervisor':request.user} )
    

    Then you won't trigger the validation.

    See http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values

    0 讨论(0)
  • 2021-02-01 08:45

    You might want to handle this in your view function. Since your view function must create the initial form, and your view function knows the user.

    form = JobRecordForm( {'supervisor':request.user} )
    

    This will trigger validation of this input, BTW, so you can't provide hint values this way.

    0 讨论(0)
提交回复
热议问题