简体   繁体   中英

Django not rendering Crispy Form Fields from model

Hi I am a beginner to using django. In my project I am trying to construct a new project form to fill in information to store online. I'm using bootstrap4 as the default template pack in django_crispy_forms. I have been trying to render a form with the crispy tags/filter. I have another form I have used and had success in rendering the fields from a form. However this time I need to render the form from a model. The button and title render on the template but no matter what I try from other examples of modelforms I cant seem to make my fields render to the template like it should. Any help would be greatly appreciated.

my related code is as follows: models.py

from django.db import models

# Create your models here.
class Project(models.Model):
    project_address = models.CharField(max_length=200, null=True)

forms.py

from django import forms
from .models import Project

class projectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = [
            'project_id',
        ]

views.py

from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect #added from enquiry views
from django.shortcuts import render
from django.conf import settings #added from enquiry views

from .models import Project
from .forms import projectForm

def projectinfo(request):
    form = projectForm(request.POST or None)
    context = {}
    template = 'projectinfo.html'
    return render(request,template,context)

html

{% load crispy_forms_tags %}

{% block content %}

            <form action="{% url 'projectinfo' %}" method="POST">{% csrf_token %}
                {{ form|crispy }}               
                <input type="submit" value="Create New Project" class="btn btn-default" role="button" style="background-color: #007bff; color: #ffffff;"/>
            </form>

{% endblock %}

Settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    
    'projects’,
    'crispy_forms',
    
]

Screenshot of button with un-rendered form

I was able to fix it by adding the following template-info in the settings.py:

CRISPY_TEMPLATE_PACK = 'bootstrap4'

You need to include the form in the context:

def projectinfo(request):
    form = projectForm(request.POST or None)
    context = {
        'form': form
    }
    template = 'projectinfo.html'
    return render(request,template,context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM