我正在尝试 Tango With Django 教程,而 clean() 方法中的覆盖无法在我的网址中添加“http://”。这段代码有什么问题?
表格.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
视图.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 本身不接受这种写作。