首页 \ 问答 \ 用于ManyToMany字段的Django表单(Django Form for ManyToMany fields)

用于ManyToMany字段的Django表单(Django Form for ManyToMany fields)

我必须在我的博客中设计一个用于添加新帖子的表单。

Model.py

class Category(models.Model):
    title = models.CharField(max_length=200)
    ...
    ...
    def __unicode__(self):
        return self.title

class Post(models.Model):

    title = models.CharField(max_length=80)
    pub_date = models.DateTimeField()
    text = models.CharField(max_length=140)
    ...

    categories = models.ManyToManyField(Category, blank=True, null=True, through='CategoryToPost')

    def __unicode__(self):
        return self.title

class CategoryToPost(models.Model):

    post = models.ForeignKey(Post)
    category = models.ForeignKey(Category)

Views.py

def add_post(request):

form = PostForm()
if request.method == "POST":
    form = PostForm(request.POST)
    if form.is_valid():
        form = PostForm(request.POST)
        post = form.save(commit=False)
        post.author = User.objects.get(id = request.user.id)
        post.categories = post.categorytopost_set
        ...
        post.save()
        return HttpResponseRedirect('/')
    else:
        return render(request, 'add_post.html', {'error': True, 'form': form})
else:
    return render(request, 'add_post.html', {'error': True, 'form': form})

Form.py

class PostForm(ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text', 'categories', 'tags')

当我尝试在模板“add_post.html”的新帖子中插入catogories时,总会有错误引用ManyToMany:

“无法在指定中间模型的ManyToManyField上设置值。请改用CategoryToPosts Manager。”


I have to design a form for add a new post in my blog.

Model.py

class Category(models.Model):
    title = models.CharField(max_length=200)
    ...
    ...
    def __unicode__(self):
        return self.title

class Post(models.Model):

    title = models.CharField(max_length=80)
    pub_date = models.DateTimeField()
    text = models.CharField(max_length=140)
    ...

    categories = models.ManyToManyField(Category, blank=True, null=True, through='CategoryToPost')

    def __unicode__(self):
        return self.title

class CategoryToPost(models.Model):

    post = models.ForeignKey(Post)
    category = models.ForeignKey(Category)

Views.py

def add_post(request):

form = PostForm()
if request.method == "POST":
    form = PostForm(request.POST)
    if form.is_valid():
        form = PostForm(request.POST)
        post = form.save(commit=False)
        post.author = User.objects.get(id = request.user.id)
        post.categories = post.categorytopost_set
        ...
        post.save()
        return HttpResponseRedirect('/')
    else:
        return render(request, 'add_post.html', {'error': True, 'form': form})
else:
    return render(request, 'add_post.html', {'error': True, 'form': form})

Form.py

class PostForm(ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text', 'categories', 'tags')

When I try to insert catogories in new post from template "add_post.html" there is always an error refers to ManyToMany:

"Cannot set values on a ManyToManyField which specifies an intermediary model. Use CategoryToPosts Manager instead."


原文:https://stackoverflow.com/questions/28743843
更新时间:2022-04-09 20:04

最满意答案

我通过将INCLUDE PATH包含在VDK目录中解决了这个问题。


I have solved the problem by including INCLUDE PATH as the VDK directory.

相关问答

更多
  • 我通过在这里找到的评论中使用@vsz建议的答案来解决OP的问题。 我有两个工具包,一个用于本地桌面,一个用于Target_ARM设备,我想要一种轻松构建这两种工具的方法,而无需专门修改.pro文件或其他任何东西。 我遵循链接的答案,并添加以下内容: 在我的桌面工具包(用于调试和发布)中,我在qmake构建步骤中添加了CONFIG+=Desktop作为额外的qmake参数。 对于Target_ARM套件,我在同一个位置添加了CONFIG+=Target_ARM 。 现在,这是事情从链接的答案转移到OP的问题的 ...
  • 使用File | New File或Project在Qt Creator中创建新项目,从Projects列表中选择Other Project ,然后选择Import Existing Project ,然后单击Choose ...按钮。 然后选择包含SDK示例的文件夹,单击下一步 ,然后单击完成 。 点击左侧的项目 (或按下Ctrl + 5),然后在工具链组合中选择Microsoft Visual C ++ 。 现在点击构建环境下的细节 ,检查清除系统环境和变量及其值如下: COMSPEC C:\Win ...
  • 我觉得我们需要一步一步地尝试解决您正在观察的错误。 我看到你使用的是Qt 5.6.0,我建议你通过执行以下命令在你的Ubuntu机器上更新你的Mesa Package : sudo apt-get install libgl1-mesa-dev 这应解决您正在观察的类似下面的错误: /usr/bin/ld: cannot find -lGL collect2: error: ld returned 1 exit status The process "/usr/bin/make" exited with ...
  • 我通过将INCLUDE PATH包含在VDK目录中解决了这个问题。 I have solved the problem by including INCLUDE PATH as the VDK directory.
  • 首先,让我们澄清一些基础知识: openfire是一个XMPP服务器。 基本上,这就是服务器端所需的基本VoIP支持。 替代品包括ejabberd和Prosody 。 jitsi meet essentialy已经是一个VoIP应用程序,所以如果你想开发自己的,你真的不需要它。 另一方面,“Jitsi Videobridge”可用于为视频会议提供中继服务器。 对于使用简单VoIP应用程序的第一步,您也不需要,但如果您希望您的用户能够与许多参与者一起创建视频会议,那么这会有所帮助。 (说明:通常,当您创建P2 ...
  • 我有同样的问题。 尝试从BIN文件夹中选择“qmake.exe”,而不是qmake文件夹,所以在你的情况下可能是P:\ Qt \ Libs \ 4.8.4 \ bin \ qmake.exe Based on SO: How to install Qt on Windows after building? I eventually got to http://qt-project.org/doc/qt-4.8/install-win.html Simply running configure solved ...
  • 您可以在Qt Creator中使用或不使用Qt,使用或不使用C ++编译器,使用或不使用cmake二进制文件等。 Qt Creator使用工具包作为(多个)项目中一起使用的东西的集合,因此您不必一次又一次地定义这些相同的设置。 套件中可用的设置取决于您启用的插件,如果未设置某些信息,Creator非常高兴 - 只要您正在处理的项目不需要此信息。 因此,如果你打开一个基于qmake的项目,如果一个工具包没有设置Qt版本(这是提供qmake二进制文件),创建者会抱怨。 如果您尝试打开基于cmake的项目,那么C ...
  • 灵感来自AlexandreP回答和Twofold-Qt项目的.travis.yml文件,非常感谢Stephan Binner 。 language: cpp matrix: include: - os: linux dist: trusty sudo: required compiler: gcc env: - QT_BASE=48 - os: linux dist: trusty sudo: required compiler: ...
  • 您需要使用CMAKE_PREFIX_PATH 。 例如: cmake.exe -DCMAKE_PREFIX_PATH="C:/path/to/Qt/5.X/compiler/lib/cmake" You need to use CMAKE_PREFIX_PATH. For example: cmake.exe -DCMAKE_PREFIX_PATH="C:/path/to/Qt/5.X/compiler/lib/cmake"
  • 还有另一种方法可以通过将PDB复制到CRM / bin并附加到异步(或沙箱)工作进程来调试 (指向最后的指令)。 我不确定哪种方式更容易......我将不得不尝试Piyush的方式,但由于工具包,我不再使用RegistrationTool了: 按照设置说明进行调试后效果很好,但复制PDB文件仍然是手动步骤。 另请注意,沙盒进程(Microsoft.Crm.Sandbox.WorkerProcess)直到运行插件后才会启动,因此您必须至少调用一次(或另一个)才能进行调试。 I found out what t ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)