这是一个创建于 2672 天前的主题,其中的信息可能已经有所发展或是发生改变。
要上传 URL,用的自带的 URLField,但是默认是必须输入 http 开头,现在想让用户不输入。现在代码是
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text='Please enter the title')
url = forms.URLField(max_length=200, help_text='Please enter the URL')
views = forms.CharField(widget=forms.HiddenInput(), initial=0)
class Meta:
model = Page
exclude = ('category',)
#这一段不知道怎么起效果
def clean(self):
cleaned_data = self.cleaned_data
url = cleaned_data.get('url')
if url and not url.startswith('http://'):
url = 'http://' + url
cleaned_data['url'] = url
return cleaned_data
views 里的代码:
def add_page(request, category_name_slug):
try:
category = Category.objects.get(slug=category_name_slug)
except Category.DoesNotExist:
category = None
form = PageForm()
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
if category:
page = form.save(commit=False)
page.category = category
page.views = 0
page.save()
return show_category(request, category_name_slug)
else:
print(form.errors)
context_dict = {'form': form, 'category': category}
return render(request, 'rango/add_page.html', context_dict)
4 条回复 • 2017-07-14 14:46:07 +08:00
|
|
1
hactrox 2017-07-14 01:00:59 +08:00
clean 应该要有针对性。
```python def clean_url(self): url = self.cleaned_data.get('url')
if not url: raise forms.ValidationError("......")
if not url.startswith('http://'): return 'http://' + url
return url ```
|
|
|
3
hactrox 2017-07-14 09:40:25 +08:00 1
@ garygay clean() 或者 clean_xxx() 会在执行 form.is_valid() 的过城中被调用
|
|
|
4
garygay 2017-07-14 14:46:07 +08:00
|