gpt4 book ai didi

python - Django 创建帖子

转载 作者:行者123 更新时间:2023-12-05 01:25:55 26 4
gpt4 key购买 nike

我正在尝试在论坛上创建一个新帖子,它确实有效,我也在打印表单是否有效,但是当我在帖子未发布后去检查时。在管理页面中,帖子在那里,已批准,但缺少标签和类别字段。它们是在创建帖子时添加的,否则我会收到错误消息。但是我必须在管理页面中手动添加它们才能将帖子发布到论坛。

这是我在模型中的帖子

class Post(models.Model):
title = models.CharField(max_length=400)
slug = models.SlugField(max_length=400, unique=True, blank=True)
user = models.ForeignKey(Author, on_delete=models.CASCADE)
content = HTMLField()
categories = models.ManyToManyField(Category)
date = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=True)
tags = TaggableManager()
comments = models.ManyToManyField(Comment, blank=True)
# closed = models.BooleanField(default=False)
# state = models.CharField(max_length=40, default="zero")

def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)

def __str__(self):
return self.title

这是我的views.py

@login_required
def create_post(request):
context = {}
form = PostForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
print("\n\n form is valid")
author = Author.objects.get(user=request.user)
new_post = form.save(commit=False)
new_post.user = author
new_post.save()

return redirect('forums')

context.update({
'form': form,
'title': 'Create New Post'
})
return render(request, 'forums/create_post.html', context)

html 非常简单,可以测试。

<form method="POST">
{% csrf_token %}
{{form|crispy}}
<!-- Submit Post -->
<input type="submit" value="Save">
</form>

如有任何帮助,我们将不胜感激

最佳答案

new_post = form.save(commit=False) 行不会根据 docs 保存多对多关系。 .解决方法

new_post = form.save(commit=False)
new_post.user = author
new_post.save()
form.save_m2m()

摘自 docs

Another side effect of using commit=False is seen when your model hasa many-to-many relation with another model. If your model has amany-to-many relation and you specify commit=False when you save aform, Django cannot immediately save the form data for themany-to-many relation. This is because it isn’t possible to savemany-to-many data for an instance until the instance exists in thedatabase.

To work around this problem, every time you save a form usingcommit=False, Django adds a save_m2m() method to your ModelFormsubclass. After you’ve manually saved the instance produced by theform, you can invoke save_m2m() to save the many-to-many form data.

我认为这并不能解决所有问题,但请尝试一下。

关于python - Django 创建帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70598161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com