tags:

views:

92

answers:

1

Hi, i'm trying to write a very simple django app. I cant get it to show my form inside my template.

<form ...>
{{form.as_p}}
</form>

it shows absolutely nothing. If I add a submit button, it only shows that.

Do I have to declare a form object that inherits from forms.Form ? Cant it be done with ModelForms?

[UPDATE]Solved! (apologize for wasting your time)

In my urls file I had:

(r'login/$',direct_to_template,   {'template':'register.html'}

Switched to:

(r'login/$','portal.views.register')

And yes, I feel terrible.

Background:

I have a Student model, and I have a registration page. When it is accessed, it should display a textfield asking for students name. If the student completes that field, then it saves it.

#models.py

class Student(models.Model):
   name = models.CharField(max_length =50)

#forms.py
class StudentForm (forms.ModelForm):
   class Meta:
       model = Student

So, here is my view:

def register(request):                                                                                                                                   
          if request.method == 'POST':
                  form = StudentForm(request.POST)
                  if form.is_valid():
                          form.save()
                          return render_to_response('/thanks/')
          else:

                  student = Student()
                  form = StudentForm(instance =student)

          return render_to_response('register.html',{'form':form})
+1  A: 

The problem is in your view. You will have no existing student object to retrieve from the database. The following code sample will help you implement an "create" view.

As a side note, you might like using the direct_to_template generic view function to make your life a bit easier.

def add_student(request):
    if request.method == 'POST':
      form = StudentForm(request.POST)
      if form.is_valid():
        new_student = form.save()

        return HttpResponseRedirect('/back/to/somewhere/on/success/')
    else:
      form = StudentForm()

    return direct_to_template(request,
                              'register.html',
                              {'form':form})
wlashell
thanks, but the form still isn't displayed the first time I access the URL. Will look at your tips though.
Tom
Im sorry, you are absolutely right.
Tom