Home > Enterprise >  Django. How to automatically select the desired user in the form
Django. How to automatically select the desired user in the form

Time:01-02

I recently started studying Django. I have a model that is associated with users. Need to fill in the "User" field automatically. I wanted to use request.user, but my attempts were unsuccessful. Can you tell me how to do it correctly?

Sample from - https://i.stack.imgur.com/zcwLk.png

models.py

class Ticket(models.Model):

    ticket_id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
    ticket_title = models.CharField(max_length=100)
    ticket_date_open = models.DateTimeField(auto_now_add=True)
    ticket_status = models.BooleanField(default=False)
    ticket_reason = models.TextField()
  
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='User')

forms.py

class TicketForm(ModelForm):
    class Meta:
        model = Ticket
        fields = ('ticket_title', 'ticket_status', 'ticket_reason', 'user',)

views.py

class CreateTicket(CreateView):
    form_class = TicketForm

    template_name = 'support/new_t[enter image description here][1]icket.html'
    success_url = reverse_lazy('test')

Form - https://i.stack.imgur.com/zcwLk.png

CodePudding user response:

You can try by overriding form_valid method

class CreateTicket(CreateView):
    form_class = TicketForm

    template_name = 'support/new_t[enter image description here[1]icket.html'
    success_url = reverse_lazy('test')

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.user= self.request.user
        return super(CreateTicket, self).form_valid(form)

CodePudding user response:

You can override the get_initial() method of CreateView:

def get_initial(self):
    if self.request.user.is_authenticated():
        return {"user": self.request.user}
    return super().initial.copy()

Adapt to your needs.

  • Related