Django ModelForm无法在模板中呈现

时间:2014-10-01 16:33:29

标签: python django django-forms django-templates django-views

我在这里看了几个答案,但我无法解决这个问题。我正在尝试创建一个模型表单,以便在用户注册网站后保存用户的个人资料。问题是,当我尝试渲染表单时,我得到一个空白页面,没有错误。任何帮助将不胜感激。

models.py

class Perfil(models.Model):
    user = models.OneToOneField(User)
    Sexo = models.CharField(max_length=100)
    Direccion = models.CharField(max_length=100)
    CP = models.CharField(max_length=100)
    Ciudad = models.CharField(max_length=100)
    Estado = models.CharField(max_length=100)
    Pais = models.CharField(max_length=100)
    Telefono = models.CharField(max_length=100)
    Celular = models.CharField(max_length=100)
    PaisPasaporte = models.CharField(max_length=100)
    NumeroPasaporte = models.CharField(max_length=100)
    VigenciaPasaporte = models.DateField(max_length=100)
    ContactoEmergencia = models.CharField(max_length=100)
    TelefonoEmergencia = models.CharField(max_length=100)
    CorreoEmergencia = models.CharField(max_length=100)
    Alergias = models.CharField(max_length=500)

forms.py

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Perfil

views.py

@verified_email_required()
def profile(request):
    if request.method == "POST":
        form = ProfileForm(request.POST)
        if form.is_valid():
            perfil = form.save(commit=False)
            perfil.user = request.user
            perfil.save()
            return HttpResponseRedirect("/profile/")
        else:
            return render(request, "explore/profile.html", {"form": form})
    return render(request, "explore/profile.html")

最后是我的HTML

<form class="profile" id="profile_form" method="post" action="" style="width: 50%;">
                {% csrf_token %}
                {% for field in form %}
                    <table>
                    <colgroup>
                        <col style="width: 45%;">
                        <col style="width: 10%;">
                        <col style="width: 45%;">
                    </colgroup>
                    <tr>
                        <td>{{ field.label_tag }}</td>
                        <td></td>
                        <td>{{ field }}</td>
                    </tr>
                    </table>
                {% endfor %}
            </form>

谢谢!

1 个答案:

答案 0 :(得分:5)

当请求类型为POST时,您将在上下文中发送表单。第一次加载页面时,默认情况下它是GET请求。因此问题

这样的事情应该有效:

def profile(request):
    form = ProfileForm()
    if request.method == "POST":
        form = ProfileForm(request.POST)
        if form.is_valid():
            perfil = form.save(commit=False)
            perfil.user = request.user
            perfil.save()
            return HttpResponseRedirect("/profile/")

    return render(request, "explore/profile.html" {'form': form})

请注意,您根本不需要else子句 - 如果表单无效,它会自动在上下文中发送错误的表单,并且您的错误消息会正常显示。