我试图运行并验证表单,但遇到了一些问题。它不显示表单,而是显示我在表单无效时显示的HttpResponse。
这是我的模特:
class Preference(models.Model):
CLASS_CHOICES = [('1', '1'), ('2', '2'), ('3', '3')]
BOARD_CHOICES = [('C', 'CBSE'), ('I', 'ICSE'), ('S', 'State Board')]
SLOT_CHOICES = [('M', 'Morning'), ('A', 'AfterNoon'), ('E', 'Evening')]
SUBJECT_CHOICES = [('H', 'HINDI'), ('M', 'MATH'), ('E', 'ENGLISH')]
LOCATION_CHOICES = [('M', 'My Home'), ('T', 'I am willing to travel')]
GENDER_CHOICES = [('M', 'Male'), ('F', 'Female'), ('B', 'Both are Fine')]
Class = models.CharField(max_length=2, choices=CLASS_CHOICES, default='1', blank=False)
Board = models.CharField(max_length=2, choices=BOARD_CHOICES, default='C', blank=False)
Subject = models.CharField(max_length=2, choices=SUBJECT_CHOICES, default='M', blank=False)
Frequency = models.IntegerField(default=7)
Slot = models.CharField(max_length=2, choices=SLOT_CHOICES, default='E', blank=False)
Location = models.CharField(max_length=2, choices=LOCATION_CHOICES, default='M', blank=False)
Gender = models.CharField(max_length=2, choices=GENDER_CHOICES, default='M', blank=False)
Address = models.CharField(max_length=250, blank=True)
Travel = models.IntegerField(default=5)
Name = models.CharField(max_length=50, blank=True)
Contact = models.IntegerField(default=100)
这是我的表格:
class PreferenceForm(forms.ModelForm):
class Meta:
model = Preference
fields = ['Class', 'Board', 'Subject', 'Frequency', 'Slot', 'Location', 'Gender', 'Address',
'Travel', 'Name', 'Contact']
widgets = {
'Board': forms.RadioSelect(),
'Subject': forms.CheckboxSelectMultiple(),
'Slot': forms.CheckboxSelectMultiple(),
'Location': forms.CheckboxSelectMultiple(),
'Gender': forms.RadioSelect() }
以下是我的观点:
def pref2(request):
form = PreferenceForm(request.POST or None)
if form.is_valid():
prefer = form.save(commit=False)
prefer.save()
return HttpResponse('Order Complete')
else:
return HttpResponse('Some Problem')
当我运行该应用时,它只会显示一行' Some Problem'没有显示表格。感谢所有帮助/建议。
答案 0 :(得分:0)
嗯,你只返回HttpResponse
。如果您想要返回表单以显示错误,则需要使用render
:
def pref2(request):
form = PreferenceForm(request.POST or None)
if form.is_valid():
prefer = form.save(commit=False)
prefer.save()
# Good practice here would be to flash a message on success
# and on failure.
return render(request, "template.html", { "form": form })