How to assign currently logged in user as default value for a model field?

前端 未结 5 1800
独厮守ぢ
独厮守ぢ 2020-11-30 07:06

I\'d like to do something like this:

class Task(models.Model):
    ...
    created_by = models.ForeignKey(User, **default=[LoggedInUser]** blank=True, null=T         


        
5条回答
  •  独厮守ぢ
    2020-11-30 07:10

    SOLVED: I will use an example, but the important part is the funciton on the views.py. User is automatically available by django. Note the 'autor' model field has a ForeignKey to the 'User'. In the 'def form_valid' below I assign the currently logged in user as the default value.

    If this is your model:

    class ProspectoAccion(models.Model):
    """
    Model representing a comment against a blog post.
    """
        descripcion = models.TextField(max_length=1000)
        autor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
        accion_date = models.DateTimeField(auto_now_add=True)
        prospecto= models.ForeignKey(Prospecto, on_delete=models.CASCADE)
        tipo_accion = models.ForeignKey('Accion', on_delete=models.SET_NULL, null=True)
    

    And you have a class based view, do the following:

    class ProspectoAccionCreate(LoginRequiredMixin, CreateView):
    """
    Form for adding una acción. Requires login (despues poner)
    """
        model = ProspectoAccion
        fields = ['tipo_accion','descripcion',]
    
        def form_valid(self, form):
    
            #Add logged-in user as autor of comment THIS IS THE KEY TO THE SOLUTION
            form.instance.autor = self.request.user
    
            # Call super-class form validation behaviour
            return super(ProspectoAccionCreate, self).form_valid(form)
    

    HERE IS AN EXAMPLE FROM THE DOCUMENTATION: https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-editing/#models-and-request-user

提交回复
热议问题