1

我正在尝试 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 本身不接受这种写作。

4

2 回答 2

1

通常,由于您只清理一个字段,因此您应该在特定于字段的方法clean_url中执行此操作。

def clean_url(self):
    url = self.cleaned_data['url']
    # your cleaning here
    return url
于 2015-06-29T20:12:57.927 回答
0

你需要这个:

def clean(self):
    cleaned_data = super(PageForm, self).clean() # <-----------
    url = cleaned_data.get('url')
    if url and not url.startswith('http://'):
        url += 'http://'
        cleaned_data['url'] = url
    return cleaned_data
于 2015-06-29T19:59:49.980 回答