我创建了一个具有多个用户的网站,使用图像发布帖子并能够添加/删除朋友。因此,很容易为帖子列表创建两个不同的页面并创建一个新页面。但当然,当你可以在同一个地方阅读帖子并发布新帖子时,它看起来会更好。
据我了解(学习 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 中看到):
炎炎设计
千万里不及你
慕容3067478
相关分类