我是django的新手,我想用另一個類來擴展用戶模型。但是,我不確定如何讓表單與類設備正常工作。我想要溫度,並在表格中顯示電池。謝謝提前:)在視圖中呈現django窗體
models.py非常
class Device(models.Model):
temperature = models.IntegerField()
battery = models.IntegerField()
class UserProfile(models.Model):
user = models.OneToOneField(User)
deviceNb= models.CharField(max_length=50)
device = models.OneToOneField(Device, null=True)
User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0])
forms.py
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('deviceNb', 'device',)
views.py
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid:
form.save()
#to go back to check that the info has changed
return HttpResponseRedirect('/accounts/loggedin')
else: # when this is a get request
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render(request, 'profile.html', args)
內聯窗體集是答案。從文檔:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets – ivan7707
注意它應該'如果form.is_valid()'。如果你忘記括號並寫入'if form.is_valid',那麼'form.is_valid'將總是*評估爲True。 – Alasdair
感謝您的提示!確實會做出改變。 :) – Rose