2016-07-12 11 views
0

Я новичок в django и пытаюсь показать форму в html-файле, и я не вижу поля, когда попаду на эту страницу в своем браузере. У кого-нибудь есть идея, почему?Поля формы Django не отображаются

Вот 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-адресов, моя проблема в том, что поля формы не отображаются.

Большое спасибо!

ответ

2

Вы не обращаетесь с запросом GET. Обновить код вида

def user_profile(request): 
    if request.method == 'POST': 
    # your existing code 
    # ..... 
    else : #when its get request 
     form = UserProfileForm(instance=request.user.profile) 
     args = {} 
     args.update(csrf(request)) 
     args['form'] = form 

     return render_to_response('profile.html',args) 

Это пример кода, его можно улучшить.

+0

Спасибо, что это именно то, что проблема была. Спасибо, что заметили и указали, что это работает! – Rose

1

Отпечаток неверен. Блок else принадлежит оператору if request.method == 'POST' и обрабатывает запросы GET.

Вам также необходимо исправить отступ в конце метода, чтобы вы возвращали ответ для запросов на получение и отправку. Лучше использовать 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) 
+1

Большое вам спасибо! Такая тупая ошибка, которую я там сделал :) Спасибо за то, что вы указали это и набросились на нее :) Я очень это ценю. Он работает сейчас! – Rose

1

Вы должны обращаться с запросом GET. Попробуйте это на ваш взгляд:

def user_profile(request): 
    form = UserProfileForm() 
    if request.method == 'GET': 
     # handle GET request here 
     form = UserProfileForm(instance=request.user.profile) 

    elif 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') 
    args = {} 
    args['form'] = form 
    return render_to_response('profile.html',args) 

И в вашем profile.html, вы можете сделать что-то вроде этого:

{{ form.as_p }} 
+0

спасибо alix :) действительно, я не обрабатывал GET правильно, он работает сейчас, спасибо! – Rose

+0

Добро пожаловать. Вы должны проголосовать за вопросы, если поможете вам :) @Rose – alix

Смежные вопросы