我有两个视图部分,其中一个将字段保存到数据库中,另一个是自动填充字段。如何在html模板中同时使用它们?
第一视图:
def stock(request):
stocks_form=StocksForm(None)
if request.method == "POST":
stocks_form =StocksForm(data=request.POST)
if stocks_form.is_valid():
instance=stocks_form.save()
instance.user=request.user
instance.save()
messages.success(request,"Successful" ,extra_tags="savestock")
else:
messages.error(request, "Error!")
else:
stocks_form=StocksForm()
return render(request,'BallbearingSite/stock.html',{'stocks_form':stocks_form})
第二视图:
class StocksAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return Stocks.objects.none()
qs = Stocks.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
urls.py
url(r'^stock/$',views.stock,name='stock'),
url(r'^stock_autocomplete/$',views.StocksAutocomplete.as_view(create_field='name'),name='stock_autocomplete'),
项目urls.py:
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^ajax_select/', include(ajax_select_urls)),
url(r'^admin/BallbearingSite/controlsite/$',views.sendemailview),
url(r'^admin/', include(admin.site.urls)),
url(r'^',include('BallbearingSite.urls', namespace='BallbearingSite')),
url(r'^logout/$',views.user_logout,name='logout'),
url(r'^login/$',views.user_login,name='login'),
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
url('^', include('django.contrib.auth.urls')),
]
模板:
<form enctype="multipart/form-data" method="post" >
{% csrf_token %}
{{ stocks_form.as_p }}
<input id="savestocks" type="submit" name="" value="ثبت">
</form>
forms.py:
class StocksForm(forms.ModelForm):
class Meta():
model=Stocks
fields=('name','number','suffix','brand','comment','price')
widgets = {
'name': autocomplete.ModelSelect2(url='stock_autocomplete')
}
def clean_name(self):
return self.cleaned_data['comment'].upper()
出现此错误:
NoReverseMatch at /stock/
Reverse for 'stock_autocomplete' with arguments '()' and keyword arguments'{}' not found. 0 pattern(s) tried: []
它错误地突出显示了这些部分:
{{ stocks_form.as_p }}
和:
return render(request,'BallbearingSite/stock.html',{'stocks_form':stocks_form})
答案 0 :(得分:1)
您可能会错过网址中的命名空间。如果stock_autocomplete
网址在BallbearingSite
命名空间中,您可以执行以下操作:
'name': autocomplete.ModelSelect2(url='BallbearingSite:stock_autocomplete')