姜戈。如何在表单中自动 select 所需的用户

Django. How to automatically select the desired user in the form

我最近开始研究Django。我有一个与用户关联的模型。 需要自动填写“用户”字段。 我想使用 request.user,但我的尝试没有成功。你能告诉我正确的做法吗?

样本来自 - 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')

表格 - https://i.stack.imgur.com/zcwLk.png

您可以尝试重写 form_valid 方法

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)

您可以覆盖 CreateViewget_initial() 方法:

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

适应您的需求。