这是我的models.py:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
utype = models.ForeignKey(Usertype)
school = models.ForeignKey(School)
courses = models.ManyToManyField(Course, related_name='c+', blank=True)
tutors = models.ManyToManyField(Course, related_name='t+', blank=True)
account = models.IntegerField(max_length=20, blank=True, null=True)
cellphone = models.BigIntegerField(max_length=14, unique=True, blank=True, null=True)
credits = models.FloatField(default=0.0)
transactions = models.ManyToManyField(Transaction, related_name='t+', blank=True)
verified = models.BooleanField(default=False)
paypalVerified = models.BooleanField(default=False)
applicationAccepted = models.BooleanField(default=False)
address = models.CharField(max_length=256, blank=True)
apartment = models.CharField(max_length=20, blank=True)
city = models.CharField(max_length=256, blank=True)
state = models.ForeignKey(State, null=True, blank=True)
zip = models.IntegerField(max_length=10, blank=True, null=True)
country = models.ForeignKey(Country, null=True, blank=True)
这是我的forms.py:
class ContactInfoForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ContactInfoForm, self).__init__(*args, **kwargs)
self.fields['cellphone'].label = "Cell Phone Number"
self.fields['address'].label = "Address"
self.fields['apartment'].label = "Apartment"
self.fields['city'].label = "City"
self.fields['state'].label = "State"
self.fields['zip'].label = "Zip Code"
self.fields['country'].label = "Country"
class Meta:
model = UserProfile
fields = ('cellphone', 'address', 'apartment', 'city', 'state', 'zip', 'country')
这是我的views.py:
def profile(request):
c=getUserContext(request)
c['contactInfoForm'] = ContactInfoForm(instance = c['profile'])
if request.method == 'POST':
if request.POST['formType'] == "ContactInfo":
c['contactInfoForm'] = ContactInfoForm(request.POST, instance = c['profile'])
if c['contactInfoForm'].is_valid():
c['contactInfoForm'].save()
return render_to_response('profile.html', c)
如果用户在 ContactInfoForm 的所有字段中都输入了数据,我如何遍历表单中的字段并显示它们的值?
例如我想显示
手机号码 123-456-7890
地址 1 West Spring St ... 等
我无法遍历模型中的字段,因为其中包含许多我不想在个人资料页面的联系人信息部分显示的其他字段。
我已经为此苦苦挣扎了一段时间,但一无所获。如果我的问题不清楚,请告诉我,我将提供更多信息或尝试重新构建问题。
这是我当前在 profile.html 上向用户显示表单的方式:
{% for field in contactInfoForm %}
<tr>
<td class="fieldright">
<label class="inline">{{ field.label_tag }}</label>
</td>
<td>
{% if profile.field %}
<div class="field">
{{ profile.field }}
<input type="hidden" name="{{ field }}" id="id_{{ field }}" value={{ profile.field }}>
</div>
{% else %}
{{ field }}
{% endif %}
</td>
</tr>
{% endfor %}
编辑:我将 profile.field 更改为 field.value,现在正在显示该值。