如何将当前登录的用户默认传递给表单

时间:2017-08-24 12:05:51

标签: python django

如何将当前登录的用户默认传递给表单?

我希望表单可以预先填充当前用户,但同时允许用户更改它(例如,为另一个用户添加客户)。

这是我的模特:

class Customer (models.Model):

    shortname = models.CharField(max_length=30)
    name = models.CharField(max_length=50, blank=True)
    [...]
    user = models.ForeignKey(User)
    nextstep = models.DateField(auto_now=False, auto_now_add=False, default=(date.today() + timedelta(days=10)))

    def due_in(self):

        due_time = self.nextstep - date.today()
        overdue = due_time.days < 0
        return {'days': abs(due_time.days), 'overdue': overdue}

    def get_absolute_url(self):
        """Absolute URL des Partners"""
        return reverse('kundencenter:partner_detail', kwargs={'pk': self.pk}, current_app='kundencenter')

我的表格:

class CustomerForm(forms.ModelForm):

    class Meta:
        model = Customer
        fields = [
            "shortname",
            "name",
            [...]
            "user",
        ]

        labels = {
            "shortname": 'Customer Shortname',
            "name": 'Full Name',
            }

我的观点:

class CustomerCreateView(SuccessMessageMixin, CreateView):
    """Adds a new customer."""
    model = Customer
    template_name = 'customercenter/generic_new.html'
    form_class = CustomerForm
    success_message = "Customer %(name)s added."

2 个答案:

答案 0 :(得分:4)

您可以在渲染表单时使用表单中的initial。

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

有关详细信息,请参阅docs

答案 1 :(得分:1)

扩展Arpit Solanki的答案,您可以添加/覆盖get_initial方法,因为您使用的是基于类的视图:

def get_initial(self):
    initial_data = super(CustomerCreateView, self).get_initial()
    initial_data.update({'user':self.request.user})
    return initial_data