Django表单域未显示

人气:398 发布:2022-10-16 标签: forms django field

问题描述

我是Django的新手,我尝试在html文件中显示表单,但在浏览器上转到这个特定页面时看不到这些字段。有人知道为什么吗?

下面是html文件:我可以在其中看到除了显示的表单之外的所有内容 Add_device.html

{% extends 'layout/layout1.html' %}
{% block content %}
    <form action = "userprofile/" method = "post">
        {% csrf_token %}
        {{ form }}
        <input type = "submit" value = "Submit"/>
    </form>
{% endblock %}

forms.py

from django import forms
from models import UserProfile

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

Models.py

from django.db import models
from django.contrib.auth.models import User


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    deviceNb = models.CharField(max_length = 100)

User.profile = property(lambda u : UserProfile.objects.get_or_create(user = u)[0])

views.py

def user_profile(request):
    if request.method == 'POST':
        #we want to populate the form with the original instance of the profile model and insert POST info on top of it
        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:
            #this is the preferred way to get a users info, it is stored that way
            user = request.user
            profile = user.profile
            #if we have a user that has already selected info, it will pass in this info
            form = UserProfileForm(instance=profile)

        args = {}
        args.update(csrf(request))
        args['form'] = form

        print(form)

        return render_to_response('profile.html',args)
我非常确定我的URL文件是正确的,因为我找到了正确的URL,我的问题实际上是表单域没有显示。

非常感谢!!

推荐答案

您的视图缩进不正确。else块属于if request.method == 'POST'语句,并处理GET请求。

您还需要修复方法末尾的缩进,以便为GET和POST请求返回响应。最好使用render而不是过时的render_to_response。这简化了您的代码,因为您不再需要调用args.update(csrf(request))

from django.shortcuts import render

def user_profile(request):
    if request.method == 'POST':
        #we want to populate the form with the original instance of the profile model and insert POST info on top of it
        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:
        #this is the preferred way to get a users info, it is stored that way
        user = request.user
        profile = user.profile
        #if we have a user that has already selected info, it will pass in this info
        form = UserProfileForm(instance=profile)

    args = {}
    args['form'] = form

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

266