gpt4 book ai didi

python - 如何正确重写 clean() 方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:36:43 24 4
gpt4 key购买 nike

我正在尝试 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

View .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 本身不接受此写入。

最佳答案

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

def clean_url(self):
url = self.cleaned_data['url']
# your cleaning here
return url

关于python - 如何正确重写 clean() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31124329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com