Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数据从表单中的ManaToManyField获取到Django视图中?_Python_Django_Django Models_Django Forms_Django Views - Fatal编程技术网

Python 如何将数据从表单中的ManaToManyField获取到Django视图中?

Python 如何将数据从表单中的ManaToManyField获取到Django视图中?,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,型号.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(

型号.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')
class PostCreationForm(forms.ModelForm):
    class Meta:
        model = Posts
        fields = ('blog_title', 'sub_catagory', 'post_cover_image', 'post_discription')
@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})
forms.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')
class PostCreationForm(forms.ModelForm):
    class Meta:
        model = Posts
        fields = ('blog_title', 'sub_catagory', 'post_cover_image', 'post_discription')
@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})
视图.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')
class PostCreationForm(forms.ModelForm):
    class Meta:
        model = Posts
        fields = ('blog_title', 'sub_catagory', 'post_cover_image', 'post_discription')
@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 %}
{%extensed“base_generic.html”%}
{%block title%}创建帖子{%endblock%}
{%block content%}
{%csrf_令牌%}
{%load bootstrap%}
{{PostForm.blog_title | bootstrap}}
{{PostForm.post_cover_image|bootstrap}
{{PostForm.sub|catogory | bootstrap}}
{{PostForm.post_description}}
{%endblock%}
我的问题是,我在帖子和子标签中有很多关系。作为子标记,可以有许多帖子。我希望获得用户选择的类别,并希望使用views.py函数将它们保存在模型中

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

postcont.sub_catagory=PostForm.cleaned_数据['sub_catagory']

我得到以下错误:

/posts/createpost处的类型错误/ 禁止直接分配到多对多集合的前端。改为使用sub_catagory.set()


任何人都请帮忙

正如错误所说,问题在于这一行:

postcont.sub_catagory = PostForm.cleaned_data['sub_catagory']
sub_category
是一个
ManyToManyField
,因此不能直接将其设置为对象。您可以使用
postcont.sub\u category.set(PostForm.cleaned\u data['sub\u 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.username
            postcont.instance.date_published = datetime.date.today()
            post_form.save()
            return redirect('postcreationsuccessful')
    else:
        post_form = PostCreationForm()

    return render(request, 'createpost.html', {'PostForm': post_form})
@需要登录\u
def createpost(请求):
如果request.method==“POST”:
post_form=PostCreationForm(request.post,request.FILES)
如果post\u表单有效():
post_form.instance.auther=request.user.username
postcont.instance.date_published=datetime.date.today()
post_form.save()
返回重定向('postcreationsuccessful')
其他:
post_form=后创建表单()
返回呈现(请求'createpost.html',{'PostForm':post\u form})
一些额外的评论:

  • if request.user.is\u authenticated无效,因为
    @login\u required
    装饰程序已经检查了这一点
  • 如果
    作者
    用户
    ,最好在此处使用
    外键(用户,…)
  • 您可以使用
    date\u published=models.DateField(auto\u add\u now=True,null=False)
    作为
    date\u published
    字段,以确保“date\u published”自动设置为构建对象的日期
  • 通过在表单无效的情况下不重定向,您实际上可以呈现带有错误的表单,这样用户就可以修复表单,然后重新提交;及
  • 您可以使用
    返回重定向(..)
    ,它是
    反向(..)
    的快捷方式,包装在
    HttpResponseRedirect(..)
    对象中

  • 等等,你自己根据表单构造了一个实例?为什么?在
    有效后,您可以使用
    PostForm.save()
    ,而且最好使用小写变量,因此
    PostForm
    。如果使用PostForm.save()语句,我将无法将发布日期和用户名保存到模型中。您只需先构造一个对象,然后用
    表单中的
    instance=my\u object
    传递它。此外,您可以将
    date\u published
    设置为
    日期字段(auto\u add\u now=True)
    ,这样它会自动将日期设置为构建实例的日期。我尝试了。它对保存许多字段选择有用吗?