【发布时间】:2016-01-08 22:42:34
【问题描述】:
我正在尝试构建一个表单,但我不确定应该如何正确完成。这些是我的模型:
class Country(models.Model):
name = models.CharField(max_length=250, null=False, blank=False, unique=True)
twocode = models.CharField(max_length=5, null=False, blank=False, unique=True)
class GeoBonus(models.Model):
name = models.CharField(max_length=250)
country = models.ForeignKey(Country, related_name='geo_bonuses')
bookmaker = models.ForeignKey(Bookmaker, related_name='geo_bonuses')
博彩公司有奖金,每个国家都不同。例如:
Bookmaker has bonuses:
Slovakia: "eligible for 100% up to $200"
Afghanistan: "eligible for 100% up to €100!"
USA: "restricted country"
...
我想在 GeoBonus 中将引号中的文本保存为 name。当然我可以写使用简单的模型表格,但我会提交表格 248 次(每个国家)。我想展示每个国家的所有领域。
- 如果
name为空白,则不会创建 GeoBonus。 - 如果
name不为空,则创建 GeoBonus 对象。 这应该是这样的: forms.py 和 views.py 中的代码是什么样的?我还需要编辑字段。
我尝试为国家/地区手动创建新字段:
<form method="post" action="" class="wide">
{% csrf_token %}
{%bootstrap_form form %}
<div class="form-group">
{%for country in countries%}
<label class="control-label" for="{{country.twocode}}">{{country}}</label>
<input class="form-control" id="{{country.twocode}}" maxlength="250" type="text" />
{%endfor%}
</div>
<input type="submit" class="btn btn-default" name="submit" value="Save">
</form>
使用这个 forms.py 类:
class GeoBonusForm(forms.ModelForm):
class Meta:
model = GeoBonus
fields = ['bookmaker']
但request.POST 确实只包含博彩公司字段。
EDIT1:Views.py
@staff_member_required
def geo_bonus_edit(request, bookmaker=None):
template = loader.get_template('geobonus/edit.html')
if request.method == 'POST':
form = GeoBonusForm(request.POST)
print request.POST
else:
form = GeoBonusForm()
context = RequestContext(request, {
'form': GeoBonusForm,
'countries': Country.objects.all(),
})
return HttpResponse(template.render(context))
【问题讨论】:
-
能否添加视图交付模板的代码?
-
@RodrigoDela 我目前没有太多视图代码,不知道应该如何完成。但是添加了视图。
标签: django django-forms