Skip to content
Advertisement

Django Model form not rendering

Im trying to create a model form on django but it doesnt want to render even though I mapped it properly and created the path.

models.py

 from django.db import models

 # Create your models here.

 Media_Choices = (
     ("TV", "TV"),
     ("Radio", "Radio"),
     ("Youtube", "Youtube"),
     ("Podcast", "Podcast"),
  )

class Appear(models.Model):
Show = models.CharField(max_length=100)
Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices)
Episode = models.IntegerField()
Date = models.DateField(max_length=100)
Time = models.TimeField(auto_now=False, auto_now_add=False)
Producer = models.CharField(max_length=100)
Producer_Email = models.EmailField(max_length=254)

def __unicode__(self):
    return self.Show + ' ' + self.Producer_Email

forms.py

from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Appear

class AppsForm(ModelForm):
      class Meta:
         model = Appear
         fields = '__all__'

def clean_Producer_Email(self):
    Producer_Email = self.cleaned_data.get('Producer_Email')
    if (Producer_Email == ""):
        raise forms.ValidationError('field cannot be left empty')

    for instance in Appear.objects.all():
        if instance.Producer_Email == Producer_Email:
            raise forms.ValidationError('Please fill in correct email')
    return Producer_Emailenter 

views.py

from django.shortcuts import render
from .forms import AppsForm

# Create your views here.

def AppS(request):
form = AppsForm()
context = {'forms': form}
return render(request, 'AppsForm.html', context)

it refuse to render but it displays the html tag that is in the file but not the fields from the form. this is the html template

AppsForm.html

{% extends 'base.html' %}

{% block content %}

{% load crispy_forms_tags %}

<form action="" method="POST">

    {% csrf_token %}

    {{ form|crispy }}

    <input type="submit" value="submit">
</form>
{% endblock %}

Advertisement

Answer

you view is wrong try this

def AppS(request):
    if request.method == 'POST':
        form = AppsForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = AppsForm()
    return render(request, 'AppsForm.html', {'form': form})

and in your html

<form method="POST" class="" action="">
   {% csrf_token %}
   {{ form|crispy }} 
  <input type="submit" class="" value="Submit"> 
</form>

now you are good to go and tell me if you still get error

Advertisement