将另一个模型添加到表单?

时间:2015-06-20 15:53:19

标签: django django-forms django-views

我正在尝试设置一个从2个模型中抽取字段的表单。

我厌倦了将模型添加到一起,如下所示但仍然出错。

model = Server, Tag

后端管理员选择了两个模型之间的关系,我可以从后端更新它,但是通过表单我很难将两者结合起来。

views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.forms import ModelForm

from servers.models import Server
from servers.models import Tag

class ServerForm(ModelForm):
    class Meta:
        model = Server, Tag
        fields = ['name', 'order', 'first_name']

def server_list(request, template_name='servers/server_list.html'):
    servers = Server.objects.all()
    data = {}
    data['object_list'] = servers
    return render(request, template_name, data)

def server_create(request, template_name='servers/server_form.html'):
    form = ServerForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('server_list')
    return render(request, template_name, {'form':form})

def server_update(request, pk, template_name='servers/server_form.html'):
    server = get_object_or_404(Server, pk=pk)
    form = ServerForm(request.POST or None, instance=server)
    if form.is_valid():
        form.save()
        return redirect('server_list')
    return render(request, template_name, {'form':form})

def server_delete(request, pk, template_name='servers/server_confirm_delete.html'):
    server = get_object_or_404(Server, pk=pk)    
    if request.method=='POST':
        server.delete()
        return redirect('server_list')
    return render(request, template_name, {'object':server})

models.py

from django.db import models
from django.core.urlresolvers import reverse

class Tag(models.Model):
    slug = models.SlugField(max_length=200, unique=True)

    def __str__(self):
        return self.slug

class Server(models.Model):
    name = models.CharField(max_length=200)
    order = models.IntegerField()
    first_name = models.CharField(max_length=250, blank=True, null=True)
    tags = models.ManyToManyField(Tag)

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('server_edit', kwargs={'pk': self.pk})

server_form.py

<form method="post">{% csrf_token %}
<!--     {{ form.as_p }}  this brings in the whole form-->

    Name <br>
    {{ form.name }} <br>
    Order <br>
    {{ form.order }} <br>
    First name <br>
    tag <br>
    {{ form.tag }} <br> <!--trying to get tag to work through this form-->
    {{ form.first_name }} <br><br>


    <input type="submit" value="Submit" />
</form>

<table cellpadding="0" cellspacing="0">

我正在努力让{{form.tag}}部分工作,并且表单可以识别这种关系。

非常感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:0)

您不能使用此语法在表单中使用多个模型。 Admin后端广泛使用InlineModelFormSet来处理这种关系。看看https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#inline-formsets