I am having this error local variable 'form' referenced before assignment
. I am not sure what's wrong with the code. The form
does not load and the if the form
is assigned to different variable and used then the page loaded but the form does not load.
My model.py:
from django.db.models.aggregates import Max
from django.db.models.base import Model
from django.db.models.fields import CharField
# Create your models here.
class Work(models.Model):
name = models.CharField(max_length=100)
image = models.ImageField(upload_to='workimages/')
summary =models.CharField(max_length=100)
def __str__(self):
return self.name
class Contact(models.Model):
name = models.CharField(max_length=200, null=True)
email = models.EmailField(max_length=50, null=True)
message = models.CharField(max_length=1000, null= True)
def __str__(self):
return self.name
view.py:
from .models import *
from .forms import *
# Create your views here.
def home (request):
work = Work.objects.all()
if request.method == "POST":
form = Contactform(request.POST or None)
if form.is_valid():
form.save()
context ={ 'work':work,'form':form}
return render(request, 'mysite/index.html',context)
index.html:
<form method="POST">
{% csrf_token %}
<div class="row margin-bottom-small center-xs">
<div class="col-md padding-small">
{{ form }}
</div>
<div class="col-md padding-small">
<!-- <textarea placeholder="Your Message" name="" rows="8"
class="margin-bottom-small"></textarea> -->
<input type="submit" value="Submit">
</div>
</div>
</form>
forms.py :
from django import forms
from django.db.models import fields
from django.forms.forms import Form
from django.forms.models import ModelForm
from django.db import models
from .models import *
class Contactform(ModelForm):
class Meta:
models = Contact
fields = "__all__"
Put else condition.
from .models import *
from .forms import *
def home(request):
work = Work.objects.all()
if request.method == "POST":
form = Contactform(request.POST)
if form.is_valid():
form.save()
context ={ 'work':work,'form':form}
return render(request, 'mysite/index.html',context)
or without else condition:
from .models import *
from .forms import *
def home(request):
work = Work.objects.all()
if request.method == "POST":
if form.is_valid():
form.save()
context ={'work':work,'form':form}
return render(request, 'mysite/index.html',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.