我想自动将配置文件实例分配给订单,我尝试了如视图中所示,但仍然形成错误显示所需的配置文件。希望有人能提供帮助,谢谢。
models.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
first_name = models.CharField(max_length=80,blank=True, null=True)
middle = models.CharField(max_length=80, blank=True, null=True)
last_name = models.CharField(max_length=80, blank=True, null=True)
class Order(models.Model):
profile = models.ForeignKey(Profile)
qty_ordered = models.IntegerField(blank=True, null=True)
views.py
class OrderCreate(CreateView):
model = Order
form_class = OrderForm
success_url = reverse_lazy('home')
def form_valid(self, form):
form.instance.order_id = self.kwargs.get('pk')
return super(OrderCreate, self).form_valid(form)
order_form.html
<form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{ form.qty_ordered| as_crispy_field }}
<input type='submit' class='btn btn-primary' value='Save & Continue' />
答案 0 :(得分:0)
尝试在form_valid
方法中添加以下内容。
def form_valid(self, form):
# ...
profile = Profile.objects.get(user=self.request.user) # or something similar
form.instance.profile = profile
# return the super as you do