我收到了上面标题中所述的错误。我正在尝试将表单提供给user_id,因为我的模型要求添加表格'。但是,我对get_form_kwargs的使用似乎有问题。
这是模型:
from django.db import models
from django.contrib.auth.models import User
class Vtable(models.Model):
user = models.ForeignKey(User)
table_name = models.CharField(max_length=200)
added_date = models.DateTimeField('date added')
class Vdata(models.Model):
table_id = models.ForeignKey(Vtable)
table_pk = models.IntegerField()
column_1 = models.CharField(max_length=200)
column_2 = models.CharField(max_length=200)
added_date = models.DateTimeField('date added')
这是观点:
from django.shortcuts import render
from django.http import HttpResponse
from django.views import generic
from vtables.models import Vtable
class CreateTableView(generic.CreateView):
model = Vtable
fields = ['table_name']
def get_form_kwargs(self):
# pass "user" keyword argument with the current user to your form
kwargs = super(CreateTableView, self).get_form_kwargs()
kwargs['user_id'] = self.request.user
return kwargs
答案 0 :(得分:1)
为了将自定义值传递给表单,您必须创建自己的表单类并将其传递给视图。视图创建的默认表单类不知道如何处理user_id
参数,以及错误来自何处。
以下是有关如何传递自定义表单类的示例,首先是表单类:
class MyForm(forms.ModelForm):
class Meta:
model = Vtable
def __init__(self, *args, **kwargs):
user_id = kwargs.pop('user_id') # Pop out your custom argument
super(MyForm, self).__init__(args, kwargs) # Initialize your form
# as usual
self.user_id = user_id # Add it as an instance variable
然后,在您看来:
class CreateVTable(generic.CreateView):
form_class = MyForm
model = Vtable
答案 1 :(得分:1)
由CreateView
(或任何模型表单)生成的表单类没有任何外键的_id
字段。相反,它有一个user
字段ModelChoiceField
。
此外,该逻辑不应包含在您的表单中。表单仅仅是捕获和验证用户输入的手段。哪个用户创建对象不是用户输入,这种逻辑应该在您的视图中,例如:
class CreateTableView(generic.CreateView):
model = Vtable
fields = ['table_name']
def form_valid(self, form):
form.instance.user = self.request.user
return super(CreateTableView, self).form_valid(form)