django ModelForm 使用 ManyToManyField 保存问题

发布于 2024-10-07 05:46:24 字数 3440 浏览 2 评论 0原文

我是 Django 新手,需要一些帮助来解决我遇到的视图错误。

我编写了一个视图,如果请求方法是 GET,则显示“组”的数据表;如果请求方法是 POST(要编辑的项目通过 POST 数据传递),则显示编辑特定“组”的表单。

另外,如果对现有项目进行 POST,我希望表单中预先填充该项目表中已有的数据。我几乎已经把所有内容都记下来了,除了当我去保存编辑过的表单时,我不断收到此错误:

“无法在指定中间模型的 ManyToManyField 上设置值”

任何帮助将不胜感激。另外,我对所有这些网络开发东西都很陌生,所以如果我做了一些完全愚蠢的事情或者错过了一个概念,请随意相应地批评我。 ;-)

模型

class Alias(models.Model):
    def __unicode__(self):
        return unicode(self.alias)
    alias = models.CharField(max_length=32)

class Octet(models.Model):
    def __unicode__(self):
        return unicode(self.num)
    num = models.IntegerField(max_length=3)

class Group(models.Model):
    def __unicode__(self):
        return unicode(self.name)
    name = models.CharField(max_length=32) #name of the group
    id = models.AutoField(primary_key=True) #primary key
    octets = models.ManyToManyField(Octet, through='OctetAssignment', blank=True) #not required
    aliases = models.ManyToManyField(Alias, through='AliasAssignment', blank=True) #not required

class OctetAssignment(models.Model):
    octet = models.ForeignKey(Octet) #octet
    group = models.ForeignKey(Group) #group that octet is assigned to

class AliasAssignment(models.Model):
    alias = models.ForeignKey(Alias)
    group = models.ForeignKey(Group)

视图

def index(request):
    if request.method == 'GET':
        groups = Group.objects.all().order_by('name')
        return render_to_response('groups.html', 
                                  { 'groups': groups, }, 
                                  context_instance = RequestContext(request),
                                  )

    elif request.method == "POST":
        g = Group.objects.get(id=request.POST['id'])
        form = GroupEditForm(instance=g)
        return render_to_response('groups.html',
                                 { 'form': form,  },
                                 context_instance = RequestContext(request),
                                 )

def save(request):
    if request.method == "POST":
        form = GroupEditForm(request.POST)
        if form.is_valid():
            form.save()

        return HttpResponseRedirect('/tradedesk/groups/') # Redirect after POST

为了使其完整,这里是我正在使用的用于呈现表格和编辑页面的表单模板代码。 模板

    <h1>Group Information</h1>

    {% if groups %}
        <table border=1>

        {% for group in groups %}

        <tr>

        <td>{{group.name}}</td>

        <td>{% for octet in group.octets.all %} {{octet}} {% endfor %}</td>

        <td>{% for alias in group.aliases.all %} {{alias}} {% endfor %}</td>

        <td>{{group.analyst}}</td>

        </tr>

        {% endfor %}

        </table>
    <br></br>

    <form method="post" action="/groups/">{% csrf_token %}
    <select name="id" >
        {% for group in groups %}
        <option value="{{group.id}}">{{group.name}}</option>
        {% endfor %}
    </select>
    <input type="submit" value="Edit">

    </form>
    {% endif %}


    {% if form %}
    <form method="post" action="/groups/save/">{% csrf_token %}

        {{form}}
    <br></br>
    <input type="submit" value="Save">
    <form>

    {% endif %}



</div>

I'm new to Django and was needing some help on a view error i am getting.

I wrote a view that will display a data table of "Groups" if the request method is GET, or display a form to edit a particular "Group" if the request method is POST (item to edit is passed with POST data).

Also, if POST on an existing item, i'd like the form to be pre-populated with the data i already have in the table for that item. I've pretty much got it all down, except when i goto save an edited form, i keep getting this error:

"Cannot set values on a ManyToManyField which specifies an intermediary model"

Any help would be greatly appreciated. Also, I'm new to all this web dev stuff, so if i'm doing something completely silly or am missing a concept, please feel free to flame me accordingly. ;-)

Model

class Alias(models.Model):
    def __unicode__(self):
        return unicode(self.alias)
    alias = models.CharField(max_length=32)

class Octet(models.Model):
    def __unicode__(self):
        return unicode(self.num)
    num = models.IntegerField(max_length=3)

class Group(models.Model):
    def __unicode__(self):
        return unicode(self.name)
    name = models.CharField(max_length=32) #name of the group
    id = models.AutoField(primary_key=True) #primary key
    octets = models.ManyToManyField(Octet, through='OctetAssignment', blank=True) #not required
    aliases = models.ManyToManyField(Alias, through='AliasAssignment', blank=True) #not required

class OctetAssignment(models.Model):
    octet = models.ForeignKey(Octet) #octet
    group = models.ForeignKey(Group) #group that octet is assigned to

class AliasAssignment(models.Model):
    alias = models.ForeignKey(Alias)
    group = models.ForeignKey(Group)

View

def index(request):
    if request.method == 'GET':
        groups = Group.objects.all().order_by('name')
        return render_to_response('groups.html', 
                                  { 'groups': groups, }, 
                                  context_instance = RequestContext(request),
                                  )

    elif request.method == "POST":
        g = Group.objects.get(id=request.POST['id'])
        form = GroupEditForm(instance=g)
        return render_to_response('groups.html',
                                 { 'form': form,  },
                                 context_instance = RequestContext(request),
                                 )

def save(request):
    if request.method == "POST":
        form = GroupEditForm(request.POST)
        if form.is_valid():
            form.save()

        return HttpResponseRedirect('/tradedesk/groups/') # Redirect after POST

To make it complete, here is the form template code i'm using that renders the table and edit page.
Template

    <h1>Group Information</h1>

    {% if groups %}
        <table border=1>

        {% for group in groups %}

        <tr>

        <td>{{group.name}}</td>

        <td>{% for octet in group.octets.all %} {{octet}} {% endfor %}</td>

        <td>{% for alias in group.aliases.all %} {{alias}} {% endfor %}</td>

        <td>{{group.analyst}}</td>

        </tr>

        {% endfor %}

        </table>
    <br></br>

    <form method="post" action="/groups/">{% csrf_token %}
    <select name="id" >
        {% for group in groups %}
        <option value="{{group.id}}">{{group.name}}</option>
        {% endfor %}
    </select>
    <input type="submit" value="Edit">

    </form>
    {% endif %}


    {% if form %}
    <form method="post" action="/groups/save/">{% csrf_token %}

        {{form}}
    <br></br>
    <input type="submit" value="Save">
    <form>

    {% endif %}



</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墟烟 2024-10-14 05:46:24

尝试删除中间模型 OctetAssignment 和 AliasAssignment。仅当您想要向其中添加自定义字段时才应使用它们。否则,Django 会自行创建并透明地使用它们。

Try to remove the intermediary models OctetAssignment and AliasAssignment. They should be used only when you want to add custom fields to them. Otherwise Django creates them and uses them transparently by itself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文