我一直在尝试将参数从我的createview传递给form,但是在表单中没有收到该参数。我不知道出了什么问题。
以下是我的观点,
class ItemCreateView(LoginRequiredMixin,CreateView):
form_class = ItemForm
template_name = 'form.html'
def get_form_kwargs(self):
kwargs = super(ItemCreateView, self).get_form_kwargs()
kwargs['user'] = self.request.user # pass the 'user' in kwargs
return kwargs
def get_context_data(self,**kwargs):
context = super(ItemCreateView,self).get_context_data(**kwargs)
context['title'] = 'Add Items'
return context
def form_valid(self,form):
instance = form.save(commit = False)
instance.user = self.request.user
instance.save()
return super(ItemCreateView, self).form_valid(form)
以下是我的表单类:
from django import forms
from .models import Item
from restaurants.models import RestaurantLocation
class ItemForm(forms.ModelForm):
class Meta:
model = Item
fields=[
'name',
'restaurant',
'contents',
'excludes',
'public'
]
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
print(user)
super(ItemForm,self).__init__(*args,**kwargs)
self.fields['restaurant'].queryset = RestaurantLocation.objects.filter(owner=user)