即使在 django 中保存表单后,标签也不会存储在数据库中

Tags are not being stored in the database even after saving form in django

views.py

def post(request):
    if request.method == 'POST':
        form = PostModelForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            # using the for loop i am able to save the tags data.
            # for tag in form.cleaned_data['tags']:
            #    post.tags.add(tag)
            images = request.FILES.getlist('images')
            for image in images:
                ImagesPostModel.objects.create(post=post, images=image)
        return redirect('/Blog/home/')
    else:
        form = PostModelForm(request.POST)
        return render(request, 'post.html', {'form': form})

models.py

class PostModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_time = models.DateTimeField(auto_now_add=True)
    title = models.TextField(null=True)
    body = models.TextField(null=True)
    tags = TaggableManager()
    def __str__(self):
        return str(self.user)

post.html

{% extends 'base.html' %}

{% block content %}

<form action="{% url 'post' %}" enctype="multipart/form-data" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="file" multiple name="images">
    <input type="submit">
</form>

{% endblock %}

输入数据后,数据会存储在标签字段中,但不会保存在数据库中。 我可以成功地通过管理面板手动插入数据,但不能以非员工用户的身份插入数据。 我已经安装了 taggit 并将其放在 settings.py 中的 installed_apps 中。 在 for 循环中使用 post.tags.add(tag) 保存标签。代码有什么问题?

这是因为您对表单使用了 commit=False:那么表单无法保存 many-to-many 字段。也没有必要这样做,您可以使用:

def post(request):
    if request.method == 'POST':
        form = PostModelForm(request.POST)
        if form.is_valid():
            form<strong>.instance.user = request.user</strong>  # set the user
            post = form.save()  # save the form
            ImagesPostModel.objects.bulk_create([
                ImagesPostModel(post=post, images=image)
                for image in request.FILES.getlist('images')
            ])
        return redirect('/Blog/home/')
    else:
        form = PostModelForm()
    return render(request, 'post.html', {'form': form})

Note: Models normally have no Model suffix. Therefore it might be better to rename PostModel to Post.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.