修复了视图django的错误:未找到页面

时间:2014-06-07 16:53:25

标签: python django django-forms django-views

我的英语不好! 我尝试了很多方法,但仍然得到错误:找不到页面。 文件views.py:

def create_article(request, template_name='vlogntruong/create_article.html'):
if request.method == "POST":
    create_form = VlogForm(request.POST)
    if create_form.is_valid():
        new_article = create_form.save()
        return HttpResponeRedirect(new_article.get_absolute_url())
else:
    create_form = VlogForm(request)

template_context = {
    'create_form': create_form,
}

return render_to_response(
    template_name,
    template_context,
    RequestContext(request)
)

文件forms.py

from django import forms
from .models import VlogNTruong

class VlogForm(forms.Form):
    title= forms.CharField(max_length=100,
                           widget=forms.TextInput(attrs={'size':50}))
    name = forms.CharField(max_length=50,
                           widget = forms.TextInput(attrs={'size':50}))
    sumary = forms.CharField(widget = forms.Textarea(attrs={"rows":10, "cols":80}))
    content = forms.CharField(widget = forms.Textarea(attrs={"rows":20, "cols":80}))
    video = forms.CharField(required = False,
                              widget = forms.TextInput(attrs={'size':60}))

    def save(self):
        create_form = VlogNTruong(title = self.cleaned_data['title'],
                           name = self.cleaned_data['name'],
                           sumary = self.cleaned_data['content'],
                           content = self.cleaned_data['content'],
                           video = self.cleaned_data['video'])
        create_form.save()
        return create_form

文件models.py:

from django.db import models
from django.db.models import permalink
from embed_video.fields import EmbedVideoField
from django.template.defaultfilters import slugify
from django.contrib import admin
import datetime



class VlogNTruong (models.Model):
    title = models.CharField(max_length=100)
    slug_field = models.TextField(null=True, blank=True)
    name = models.CharField(max_length=50)
    sumary = models.TextField()
    content = models.TextField()
    time_create = models.DateTimeField(auto_now_add=True)
    video = EmbedVideoField(null=True, blank=True)

    class Meta:
        ordering = ('-time_create',)

    def __unicode__(self):
        return "%s" % self.title

    @permalink
    def get_absolute_url(self):
        return ('vlogntruong.views.article_detail', [self.slug_field])

    def save(self, *args, **kwargs):
        if not self.slug_field:
            self.slug_field = slugify(self.title)
        super(VlogNTruong, self).save(*args, **kwargs)

file html

{% extends 'vlogntruong/base.html' %}
{% block panel_content %}
<form action="/" method="post">{% csrf_token %} 
<table>
    {{form.as_table}}
</table>
<input type="submit" name="Create" />
</form>
{% endblock %}

文件网址

urlpatterns = patterns('vlogntruong.views',
    url(r'^$', 'list_article',
        {'template_name':'vlogntruong/list_article.html'}),
    url(r'^(?P<slug_field>[-\w\d]+)/$', 'article_detail'),
    url(r'^create/$', 'create_article'),
)

帮帮我

错误

Page not found (404)
Request Method: GET
Request URL:    /nhuttruong/create/
No VlogNTruong matches the given query.
You're seeing this error because you have DEBUG = True in your Django settings file.   Change that to False, and Django will display a standard 404 page.

2 个答案:

答案 0 :(得分:0)

您在第三个url()中使用的正则表达式与请求的URL不匹配:

r'^ create / $''/ nhuttruong / create /'

不匹配

为了实现您的目标,您应该使用类似 r'。+ / create / $'

答案 1 :(得分:0)

您的问题是表单中的save()方法没有返回它在数据库中创建的对象,而是返回未保存的实例,您正试图获取该实例重定向网址。

我建议你阅读modelforms guide来帮助你。

您的表单应如下所示:

from django import forms
from .models import VlogNTruong

class VlogForm(forms.ModelForm):
    title= forms.CharField(max_length=100,
                           widget=forms.TextInput(attrs={'size':50}))
    name = forms.CharField(max_length=50,
                           widget = forms.TextInput(attrs={'size':50}))
    sumary = forms.CharField(widget = forms.Textarea(attrs={"rows":10, "cols":80}))
    content = forms.CharField(widget = forms.Textarea(attrs={"rows":20, "cols":80}))
    video = forms.CharField(required = False,
                              widget = forms.TextInput(attrs={'size':60}))

    class Meta:
        model = VlogNTruong

然后,在您的视图中,您需要像这样调整它:

from django.shortcuts import render

def create_article(request, template_name='vlogntruong/create_article.html'):
    create_form = VlogForm(request.POST or None)
    if create_form.is_valid():
        new_article = create_form.save()
        return HttpResponeRedirect(new_article.get_absolute_url())
    template_context = {'create_form': create_form,}
    return render(request, template_name, template_context)

您还需要确保VlogNTruong模型的get_absolute_url method返回一个网址。你的方法只返回一个元组,修复如下:

def get_absolute_url(self):
    from django.core.urlresolvers import reverse
    return reverse('vlogntruong.views.article_detail', args=[self.slug_field])

最后你的__unicode__方法必须返回一个unicode对象,你的方法返回一个字符串:

def __unicode__(self):
    return unicode('{}'.format(self.title))