我想填写我的表单字段(url)并在我的下一个表单字段中使用该url作为默认值(在另一个视图中)。我无法切换视图并获取该表单值。有什么建议吗?这是我的文件:
views.py
def subcategory(request, category_name_slug, subcategory_name_slug):
context = {}
form = SiteAddForm()
context['form'] = form
try:
category = Category.objects.get(slug=category_name_slug)
subcategory = SubCategory.objects.filter(category=category
).get(slug=subcategory_name_slug)
sites = Site.objects.filter(subcategory=subcategory)
context['subcategory'] = subcategory
context['sites'] = sites
except (SubCategory.DoesNotExist, Category.DoesNotExist):
raise Http404("Nie ma takiej strony")
if request.method == 'POST':
form = SiteAddForm(request.POST)
if form.is_valid():
siteurl = form.cleaned_data['url']
context['siteurl'] = siteurl
return render(request, 'mainapp/add_site.html', context)
return render(request, 'mainapp/subcategory.html', context)
def add_site(request, category_name_slug, subcategory_name_slug):
context = {}
forms = SiteAddFormA()
context['form'] = forms
return render(request, 'mainapp/add_site.html', context)
forms.py:
from django import forms
from mainapp.models import Site
class SiteAddForm(forms.Form):
url = forms.URLField(label='Url')
class SiteAddFormA(forms.ModelForm):
url = forms.URLField(max_length=200, help_text='Please enter the URL of the page.')
class Meta:
model = Site
fields = ('url', 'name', 'description',)
urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category,
name='category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/$',
views.subcategory,
name='subcategory'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/(?P<id>[\w\-]+)/$',
views.site,
name='site'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/add_site/$',
views.add_site,
name='add_site'),
models.py:
class Site(models.Model):
category = models.ForeignKey('Category')
subcategory = ChainedForeignKey(
'Subcategory',
chained_field='category',
chained_model_field='category',
show_all=False,
auto_choose=True)
name = models.CharField(max_length=30)
description = models.TextField()
keywords = MyTextField()
date = models.DateTimeField(default=datetime.now)
url = models.URLField()
def __str__(self):
return self.name