Annie Shlepak
Annie Shlepak

Reputation: 103

Django form doesn't show up

I'm working on some project and ended up with some issues. So my form doesn't display itself at all in my template. But I've created another form before and it works as it should!

So my code:

models.py

class Project(models.Model):
    class Meta:
        db_table = "project"

    COLORS = (
        ('R', 'Red'),
        ('B', 'Blue'),
        ('G', 'Green'),
        ('Y', 'Yellow')
     )
    project_title = models.CharField(max_length=200)
    project_color = models.CharField(max_length=1, choices=COLORS)

    def __str__(self):
        return self.project_title

forms.py

class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = ['project_title', 'project_color']

views.py

def addproject(request):
    if request.POST:
        form_p = ProjectForm(request.POST)
        if form_p.is_valid():
            form_p.save(commit=False)
            return HttpResponseRedirect('/')
   else:
        form_p = ProjectForm()
    context = {
        'projects': Project.objects.all(),
        "form": form_p,
        'username': auth.get_user(request).username,
    }
    context.update(csrf(request))
    return render(request, 'index.html', context)

urls.py

urlpatterns = [
    url(r'^addproject/$', views.addproject, name='addproject'),]

index.html

<form action="/addproject/" method="post">
    {% csrf_token %}
    {{ form_p.as_table }}
    <button type="submit" class="btn btn-primary">Add Project</button>
</form>

Upvotes: 2

Views: 4634

Answers (3)

ErfanSafarzad7
ErfanSafarzad7

Reputation: 129

Make sure you are using "ModelForm" instead "Form"

class NewAccountForm(forms.ModelForm):
    class Meta:
        model = NewAccount
        fields = ('name',)

Upvotes: 2

Bernardo Duarte
Bernardo Duarte

Reputation: 4264

The problem is within your template, you are calling your context variable as form_p while passing it as "form":

index.html

<form action="/addproject/" method="post">
    {% csrf_token %}
    {{ form.as_table }}
    <button type="submit" class="btn btn-primary">Add Project</button>
</form>

Upvotes: 5

n1cko_r
n1cko_r

Reputation: 382

Have you imported the form in to the views.py? place this in to your views.py

from .forms import ProjectForm

Upvotes: 0

Related Questions