干燥我的 Django 视图:请帮助我!

发布于 2024-11-09 02:11:57 字数 6351 浏览 0 评论 0原文

我希望这是一个很好的第一个问题。我一直在尝试干燥我的 Django 代码,但不幸的是我不断遇到几个错误! (如果我不发布有问题的代码,请原谅我 - 我只会发布有效的代码)我尝试过使用@decorators,并且还在视图中放置了一个视图。请帮我!

from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from blog.models import Post, User, Blog, Comment
from blog.forms import CommentForm, PostForm, BlogForm
from django.core.urlresolvers import reverse
import datetime
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django import forms

def limiter(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))

def postindex(request):
    posts = get_list_or_404(Post.objects.all())
    return render_to_response('index.html', {'posts':posts})

def onepost(request, postid):
    post = get_object_or_404(Post, pk=postid)
    if request.method == 'POST':
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('accounts.views.login_view'))
        form = CommentForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            c = Comment(owner=request.user,
                post=Post.objects.get(pk=postid),
                time=datetime.datetime.now(),
                text=cd['text'])
            c.save()
            return HttpResponseRedirect(reverse('blog.views.onepost', 
                args=[postid]))
    else:
        form = CommentForm()
    return render_to_response('single.html',
        {'post':post,'comments':post.comment_set.all(),
        'form':form},
        context_instance=RequestContext(request))

def userlist(request):
    users = get_list_or_404(User.objects.all())
    return render_to_response('userlist.html', {'users':users})

def bloglist(request, userid):
    blogs = get_list_or_404(Blog.objects.filter(owner__pk=userid))
    return render_to_response('bloglist.html', {'blogs':blogs})

def postlist(request, blogid):
    posts = get_list_or_404(Post.objects.filter(blog__pk=blogid))
    return render_to_response('postlist.html', {'posts':posts})

def landing(request):
    return render_to_response('landing.html', {})

def dash(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    user = request.user
    blogs = Blog.objects.filter(owner=request.user)
    comments = Comment.objects.filter(owner=request.user)
    posts = Post.objects.filter(blog__owner=request.user)
    return render_to_response('dash.html',
        {'user':user, 'blogs':blogs, 'comments':comments, 'posts':posts})

def newpost(request, blogid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    blog = Blog.objects.get(pk=blogid)
    if not request.user == blog.owner:
        return HttpResponseRedirect(reverse('blog.views.dash'))
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            p = Post(title=cd['title'],
                blog=Blog.objects.get(pk=blogid),
                date=datetime.datetime.now(),
                content=cd['content'])
            p.save()
            return HttpResponseRedirect(reverse('blog.views.postlist', 
                args=[blogid]))
    else:
        form = PostForm()
    return render_to_response('chngpost.html',
        {'blog':blog,
        'form':form},
        context_instance=RequestContext(request))

def editpost(request, postid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    post = Post.objects.get(pk=postid)
    if not request.user == post.blog.owner:
        return HttpResponseRedirect(reverse('blog.views.dash'))
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            post.title=cd['title']
            post.content=cd['content']
            post.save()
            return HttpResponseRedirect(reverse('blog.views.onepost', 
                args=[postid]))
    else:
        form = PostForm(initial={'title':post.title,'content':post.content})
    return render_to_response('chngpost.html',
        {'post':post,
        'form':form},
        context_instance=RequestContext(request))

def delpost(request, postid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    post = Post.objects.get(pk=postid)
    if not request.user == post.blog.owner:
        return HttpResponseRedirect(reverse('blog.views.dash'))
    if request.method == 'POST':
        post.delete()
        return HttpResponseRedirect(reverse('blog.views.dash'))
    return render_to_response('delpost.html',
        {'post':post},
        context_instance=RequestContext(request))

def newblog(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    if request.method == 'POST':
        form = BlogForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            b = Blog(title=cd['title'],
                owner=request.user)
            b.save()
            return HttpResponseRedirect(reverse('blog.views.bloglist', 
                args=[request.user.pk]))
    else:
        form = BlogForm()
    return render_to_response('chngpost.html',
        {'form':form},
        context_instance=RequestContext(request))

def delcomment(request, commentid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    comment = Comment.objects.get(pk=commentid)
    if not (request.user == comment.post.blog.owner) | (request.user == comment.owner):
        return HttpResponseRedirect(reverse('blog.views.dash'))
    if request.method == 'POST':
        comment.delete()
        return HttpResponseRedirect(reverse('blog.views.dash'))
    return render_to_response('delpost.html',
        {},
        context_instance=RequestContext(request))

(希望格式正确)我想特别考虑的代码是

if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))

但是当然,任何更多的建议将不胜感激!太感谢了! `

I hope this is a good first question. I've been trying to DRY out my Django code, but unfortunately I keep getting hit with several errors! (Forgive me if I don't post the code with problems - I'll just post the code that works) I've tried using @decorators, and also putting a view within a view. Please help me!

from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from blog.models import Post, User, Blog, Comment
from blog.forms import CommentForm, PostForm, BlogForm
from django.core.urlresolvers import reverse
import datetime
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django import forms

def limiter(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))

def postindex(request):
    posts = get_list_or_404(Post.objects.all())
    return render_to_response('index.html', {'posts':posts})

def onepost(request, postid):
    post = get_object_or_404(Post, pk=postid)
    if request.method == 'POST':
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('accounts.views.login_view'))
        form = CommentForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            c = Comment(owner=request.user,
                post=Post.objects.get(pk=postid),
                time=datetime.datetime.now(),
                text=cd['text'])
            c.save()
            return HttpResponseRedirect(reverse('blog.views.onepost', 
                args=[postid]))
    else:
        form = CommentForm()
    return render_to_response('single.html',
        {'post':post,'comments':post.comment_set.all(),
        'form':form},
        context_instance=RequestContext(request))

def userlist(request):
    users = get_list_or_404(User.objects.all())
    return render_to_response('userlist.html', {'users':users})

def bloglist(request, userid):
    blogs = get_list_or_404(Blog.objects.filter(owner__pk=userid))
    return render_to_response('bloglist.html', {'blogs':blogs})

def postlist(request, blogid):
    posts = get_list_or_404(Post.objects.filter(blog__pk=blogid))
    return render_to_response('postlist.html', {'posts':posts})

def landing(request):
    return render_to_response('landing.html', {})

def dash(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    user = request.user
    blogs = Blog.objects.filter(owner=request.user)
    comments = Comment.objects.filter(owner=request.user)
    posts = Post.objects.filter(blog__owner=request.user)
    return render_to_response('dash.html',
        {'user':user, 'blogs':blogs, 'comments':comments, 'posts':posts})

def newpost(request, blogid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    blog = Blog.objects.get(pk=blogid)
    if not request.user == blog.owner:
        return HttpResponseRedirect(reverse('blog.views.dash'))
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            p = Post(title=cd['title'],
                blog=Blog.objects.get(pk=blogid),
                date=datetime.datetime.now(),
                content=cd['content'])
            p.save()
            return HttpResponseRedirect(reverse('blog.views.postlist', 
                args=[blogid]))
    else:
        form = PostForm()
    return render_to_response('chngpost.html',
        {'blog':blog,
        'form':form},
        context_instance=RequestContext(request))

def editpost(request, postid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    post = Post.objects.get(pk=postid)
    if not request.user == post.blog.owner:
        return HttpResponseRedirect(reverse('blog.views.dash'))
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            post.title=cd['title']
            post.content=cd['content']
            post.save()
            return HttpResponseRedirect(reverse('blog.views.onepost', 
                args=[postid]))
    else:
        form = PostForm(initial={'title':post.title,'content':post.content})
    return render_to_response('chngpost.html',
        {'post':post,
        'form':form},
        context_instance=RequestContext(request))

def delpost(request, postid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    post = Post.objects.get(pk=postid)
    if not request.user == post.blog.owner:
        return HttpResponseRedirect(reverse('blog.views.dash'))
    if request.method == 'POST':
        post.delete()
        return HttpResponseRedirect(reverse('blog.views.dash'))
    return render_to_response('delpost.html',
        {'post':post},
        context_instance=RequestContext(request))

def newblog(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    if request.method == 'POST':
        form = BlogForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            b = Blog(title=cd['title'],
                owner=request.user)
            b.save()
            return HttpResponseRedirect(reverse('blog.views.bloglist', 
                args=[request.user.pk]))
    else:
        form = BlogForm()
    return render_to_response('chngpost.html',
        {'form':form},
        context_instance=RequestContext(request))

def delcomment(request, commentid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))
    comment = Comment.objects.get(pk=commentid)
    if not (request.user == comment.post.blog.owner) | (request.user == comment.owner):
        return HttpResponseRedirect(reverse('blog.views.dash'))
    if request.method == 'POST':
        comment.delete()
        return HttpResponseRedirect(reverse('blog.views.dash'))
    return render_to_response('delpost.html',
        {},
        context_instance=RequestContext(request))

(Hope that's formatted properly) The code I'd like to factor out especially is

if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('accounts.views.login_view'))

But of course any more suggestions would be appreciated! Thank you so much!
`

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终止放荡 2024-11-16 02:11:57
  1. 使用 login_required 装饰器 (docs
  2. 使用模型表单来编辑/创建模型。 (docs)
  3. 如果您需要将某些内容传递给模板,请使用direct_to_template 通用视图(文档
  1. Use login_required decorator (docs)
  2. Use modelforms for editing/creating models. (docs)
  3. If you need to just pass something to template, use direct_to_template generic view (docs)
孤单情人 2024-11-16 02:11:57

您可以使用 @login_required 装饰器。您可以在 Django 文档中找到更多信息: http ://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required

请描述您遇到的任何问题。

You can use @login_required decorator for that. You can find out more at Django documentation: http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required.

Please describe any problems that you are experiencing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文