Django:同一页面上的帖子表单和帖子列表

我创建了一个具有多个用户的网站,使用图像发布帖子并能够添加/删除朋友。因此,很容易为帖子列表创建两个不同的页面并创建一个新页面。但当然,当你可以在同一个地方阅读帖子并发布新帖子时,它看起来会更好。


据我了解(学习 django 不到一个月),我无法将 2 个视图连接到同一个 url,所以我看到的最合乎逻辑的方法是将 2 个视图连接到一个视图中,我还尝试使用模板继承来渲染通过包含模板发布表单,但实际上它不起作用。


下面你可以看到我的观点、帖子模型和模板。感谢您的关注。


views.py:


from braces.views import SelectRelatedMixin

from . import models

from django.views import generic

from django.contrib.auth.mixins import LoginRequiredMixin


class PostList(SelectRelatedMixin, generic.ListView):

    model = models.Post

    select_related = ('user',)


class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView):

    fields = ('post_message', 'post_image')

    model = models.Post

    select_related = ('user',)


    def form_valid(self, form):

        self.object = form.save(commit = False)

        self.object.user = self.request.user

        self.object.save()

        return super().form_valid(form)

models.py:


import misaka


class Post(models.Model):

    user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'posts')

    posted_at = models.DateTimeField(auto_now = True)

    post_message = models.TextField()

    message_html = models.TextField(editable = False)

    post_image = models.ImageField(upload_to = 'postpics', blank = True)


    def __str__(self):

        return self.post_message


    def save(self, *args, **kwargs):

        self.message_html = misaka.html(self.post_message)

        super().save(*args, **kwargs)


    def get_absolute_url(self):

        return reverse('posts:all')


    class Meta:


        ordering = ['-posted_at']

        unique_together = ['user', 'post_message']

urls.py:


app_name = 'posts'


urlpatterns = [

    path('', views.PostList.as_view(), name = 'all'),

    path('new/', views.CreatePost.as_view(), name = 'create'),

]

post_form.html(模板,允许创建新帖子,将在 post_list.html 中看到):



白衣染霜花
浏览 106回答 3
3回答

炎炎设计

您可以将 post_create_form 与 post_list_view 放在同一页面上,无需为帖子创建创建单独的视图,但您需要创建用于编辑和删除的视图。您可以为所有这些视图提供具有不同 URL 的相同 HTML 页面。在 Class_Based_Views 中使用template_name = 'example/example.html',。我希望我能理解您的问题,如果不能进一步澄清为什么您不能将两个视图合并为一个。

千万里不及你

def posts(request):posts = Post.objects.all()form = PostForm(request.POST or None, request.FILES or None)if request.method == "POST":    if form.is_valid():       ...context={    'posts'         : page_obj,    'create_or_update_post_form' : form,}return  render(request, 'post/posts.html',context)您是否在基于类的视图中很难做到这一点?

慕容3067478

您可以使用基于 django 类的视图轻松完成。创建视图为from django.views.generic import ListViewfrom django.views.generic.edit import CreateViewclass ModelCreate(CreateView):&nbsp; &nbsp; model = ModelName&nbsp; &nbsp; fields = ['field1', 'field2']&nbsp; &nbsp; template_name = 'same_page.html'&nbsp; &nbsp; success_url = reverse_lazy('list_view')class ModelList(CreateView, ListView):&nbsp; &nbsp; model = ModelName&nbsp; &nbsp; fields = ['field1', 'field2']&nbsp; &nbsp; paginate_by = 5&nbsp; &nbsp; template_name = 'same_page.html'&nbsp; &nbsp; def get_context_data(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; context = super().get_context_data(*args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; context['form'] = self.get_form()&nbsp; &nbsp; &nbsp; &nbsp; return context&nbsp; &nbsp; # If form post redirect to ModelCreate View&nbsp; &nbsp; def post(self, request, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; return ModelCreate.as_view()(request)应用程序/urls.pyfrom django.urls import pathfrom app import viewspath('list', views.ModelList.as_view(), name='list_view'),path('add', views.ModelCreate.as_view(), name='add_view'),最后在 templates/same_page.html 中<div class="row">&nbsp; &nbsp;<div class="col-sm-5">&nbsp; &nbsp; &nbsp; <form method="post" enctype="multipart/form-data">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{% csrf_token %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{{form.as_p}}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<button type="submit" value="submit" class="btn btn-primary btn-sm float-right">Submit</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;</form>&nbsp; &nbsp;</div>&nbsp; &nbsp;<div class="col-sm-5">&nbsp; &nbsp; {% if object_list %}&nbsp; &nbsp; &nbsp; &nbsp;{% for object in object_list %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p>{{object.field1}}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p>{{object.field2}}</p>&nbsp; &nbsp; &nbsp; &nbsp;{% endfor %}&nbsp; &nbsp; {% endif %}&nbsp; &nbsp;</div></div>希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python