【发布时间】:2014-03-26 16:37:32
【问题描述】:
今天我试图获取并打印我所有用户的电子邮件,他们选择了“Value1”。
这就是我的 model.py 的样子:
from django.db import models
class Vartotojas(models.Model):
email = models.EmailField()
option = models.CharField(max_length=30)
Forms.py:
from django import forms
from emailai.models import Vartotojas
class VartotojasForm(forms.Form):
email = forms.EmailField(max_length=100)
my_field = forms.MultipleChoiceField(choices=(('Value1','Value1'),('Value2','Value2')), widget=forms.CheckboxSelectMultiple())
def save(self):
mymodel = Vartotojas(
email=self.cleaned_data['email'],
option=self.cleaned_data['my_field'],
)
mymodel.save()
最后是我的views.py"
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from emailai.models import Vartotojas
from renginiai.forms import VartotojasForm
def name(request):
if request.method == 'POST':
form = VartotojasForm(request.POST)
if form.is_valid():
a = Vartotojas.objects.filter(option="u'Value1'") # How to do it right?
# Now How To Get those object emails?
new_user = form.save()
return render(request, "Vartotojas-result.html", {
'form': form, #BLABLABLA,
})
else:
form = VartotojasForm()
return render(request, "Vartotojas-form.html", {
'form': form,
})
我在 views.py 中评论了我的问题。我希望你能帮助我。提前谢谢!
我用 getlist 重写了我的代码。现在看起来像这样:
views.py:
if form.is_valid():
email = form.cleaned_data['email']
option = request.POST.getlist('my_field')
new_user = form.save(email, option)
forms.py:
email = forms.EmailField(max_length=100)
my_field = forms.MultipleChoiceField(choices=(('Value1','Value1'),('Value2','Value2')), widget=forms.CheckboxSelectMultiple())
def save(self, email, option):
mymodel = Vartotojas(
email=email,
option = option,
)
mymodel.save()
如您所见,我只粘贴了最重要的地方。顺便说一句,用户可以选择 2 个值,这就是我使用复选框的原因。但是还是不行。
【问题讨论】:
-
你用 option='Value1' 过滤所有值对吗?现在你有满足该选项的对象列表。您可以遍历该列表并使用点运算符获取电子邮件属性,例如,a[i].email 其中 i 是列表 a 的索引。
-
以及如何打印到模板上?
-
您必须将其添加到您传递给
render的字典中,但不要按照评论的建议进行操作;我下面的回答会直接给你列表并保存循环。 -
option="u'Value1'"看起来很奇怪。你不是说option=u'Value1'? -
是的,我认为你是对的,但仍然 - 它不起作用:(