如何让用户删除和编辑他们在Django中创建的帖子?

时间:2016-08-23 18:42:38

标签: python django python-3.x edit delete-file

我试图让用户删除并编辑他们创建的帖子。我被告知“Post.user需要成为一个对象实例,你写的是不正确的。”但我仍然是django的新手,并且想知道在我创建这个项目的过程中有所帮助的步骤。

这是我的模特

        from django.db import models

        from django.db.models import Count, QuerySet, F
        from django.utils import timezone
        from django.conf import settings
        from django.contrib.contenttypes.models import ContentType
        from django.core.urlresolvers import reverse
        from django.db.models.signals import pre_save
        from django.utils.text import slugify
        from markdown_deux import markdown
        from django.utils.safestring import mark_safe
        from taggit.managers import TaggableManager

        from comments.models import Comment

        def upload_location(instance, filename):
            return "%s/%s" %(instance.slug, filename)


        class Post(models.Model):
            user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 )
            title = models.CharField(max_length=75)
            slug = models.SlugField(unique=True)
            image = models.ImageField(
                    upload_to=upload_location,
                    null=True,
                    blank=True,
                    width_field="width_field",
                    height_field="height_field")
            height_field = models.IntegerField(default=0)
            width_field = models.IntegerField(default=0)
            description = models.TextField()
            tags = TaggableManager()
            public = models.BooleanField(default=False)
            updated = models.DateTimeField(auto_now_add=False, auto_now=True)
            created = models.DateTimeField(auto_now_add=True, auto_now=False)


            def __str__(self):
                return self.title

            def get_absolute_url(self):
                return reverse("posts:detail", kwargs={"slug": self.slug})

            class Meta:
                ordering = ["-created", "-updated" ]

            def get_markdown(self):
                description = self.description
                markdown_text = markdown(description)
                return mark_safe(markdown_text)

            @property
            def comments(self):
                instance = self
                qs = Comment.objects.filter_by_instance(instance)
                return qs

            @property
            def get_content_type(self):
                instance = self
                content_type = ContentType.objects.get_for_model(instance.__class__)
                return content_type


        def create_slug(instance, new_slug=None):
                slug = slugify(instance.title)
                if new_slug is not None:
                    slug = new_slug
                qs = Post.objects.filter(slug=slug).order_by("-id")
                exists = qs.exists()
                if exists:
                    new_slug = "%s-%s" %(slug, qs.first().id)
                    return create_slug(instance, new_slug=new_slug)
                return slug



        def pre_save_post_receiver(sender, instance, *args, **kwargs):
            if not instance.slug:
                instance.slug = create_slug(instance)


        pre_save.connect(pre_save_post_receiver, sender=Post)

以下是我的观点

            from django.contrib import messages
            from django.contrib.contenttypes.models import ContentType
            from django.core.paginator import Paginator, EmptyPage,   PageNotAnInteger
            from django.shortcuts import render
            from django.contrib.auth.decorators import login_required


            from django.db.models import Q
            from django.http import HttpResponse, HttpResponseRedirect, Http404
            from django.shortcuts import render, get_object_or_404, redirect
            from django.core.exceptions import PermissionDenied


            from comments.forms import CommentForm
            from comments.models import Comment
            from .forms import PostForm
            from .models import Post


            def post_main(request):
                return render(request, "base2.html")

            @login_required
            def post_create(request):
                form = PostForm(request.POST or None, request.FILES or None)
                if form.is_valid():
                    instance = form.save(commit=False)
                    instance.user = request.user
                    instance.save()
                    # message success
                    messages.success(request, "Successfully Created")
                    return HttpResponseRedirect(instance.get_absolute_url())
                context = {
                    "form": form,
                }
                return render(request, "post_form.html", context)

            @login_required
            def post_update(request, slug=None):
                    instance = get_object_or_404(Post, slug=slug)
                    form = PostForm(request.POST or None, request.FILES or None, instance=instance)
                    if form.is_valid():
                        instance = form.save(commit=False)
                        instance.save()
                        messages.success(request, "Post Saved")
                        return HttpResponseRedirect(instance.get_absolute_url())

                    context = {
                    "title": instance.title,
                    "instance": instance,
                    "form":form
                    }

                    return render(request, "post_form.html", context)


            def post_user(request):

                return HttpResponse("<h1>Users Post</h1>")

            @login_required
            def post_detail(request, slug=None):
                instance = get_object_or_404(Post, slug=slug)

                initial_data = {
                    "content_type": instance.get_content_type,
                    "object_id": instance.id
                }
                form = CommentForm(request.POST or None, initial=initial_data)
                if form.is_valid() and request.user.is_authenticated():
                    c_type = form.cleaned_data.get("content_type")
                    content_type = ContentType.objects.get(model=c_type)
                    obj_id = form.cleaned_data.get('object_id')
                    content_data = form.cleaned_data.get("content")
                    parent_obj = None
                    try:
                        parent_id = int(request.POST.get("parent_id"))
                    except:
                        parent_id = None

                    if parent_id:
                        parent_qs = Comment.objects.filter(id=parent_id)
                        if parent_qs.exists() and parent_qs.count() == 1:
                            parent_obj = parent_qs.first()


                    new_comment, created = Comment.objects.get_or_create(
                                        user = request.user,
                                        content_type= content_type,
                                        object_id = obj_id,
                                        content = content_data,
                                        parent = parent_obj,
                                    )
                    return HttpResponseRedirect(new_comment.content_object.get_absolute_url())


                comments = instance.comments
                context = {
                    "title": instance.title,
                    "instance": instance,
                    "comments": comments,
                    "comment_form":form,
            }
                return render(request, "post_detail.html", context)

            @login_required
            def post_feed(request):
                queryset_list = Post.objects.all()
                query = request.GET.get("q")
                if query:
                    queryset_list = queryset_list.filter(
                            Q(title__icontains=query)|
                            Q(tags__icontains=query)|
                            Q(content__icontains=query)|
                            Q(user__first_name__icontains=query) |
                            Q(user__last_name__icontains=query)
                            ).distinct()
                paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
                page_request_var = "page"
                page = request.GET.get(page_request_var)
                try:
                    queryset = paginator.page(page)
                except PageNotAnInteger:
                    # If page is not an integer, deliver first page.
                    queryset = paginator.page(1)
                except EmptyPage:
                    # If page is out of range (e.g. 9999), deliver last page of results.
                    queryset = paginator.page(paginator.num_pages)


                context = {
                    "object_list": queryset,
                    "title": "List",
                    "page_request_var": page_request_var,
                }
                return render(request, "post_feed.html", context)

            @login_required
            def post_delete(request,  slug=None):
                instance = get_object_or_404(Post, slug=slug)
                if request.user == Post.user:
                    instance.delete() # or save edits
                    messages.success(request, "Successfully Deleted")
                    return redirect("posts:feed")
                else:
                    raise PermissionDenied # import it from django.core.exceptions
                    return redirect("posts:feed")

            def privacy(request):
                    return render(request, "privacy.html")

            def post_about(request):
                return HttpResponse("<h1>About Page</h1>")

            def home(request):
                return render(request, "base2.html")

如果需要任何其他信息,请告诉我。

1 个答案:

答案 0 :(得分:5)

你快到了。

delete

,您的支票应为:

request.user == instance.user

而不是

request.user == Post.user

同样在post_update中,你可以这样做:

if instance.user == request.user:
    #Now, allow update

此外,检查请求类型可能是个好主意。例如:

if request.method == "POST":

这样,只有在POST类型

时才会进行此检查