如何将ManaToManyField中的数据从窗体转换到Django视图中?

2024-09-29 23:19:22 发布

您现在位置:Python中文网/ 问答频道 /正文

型号.py

class Posts(models.Model):
   """model for CreatePost"""
   author = models.CharField(max_length=100, null=False, blank=False)

   blog_title = models.CharField(max_length=100, null=False, blank=False)

   sub_catagory = models.ManyToManyField('SubCatagory')

   post_cover_image = models.ImageField(upload_to='post_cover_images', null=False, blank=False)

   post_discription = HTMLField(max_length=5000, null=False, blank=False, help_text='Enter the detailed post in max. 5000 characters')

   date_published = models.DateField(null=False, blank=False)

class Catagory(models.Model):
   """model for Catagory"""
   name = models.CharField(max_length=150, help_text='Enter a ctagory for blogpost')

class SubCatagory(models.Model):
   """model for subcatagories"""
   catagory = models.ForeignKey('Catagory', on_delete=models.CASCADE)
   sub_catagory_name = models.CharField(max_length=150, help_text='Enter subcatagory')

表单.py

class PostCreationForm(forms.ModelForm):
    class Meta:
        model = Posts
        fields = ('blog_title', 'sub_catagory', 'post_cover_image', 'post_discription')

视图.py

@login_required
def createpost(request):
    if request.method=="POST":
        PostForm = PostCreationForm(request.POST, request.FILES)

        if PostForm.is_valid():

            postcont = Posts()

            if request.user.is_authenticated:
                postcont.blog_title = PostForm.cleaned_data['blog_title']
                postcont.post_cover_image = PostForm.cleaned_data['post_cover_image']
                postcont.post_discription = PostForm.cleaned_data['post_discription']
                postcont.author = request.user.username
                postcont.sub_catagory = PostForm.cleaned_data['sub_catagory']
                postcont.date_published = datetime.date.today()
                postcont.save()

                return HttpResponseRedirect(reverse('postcreationsuccessful'))
            else:
                return HttpResponseRedirect(reverse('createpost'))

    else:
        PostForm = PostCreationForm()

    return render(request, 'createpost.html', {'PostForm':PostForm})

模板

{% extends "base_generic.html" %}

{% block title %}<title>Create Post</title>{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="row w-100">
            <div class="col-md-3">

            </div>
            <div class="col-md-6 shadow-sm p-3 mb-5 bg-white rounded">
                <form method="POST" enctype="multipart/form-data" action="{% url 'createpost' %}">{% csrf_token %}
                    <div class="row">
                        {% load bootstrap %}
                        <div class="col-md-12">
                            {{ PostForm.blog_title|bootstrap }}
                        </div>
                        <div class="col-md-12">
                            {{ PostForm.post_cover_image|bootstrap }}
                        </div>
                        <div class="col-md-12">
                            {{ PostForm.sub_catagory|bootstrap }}
                        </div>
                        <div class="col-md-12">
                            {{ PostForm.post_discription }}
                        </div>
                        <div class="col-md-12">
                            <input type="submit" value="Post">
                        </div>
                    </div>
                </form>
            </div>

            <div class="col-md-3">

            </div>
        </div>
    </div>
 {% endblock %}

我的问题是我在帖子和子标签中有很多关系。作为子标签,可以有许多帖子。我想获得用户选择的类别,并希望使用views.py函数将它们保存在模型中

我想问我怎么能做到。当我尝试这样做时:

postcont.sub\u catagory=PostForm.cleaned\u data['sub\u catagory']

我得到以下错误:

/posts/createpost处的TypeError/ 禁止直接分配到多对多集合的前端。请改用sub\u catagory.set()

任何人请救命


Tags: divfalsedatatitlemodelsrequestcolcover
1条回答
网友
1楼 · 发布于 2024-09-29 23:19:22

正如错误所说,问题在于这条线:

postcont.sub_catagory = PostForm.cleaned_data['sub_catagory']

sub_categoryManyToManyField,因此不能直接将其设置为对象。您可以使用postcont.sub_category.set(PostForm.cleaned_data['sub_category']),但这仍然不是很优雅

您的视图实际上不必对对象的所有字段进行修补。我们可以让表单完成工作:

@login_required
def createpost(request):
    if request.method=="POST":
        post_form = PostCreationForm(request.POST, request.FILES)

        if post_form.is_valid():
            post_form.instance.auther = request.user.usernamepostcont.instance.date_published = datetime.date.today()post_form.save()
            return redirect('postcreationsuccessful')
    else:
        post_form = PostCreationForm()

    return render(request, 'createpost.html', {'PostForm': post_form})

一些附加说明:

  1. if request.user.is_authenticated是无用的,因为@login_required装饰器已经检查过了
  2. 如果authorUser,在这里使用ForeignKey(User, ...)更好
  3. 可以对date_published = models.DateField(auto_add_now=True, null=False)字段使用date_published,以确保“date\u published”自动设置为对象构造的日期
  4. 通过在表单无效的情况下不重定向,您实际上可以呈现带有错误的表单,这样用户就可以修复表单,然后重新提交;以及
  5. 您可以使用return redirect(..),它是包装在HttpResponseRedirect(..)对象中的reverse(..)的快捷方式

相关问题 更多 >

    热门问题