2016-07-12 111 views
0

我是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) 
+0

內聯窗體集是答案。從文檔:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets – ivan7707

+1

注意它應該'如果form.is_valid()'。如果你忘記括號並寫入'if form.is_valid',那麼'form.is_valid'將總是*評估爲True。 – Alasdair

+0

感謝您的提示!確實會做出改變。 :) – Rose

回答

1

UserProfile形式取出device場 - 您要編輯現有設備,而不是將其更改爲其他設備副。

class UserProfileForm(forms.ModelForm): 
    class Meta: 
     model = UserProfile 
     fields = ('deviceNb',) 

然後創建設備表單。

class DeviceForm(forms.ModelForm): 
    class Meta: 
     model = Device 
     fields = ('temperature', 'battery',) 

然後更新您的視圖來處理兩種形式。例如,您需要實例化兩個表單,檢查兩個表單是否有效,如果兩個表單都有效,則保存這些表單等。如果device不存在,您可以使用commit=False保存配置文件表單以獲取profile,設置設備,然後最終保存配置文件。

def user_profile(request): 
    user = request.user 
    profile = user.profile 
    device = profile.device 
    if request.method == 'POST':    
     form = UserProfileForm(request.POST, instance=profile) 
     device_form = DeviceForm(request.POST, instance=device) 

     if form.is_valid() and device_form.is_valid(): 
      device = device_form.save() 
      profile = form.save(commit=False) 
      profile.device = device 
      profile.save() 
      #to go back to check that the info has changed 
      return HttpResponseRedirect('/accounts/loggedin') 

    else: # when this is a get request 
     form = UserProfileForm(instance=profile) 
     device_form = DeviceForm(instance=device) 

    args = {} 
    # Delete the following line - you don't need it now that you use render 
    # args.update(csrf(request)) 
    args['form'] = form 
    args['device_form'] = device_form 

    return render(request, 'profile.html', args) 

最後,在您的模板中,在同一個<form>標記中包含兩個表單。

<form method='post'> 
    {{ form }} 
    {{ device_form }} 
    <input type="submit" value="submit" /> 
</form> 
+0

:)非常感謝你!它工作完美。 – Rose