如何在Python Django中更新文章?

zte4gxcn  于 2023-03-24  发布在  Go
关注(0)|答案(1)|浏览(97)

我用Django做了一个博客。我看了很多视频来制作一个用户可以更新/编辑自己文章的功能。但是我没有得到它的工作。我是Django的新手,所以如果有人能帮助我,我会很感激。
这是我的views.py:

from django.shortcuts import render, redirect
from .models import Article
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . import forms
#from django.core.paginator import Paginator
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

@login_required(login_url="/accounts/login/")
def article_list(request):
    articles = Article.objects.all().order_by('-date')
    paginator = Paginator(Article.objects.all().order_by('-date'), 6)
    page = request.GET.get('page')

    try:
        items = paginator.page(page)
    except PageNotAnInteger:
        items = paginator.page(1)
    except EmptyPage:
        items = paginator.page(paginator.num_pages)
    index = items.number - 1
    max_index = len(paginator.page_range)
    page_range = paginator.page_range[0:max_index]

    return render(request, 'articles/article_list.html', {'articles':articles, 'items':items, 'page_range':page_range})

@login_required(login_url="/accounts/login/")
def article_details(request, slug):
    article = Article.objects.get(slug=slug)
    return render(request, 'articles/article_details.html', {'article':article})

@login_required(login_url="/accounts/login/")
def article_create(request):
    if request.method == 'POST':
        form = forms.CreateArticle(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return redirect('articles:list')
    else:
        form = forms.CreateArticle()
    return render(request, 'articles/article_create.html', {'form':form})

@login_required(login_url="/accounts/login/")
def article_edit(request, slug):
    article = Article.objects.get(slug=slug)
    form = forms.CreateArticle(request.GET, request.FILES)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.author = request.user
        instance.save()
        return redirect('articles:list')
    return render(request, 'articles/article_edit.html', {'form':form})

我试图在article_edit中创建视图。
这里是urls.py:

from django.conf.urls import url
from . import views

from .views import article_edit

app_name = 'articles'
urlpatterns = [
    url(r'^$',views.article_list, name="list"),
    url(r'^create/$', views.article_create, name="create"),
    url(r'^(?P<slug>[\w-]+)/$', views.article_details, name="details"),
    url(r'^(?P<slug>[\w-]+)/edit/$', views.article_edit, name="edit"),
]

我想用url()来做,就像上面的article_details一样。
下面是包含编辑按钮的article_details. html:

{% extends 'default.html' %}

{% block content %}
{% if article.author.id == user.id %}
    <nav class="UpdateArticle">
        <li><a href="{% url 'articles:edit' slug=article.slug %}" class="ArticleEdit">Edit</a></li>
        <li><a href="{% url 'articles:delete' %}" class="ArticleDelete">Delete</a></li>
    </nav>
{% endif %}
<div class="article-details">
    <div class="article">
        <img src="{{ article.thumb.url }}"/>
        <h2>{{ article.title }}</h2>
        <div class="infos">
            <p>Director: {{ article.director }}</p>
            <p>Protagonist(s): {{ article.protagonist }}</p>
        </div>
        <p>{{ article.body }}</p>
        <p class="author">Created by <br>{{ article.author }}</p>
        <p>{{ article.date }}</p>
    </div>
</div>
{% endblock %}

删除功能还没有实现,现在我把重点放在编辑上。
下面是我的article_edit.html:

{% extends 'default.html' %}

{% block content %}
<div class="edit-article">
    <h2>Edit an article</h2>
    <form class="site-form" action="{% url 'articles:edit' slug=article.slug %}" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Update">
    </form>
</div>
<script src="/static/slugify.js"></script>
{% endblock %}
rxztt3cl

rxztt3cl1#

将示例传递给窗体:

from django.shortcuts import get_object_or_404

@login_required(login_url="/accounts/login/")
def article_edit(request, slug):
    article = get_object_or_404(Article, slug=slug)
    if request.method == 'POST':
        form = forms.CreateArticle(request.GET, request.FILES, instance=article)
        if form.is_valid():
            instance.author = request.user
            form.save()
            return redirect('articles:list')
    else:
        form = forms.CreateArticle(instance=article)
    return render(request, 'articles/article_edit.html', {'form': form})

您可能还希望限制对作者的访问,因此:

from django.shortcuts import get_object_or_404

@login_required(login_url='/accounts/login/')
def article_edit(request, slug):
    article = get_object_or_404(Article, slug=slug, author=request.user)
    if request.method == 'POST':
        form = forms.CreateArticle(request.GET, request.FILES, instance=article)
        if form.is_valid():
            form.save()
            return redirect('articles:list')
    else:
        form = forms.CreateArticle(instance=article)
    return render(request, 'articles/article_edit.html', {'form': form})

然而,这样的视图可以简化为使用简单的**UpdateView**[Django-doc]:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import UpdateView

class ArticleEditView(LoginRequiredMixin, UpdateView):
    login_url = '/accounts/login/'
    model = Article
    form = forms.CreateArticle

如果我们只想限制作者的访问权限:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import UpdateView

class ArticleEditView(LoginRequiredMixin, UpdateView):
    login_url = '/accounts/login/'
    model = Article
    form = forms.CreateArticle

    def get_queryset(self, *args, **kwargs):
        return (
            super().get_queryset(*args, **kwargs).filter(author=self.request.user)
        )

注意FormModelForm通常以…Form后缀结尾,以避免与型号名称冲突,并明确表示我们正在使用 * 表单 。因此,使用ArticleForm可能比使用CreateArticle更好。
注意:通常使用
*get_object_or_404(…)[Django-doc]比直接使用.get(…)**[Django-doc]更好。如果对象不存在,例如用户自己修改了URL,则get_object_or_404(…)将返回 HTTP 404 Not Found 响应,而使用.get(…)将返回 HTTP 500 Server Error

相关问题