我的models.py如下:
from django.db import models
from extensions.models import SipExtension
xmpp_users = SipExtension.objects.values_list('real_name',flat=True)
xmpp_users_choices = [('', 'None')] + [(real_name,real_name) for real_name in xmpp_users]
class xmpp_buddy_groups(models.Model):
group_name = models.CharField(max_length=30)
name = models.CharField(choices=xmpp_users_choices,max_length=100)
def __str__(self):
return '%s %s' % (self.group_name,self.name)
我的forms.py如下:
from django import forms
from .models import xmpp_buddy_groups
from extensions.models import SipExtension
class xmpp_buddy_groups_form(forms.ModelForm):
xmpp_users = SipExtension.objects.values_list('real_name',flat=True)
xmpp_users_choices = [('', 'None')] + [(real_name,real_name) for real_name in xmpp_users]
name = forms.ChoiceField(xmpp_users_choices,required=True, widget=forms.SelectMultiple())
# name = forms.ModelChoiceField(widget=forms.CheckboxSelectMultiple,queryset=SipExtension.objects.values_list('real_name',flat=True),required=True)
class Meta:
model = xmpp_buddy_groups
fields = ['group_name']
我的views.py如下:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from .forms import xmpp_buddy_groups_form
@login_required
def index(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = xmpp_buddy_groups_form(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
#return HttpResponseRedirect('/index.html')
form.save()
# if a GET (or any other method) we'll create a blank form
else:
form = xmpp_buddy_groups_form()
print(form.errors)
return render(request, 'xmpp/index.html', {'form': form})
我的模板index.html位于
之下{% extends 'base.html' %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create Buddy Groups">
</form>
{% endblock %}
感谢帮助我。似乎是模板和模板中通过表单显示的选择的选择不匹配,但我无法弄清楚原因,因为两者是完全相同的选择。
答案 0 :(得分:0)
models.py
from django.db import models
from extensions.models import SipExtension
class xmpp_buddy_groups(models.Model):
group_name = models.CharField(max_length=30)
name = models.ForiegnKey(SipExtension)
def __str__(self):
return '%s %s' % (self.group_name,self.name)
forms.py
from django import forms
from .models import xmpp_buddy_groups
from extensions.models import SipExtension
class xmpp_buddy_groups_form(forms.ModelForm):
class Meta:
model = xmpp_buddy_groups
fields = ['group_name']
def __init__(self, *args, **kwargs):
super(xmpp_buddy_groups_form, self).__init__(*args, **kwargs)
if self.instance:
self.fields['name'].initial = SipExtension.objects.get(pk=self.instance.SipExtension).real_name