我正在尝试Tango With Django Tutorial,而clean()方法中的覆盖不能在我的网址中添加“http://”。这段代码有什么问题?
forms.py
class PageForm(forms.ModelForm):
...
def clean(self):
cleaned_data = self.cleaned_data
url = cleaned_data.get('url')
if url and not url.startswith('http://'):
url += 'http://'
cleaned_data['url'] = url
return cleaned_data
views.py
def add_page(request, category_name_slug):
try:
cat = Category.objects.get(slug=category_name_slug)
except Category.DoesNotExist:
cat = None
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
if cat:
page = form.save(commit=False)
page.category = cat
page.views = 0
page.save()
return category(request, category_name_slug)
else:
print(form.errors)
else:
form = PageForm()
context_dict = {'category': cat, 'form': form}
return render(request, 'rango/add_page.html', context_dict)
add_page.html
{% extends "base.html" %}
{% block title %}Add Page{% endblock title %}
{% block content %}
<h1>Add a Page</h1>
<form id='page_form' method='post' action="">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" Value="Create Page" />
</form>
{% endblock content %}
管理员工作正常,但html本身并不接受这篇文章。
答案 0 :(得分:1)
你需要这个:
A2 contains TC9999 AB2 should say 209999
A3 contains CFG8888 AB3 should say 108888
A4 contains BCA11 AB4 should say 500011
答案 1 :(得分:1)
通常,由于您只清理一个字段,因此应使用特定于字段的方法 clean_url 执行此操作。
def clean_url(self):
url = self.cleaned_data['url']
# your cleaning here
return url