So , my website has a feature where user can upload an image of themselves for their profile picture when they register their account . The model for the same is as follows :
class Buyer(models.Model):
name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
phone = models.BigIntegerField()
email = models.EmailField(max_length=20)
address = models.CharField(max_length=100)
city = models.CharField(max_length=30)
state = models.CharField(max_length=30)
pincode = models.IntegerField()
dp = models.ImageField(upload_to='user_profile_picture/', blank=True, null=True)
created_on = models.DateField(auto_now_add=True, blank=True, null=True)
created_by = models.OneToOneField(User, related_name='buyer', on_delete=models.CASCADE)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
Now for this model , I have made the following views to extract the relevant data (including images) from the form inside the template when the submit button is pressed
#login_required
def buyer_profile_details(request):
if request.method == 'POST':
# creating the buyer object
firstname = request.POST.get('firstname')
lastname = request.POST.get('lastname')
phone = request.POST.get('phone')
email = request.POST.get('email')
city = request.POST.get('city')
state = request.POST.get('state')
address = request.POST.get('address')
pincode = request.POST.get('pincode')
# dp is the user submitted image which I want to get from the form
dp = request.POST.get('dp')
Buyer.objects.create(name=firstname, last_name=lastname, phone=phone, email=email, address=address,
city=city, state=state, pincode=pincode, dp=dp, created_by=request.user)
UserType.objects.create(user_type=2, created_by=request.user)
return redirect('my_profile')
return render(request, 'new_buyer_profile_details.html', {})
And finally this is the template containing the form that I made for getting the image
<form class="block-register" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-row">
<div class="col form-group">
<label>First name</label>
<input type="text" class="form-control" placeholder="" id="firstname" name="firstname">
</div> <!-- form-group end.// -->
<div class="col form-group">
<label>Last name</label>
<input type="text" class="form-control" placeholder="" id="lastname" name="lastname">
</div> <!-- form-group end.// -->
</div> <!-- form-row end.// -->
<div class="form-row">
<div class="form-group col-md-6">
<label>Phone</label>
<input class="form-control" type="text" id="phone" name="phone">
</div> <!-- form-group end.// -->
<div class="form-group col-md-6">
<label>Email</label>
<input class="form-control" type="email" id="phone" name="email">
</div> <!-- form-group end.// -->
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>City</label>
<input class="form-control" type="text" id="city" name="city">
</div> <!-- form-group end.// -->
<div class="form-group col-md-6">
<label>State</label>
<input class="form-control" type="text" id="state" name="state">
</div> <!-- form-group end.// -->
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Street</label>
<input class="form-control" type="text" id="address" name="address">
</div> <!-- form-group end.// -->
<div class="form-group col-md-6">
<label>Pincode</label>
<input class="form-control" type="number" id="pincode" name="pincode">
</div> <!-- form-group end.// -->
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Display Picture</label>
<input type="file" id="dp" name="dp" accept="image/*">
</div> <!-- form-group end.// -->
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block"> Register </button>
</div> <!-- form-group// -->
<div class="form-group">
<label class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" checked=""> <div class="custom-control-label"> I am agree with terms and contitions </div> </label>
</div> <!-- form-group end.// -->
</form>
When I press submit , all data other than the image is getting stored for some reason . Why is my image not getting submitted ? When I add the image directly from admin panel of django , it gets stored properly to the media/user_profile_picture folder .
You have written this line to get the file from the POST data:
dp = request.POST.get('dp')
But files are not present in request.POST they are present in request.FILES [Django docs] hence you want to change that line to:
dp = request.FILES.get('dp')
Note: It is better to use a Form class [Django docs]
(or a ModelForm [Django
docs])
when dealing with forms in Django as they will automatically clean and
validate the form for you.
In your settings.py file, you need to have the following specified to indicate where user-uploaded files will be stored:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
See the documentation for more details: https://docs.djangoproject.com/en/3.2/ref/settings/
Related
Am working on school database, when I'm trying to submit my django form using pure html form, it throws me an error like this: ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. How can i solve this error please?
Am using this method for the first time:
class PrimaryCreativeView(LoginRequiredMixin, CreateView):
model = Primary
fields = ['profilePicture', 'firstName', 'sureName',
'gender', 'address', 'classOf', 'album',
'hobbies', 'dateOfBirth','year',
'name', 'contact', 'homeAddress',
'emails', 'nationality','occupations',
'officeAddress', 'state', 'localGovernments',
'relationship' ]
template_name = 'post_student_primary.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
form.instance.user = self.request.user
return super (PrimaryCreativeView, self).form_valid(form)
so I changed it to this method down below, but I don't know why it throws me this error:ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. when I submitted the form. How can I solve? And why this error is shown?
my Views:
def primary_submit_form(request):
albums = PrimaryAlbum.objects.filter(user=request.user)
if request.method == 'POST':
addmisssion_number = request.POST.get('addmisssion_number')
profile_picture = request.POST.get('profile_picture', None)
first_name = request.POST.get('first_name')
sure_name = request.POST['sure_name']
gender = request.POST['gender']
address_of_student = request.POST['address_of_student']
class_Of_student = request.POST['class_Of_student']
album = request.POST['album']
date_of_birth = request.POST['date_of_birth']
nationality_of_student = request.POST['nationality_of_student']
state_of_student = request.POST['state_of_student']
local_government_of_student = request.POST['local_government_of_student']
certificate_of_birth_photo = request.FILES.get('certificate_of_birth_photo')
residential_certificate_photo = request.FILES.get('residential_certificate_photo')
name = request.POST['name']
contact = request.POST['contact']
address_2 = request.POST['address_2']
nationality_2 = request.POST['nationality_2']
occupations = request.POST['occupations']
work_address = request.POST['work_address']
state_2 = request.POST['state_2']
local_government_2 = request.POST['local_government_2']
relationship = request.POST['relationship']
student_create = Primary.objects.create(
addmisssion_number=addmisssion_number, profile_picture=profile_picture,
first_name=first_name, sure_name=sure_name, gender=gender, address_of_student=address_of_student,
class_Of_student=class_Of_student, album=album, date_of_birth=date_of_birth,
nationality_of_student=nationality_of_student, state_of_student=state_of_student, local_government_of_student=local_government_of_student,
certificate_of_birth_photo=certificate_of_birth_photo, residential_certificate_photo=residential_certificate_photo,
name=name, contact=contact, address_2=address_2, nationality_2=nationality_2, occupations=occupations, work_address=work_address,
state_2=state_2, local_government_2=local_government_2, relationship=relationship
)
student_create.save()
return redirect('Primary-Albums')
return render(request, 'create_primary_student_information.html', {'albums':albums})
my models:
class PrimaryAlbum(models.Model):
name = models.CharField(max_length=100)
user = models.ForeignKey(User,
on_delete=models.CASCADE)
def __str__(self):
return self.name
class Primary(models.Model):
addminssion_number = models.CharField(max_length=40)
profilePicture = models.FileField(upload_to='image')
first_name = models.CharField(max_length=40)
sure_name = models.CharField(max_length=40)
gender = models.CharField(max_length=25)
address_of_student = models.CharField(max_length=50)
class_Of_student = models.CharField(max_length=20)
date_of_birth = models.CharField(max_length=20)
album = models.ForeignKey(PrimaryAlbum, on_delete=models.CASCADE)
hobbies = models.TextField(blank=True, null=True)
nationality_of_student = models.CharField(max_length=50)
state_of_student = models.CharField(max_length=30)
local_government_of_student = models.CharField(max_length=50)
certificate_of_birth_photo = models.FileField(upload_to='image')
residential_certificate_photo = models.FileField(upload_to='image')
#Guadians
name = models.CharField(max_length=30)
contact = models.CharField(max_length=15)
address_2 = models.CharField(max_length=50)
nationality_2 = models.CharField(max_length=50)
occupations = models.CharField(max_length=50)
work_address = models.CharField(max_length=50)
state = models.CharField(max_length=30)
local_government = models.CharField(max_length=50)
relationship = models.CharField(max_length=25)
def __str__(self):
return str(self.first_name)
My Templates:
<form action="{% url 'Create-Primary-Student' %}" method="POST">
{% csrf_token %}
<div class="container">
<div class="row">
<div class="text-center">
{% for message in messages %}
<h5>{{message}}</h5>
{% endfor %}
</div>
<div class="col-md-4">
<label for="" class="form-label">Admission Number</label>
<input type="text" class="form-control" name="addmission_number">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Profile Picture</label>
<input type="file" class="form-control" name="profile_picture">
</div>
<div class="col-md-4">
<label for="" class="form-label">First Name</label>
<input type="text" class="form-control" name="first_name">
</div>
<div class="col-md-4">
<label for="" class="form-label">Sure Name</label>
<input type="text" class="form-control" name="sure_name">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label"> Gender</label>
<input type="text" class="form-control" name="gender">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Address</label>
<input type="text" class="form-control" name="address_of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Class</label>
<input type="text" class="form-control" name="class_Of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Date Of Birth</label>
<input type="date" class="form-control" name="date_of_birth">
</div>
<div class="col-md-4">
<label for="" class="form-group">Year Of Graduation</label>
<select class="form-select" aria-label="Default select example" name="album">
<option selected>Select Year Of Graduation</option>
{% for album in albums %}
<option value="{{ album.id }}">{{ album.name }}</option>
{% endfor %}
</select>
<br>
</div>
<div class="col-md-4">
<label class="form-label">Example textarea</label>
<textarea class="form-control" rows="3" name="hobbies"></textarea>
<br>
</div>
<div class="col-md-4">
<br>
<label class="form-label">Student Country</label>
<input type="text" class="form-control" name="nationality_of_student">
</div>
<div class="col-md-4">
<br>
<label for="" class="form-label">State Of Origin</label>
<input type="text" class="form-control" name="state_of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Local Government</label>
<input type="text" class="form-control" name="local_government_of_student">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Certificate of Birth Photo</label>
<input type="file" class="form-control" name="certificate_of_birth_photo">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Indigen Photo</label>
<input type="file" class="form-control" name="residential_certificate_photo">
</div>
<div class="text-center">
<br>
<h2>Guidance Information</h2>
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Full Name</label>
<input type="text" class="form-control" name="name">
</div>
<div class="col-md-4">
<label for="" class="form-label">Phone Number</label>
<input type="text" class="form-control" name="contact">
</div>
<div class="col-md-4">
<label for="" class="form-label">Home Address</label>
<input type="text" class="form-control" name="address_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Country</label>
<input type="text" class="form-control" name="nationality_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Occupation</label>
<input type="text" class="form-control" name="occupations">
</div>
<div class="col-md-4">
<label for="" class="form-label">Work Address</label>
<input type="text" class="form-control" name="work_address">
</div>
<div class="col-md-4">
<label for="" class="form-label">State Of Origin</label>
<input type="text" class="form-control" name="state_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Local Government</label>
<input type="text" class="form-control" name="local_government_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Relationship To Student</label>
<input type="text" class="form-control" name="relationship">
</div>
<button type="submit" class="btn btn-success">create album</button>
</div>
</div>
</form>
You create this by assigning it to album_id, not album:
student_create = Primary.objects.create(
addmisssion_number=addmisssion_number,
profile_picture=profile_picture,
first_name=first_name,
sure_name=sure_name,
gender=gender,
address_of_student=address_of_student,
class_Of_student=class_Of_student,
album_id=album,
date_of_birth=date_of_birth,
nationality_of_student=nationality_of_student,
state_of_student=state_of_student,
local_government_of_student=local_government_of_student,
certificate_of_birth_photo=certificate_of_birth_photo,
residential_certificate_photo=residential_certificate_photo,
name=name,
contact=contact,
address_2=address_2,
nationality_2=nationality_2,
occupations=occupations,
work_address=work_address,
state_2=state_2,
local_government_2=local_government_2,
relationship=relationship,
)
I would however strongly advise to use a ModelFormĀ [Django-doc] this will remove a lot of boilerplate code from the view, do proper validation, and create the object effectively.
When I try to do this I get the following error "'BoundField' object has no attribute 'width'".
My model
class Reviews(models.Model):
...
image = models.ForeignKey('wagtailimages.Image',
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name='+')
def __str__(self):
return(self.author)
Save method, error on Image.objects.create
class FeedbackPage(Page):
...
def serve(self, request):
post_data = request.POST or None
review_form_class = ReviewForm
if "review" in request.POST:
review_form = review_form_class(post_data, prefix='review')
new_review = Reviews()
new_review.author = review_form['author']
new_review.is_pub = False
new_review.text = review_form['text']
new_image = Image.objects.create(
file=review_form['file'],
title="Image title"
)
new_review.image = new_image
if new_review.is_valid():
new_review.save()
My form
class ReviewForm(TemplateForm):
file = forms.ImageField()
I used part of code of this answer https://stackoverflow.com/a/42551931/9842214
from wagtail.images.models import Image
def save(self, commit=False):
if not commit:
raise Exception("This form doesn't support save(commit=False)")
# build the instance for this form, but don't save it to the db yet
instance = super(MyForm, self).save(commit=False)
# create the Image object
avatar = Image.objects.create(
file=self.cleaned_data['avatar_image'],
title="Image title"
# you may need to add more fields such as collection to make it a valid image...
)
# attach the image to your final model, and save
instance.avatar = avatar
instance.save()
return instance
def chef_register(request):
if request.method == "POST" and "image" in request.FILES:
fullname= request.POST.get('fullname')
contact = request.POST.get('contact')
license_no = request.POST.get('license_no')
email = request.POST.get('email')
city = request.POST.get('city')
password = request.POST.get('password')
address = request.POST.get('address')
image= request.FILES['image']
restaurent_name = request.POST.get('restaurent_name')
ChefDetailsModel.objects.create(fullname=fullname,contact=contact,license_no=license_no,email=email,city=city,password=password,address=address,logo=image,restaurent_name=restaurent_name)
<section class="py-5 overflow-hidden bg-primary" id="">
<div class="container">
<div class="row flex-center">
<div class="row">
<div class="row" >
<center><h1 style="color:white">Register Now</h1></center><br><br><br>
<form style="border: radius 10px;border-color:white" method="post" enctype="multipart/form-data" name="myform" onsubmit = "return validate()">
{% csrf_token %}
<div>
<center> <div class="row" >
<div class="col-4">
<label class="" for="inputDelivery" style="color:white">FULL NAME</label>
<input class="form-control input-box form-foodwagon-control" name="fullname" id="inputDelivery" type="text" placeholder="Enter Your Name" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">MOBILE NUMBER</label>
<input class="form-control input-box form-foodwagon-control"name="contact" id="inputDelivery" type="text" placeholder="Enter Your Mobile Number" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">License Id</label>
<input class="form-control input-box form-foodwagon-control"name="license_no" id="inputDelivery" type="text" placeholder="Enter Your FSSAI License" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">Email Id</label>
<input class="form-control input-box form-foodwagon-control" name="email" id="inputDelivery" type="text" placeholder="Enter Your Email Address" />
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">CITY</label>
<input class="form-control input-box form-foodwagon-control" name="city" id="inputDelivery" type="text" placeholder="Enter Your City Name" />
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">PASSWORD</label>
<input class="form-control input-box form-foodwagon-control" name="password" id="inputDelivery" type="password" placeholder="Enter Your Password" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">ADDRESS</label>
<input class="form-control input-box form-foodwagon-control" name="address" id="inputDelivery" type="text" placeholder="Enter Your Full Adress" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">Restaurent Name</label>
<input class="form-control input-box form-foodwagon-control" name="restaurent_name" id="inputDelivery" type="text" placeholder="Enter Restaurent Name" /><br>
</div>
<div class="col-4">
<label class="form-label" for="customFile" style="color:white">LOGO</label>
<input type="file" class="form-control" name="image" />
</div>
</div> </center>
</div>
<center><button type="submit" class="btn btn-success">REGISTER NOW</button></center><br>
</form>
</div>
</div>
</div>
</div>
</section>
I have the following ModelForm which when I use as below it is not saving to the database. I have tried other posts and answers on here but cannot get this to save.
If I use the same Class Base View (CreateView) and use the input of {{form}} in the HTML I can get this working and it saves to the database, but I need to have the form fields added separately in the HTML page as below that has been created for me with separate inputs.
The output of the post prints in the terminal ok, but then as mentioned not to the database.
Hope this all makes sense and thanks in advance for any help I can get on this.
models.py
class ASPBookings(models.Model):
program_types = (
('Athlete Speaker & Expert Program', 'Athlete Speaker & Expert Program'),
('Be Fit. Be Well', 'Be Fit. Be Well')
)
presentation_form_options = (
('Face to Face', 'Face to Face'),
('Virtual', 'Virtual'),
)
organisation_types = (
('Goverment School', 'Goverment School'),
('Community Organisation', 'Community Organisation'),
('Non-Goverment School', 'Non-Goverment School'),
('Other', 'Other')
)
contact_name = models.CharField(max_length=80)
program_type = models.CharField(max_length=120,choices=program_types)
booking_date = models.DateField()
booking_time = models.DateTimeField(default=datetime.now())
duration = models.CharField(max_length=10, default="1")
email = models.EmailField()
phone_number = models.CharField(max_length=120)
speaker_brief = models.TextField()
presentation_form = models.CharField(max_length=120, choices=presentation_form_options)
audience_number = models.CharField(max_length=10)
street = models.CharField(max_length=120)
suburb = models.CharField(max_length=120)
region = models.CharField(max_length=50, default="1")
post_code = models.CharField(max_length=40)
organisation_type = models.CharField(max_length=120,choices=organisation_types)
athlete = models.ForeignKey(Athlete, default="13", on_delete=models.CASCADE)
def __str__(self):
return self.contact_name
forms.py
class ASPBookingsForm(forms.ModelForm):
class Meta():
model = ASPBookings
fields = ('__all__')
views.py
class ASPBookingsCreateView(CreateView):
form_class = ASPBookingsForm
model = ASPBookings
template_name = "vistours/bookings_asp.html"
def post(self, request):
if request.method == 'POST':
form = self.form_class(request.POST)
print(request.POST)
if form.is_valid():
program_type = form.cleaned_data['prev_program']
booking_date = form.cleaned_data['prev_date']
booking_time = form.cleaned_data['prev_time']
duration = form.cleaned_data['prev_duration']
street = form.cleaned_data['street']
suburb = form.cleaned_data['suburb']
post_code = form.cleaned_data['postcode']
region = form.cleaned_data['region']
organisation_type = form.cleaned_data['org_type']
audience_number = form.cleaned_data['audience']
presentation_form = form.cleaned_data['presentation_form']
contact_name = form.cleaned_data['contact_name']
email = form.cleaned_data['email']
phone_number = form.cleaned_data['phone']
speaker_brief = form.cleaned_data['comments']
athlete = form.cleaned_data['athlete']
form.save()
return render(request, self.template_name)
HTML
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="utf-8">
<title>Athlete Speaker Program</title>
<!-- VIS Branding -->
<link rel="stylesheet" type="text/css" href="{% static 'vistours/css/vis.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'vistours/css/number-input.css' %}">
<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Bootstrap -->
<link href="{% static 'vistours/css/bootstrap.min.css' %}" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
</head>
<body>
<form method="post" class="needs-validation" novalidate enctype="multipart/form-data">
{% csrf_token %}
<div class="container-fluid pt-3">
<!-- Nav Bar -->
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8"><img alt="VIS Logo" src="https://www.vis.org.au/theme/vis/img/logo.svg" style="height: 50px;" class="img-fluid"></div>
<div class="col-md-2"></div>
</div>
<!-- END Nav Bar -->
<div id="duration_container" class="row py-5">
<div class="col-md-2">
</div>
<div class="col-md-8">
<div class="card">
<h5 class="card-header">Address & Organisation Type</h5>
<div class="card-body">
<h5 class="card-title">Please fill out the address fields</h5>
<p class="card-text">Uncheck the box below if you've already booked a session with us in an earlier date.</p>
<div class="form-floating mb-3">
<input type="text" required class="form-control" id="street" name="street" placeholder="Flinders Street" value={{street}} >
<label for="street">Street</label>
<div class="invalid-feedback">
Please enter a valid street name
</div>
</div>
<div class="form-floating mb-3">
<input type="text" required class="form-control" id="suburb" name="suburb" placeholder="Albert Park" value={{suburb}}>
<label for="suburb">Suburb</label>
<div class="invalid-feedback">
Please enter a valid suburb name
</div>
</div>
<div class="form-floating mb-3">
<input required oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null; if(this.value<0){this.value= this.value =0} else if(this.value>9999){this.value= this.value =9999}
" type="number" min="0" max="9999" class="form-control" id="postcode" name="postcode" placeholder="3000" value={{post_code}}>
<label for="postcode">Post Code</label>
<div class="invalid-feedback">
Please enter a valid post code
</div>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="region" name="region" aria-label="Region" value={{region}}>
<option value="1">Metro</option>
<option value="2" selected>Suburb</option>
</select>
<label for="region">Region</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="org_type" name="org_type" aria-label="Organisation Type" value={{form.organisation_type}}>
<option value="1">Community organisation</option>
<option value="2">Corporation</option>
<option value="3" selected>Government school</option>
<option value="4">Non-Government school</option>
<option value="5">Other</option>
</select>
<label for="org_type">Organisation Type</label>
</div>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
<!-- Next Button DIV -->
<div class="row">
<div class="col-2">
</div>
<div class="col-8">
Next
</div>
<div class="col-2"></div>
</div>
<!-- END Next Button DIV -->
<div class="col-xs-12" style="height:350px;"></div>
<!--Time Container Blank Space-->
<div id="time_container" class="row py-5">
<div class="col-md-2"></div>
<div class="col-md-8">
</div>
<div class="col-md-2"></div>
</div>
<!--END Time Container Blank Space-->
<!-- Time Slots -->
<div class="row pb-5">
<div class="col-md-2">
</div>
<div class="col-md-8">
<div class="card">
<h5 class="card-header">Audience</h5>
<div class="card-body">
<h5 class="card-title">Audience Number</h5>
<p class="card-text">How many people will be attending this conference</p>
<div class="form-floating mb-3">
<input required oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null;if(this.value<0){this.value= this.value =0} else if(this.value>9999){this.value= this.value =9999}
" type="number" min="0" max="9999" class="form-control" id="audience" name="audience" placeholder="0 - 9999" value={{audience_number}}>
<label for="audience">Audience Number</label>
<div class="invalid-feedback">
Please enter a valid audience number
</div>
</div>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
<!-- Next Button DIV -->
<div class="row">
<div class="col-2">
</div>
<div class="col-8">
Next
</div>
<div class="col-2"></div>
</div>
<!-- END Next Button DIV -->
<div class="col-xs-12" style="height:350px;"></div>
<!--END Time Slots-->
<!--Date Container Blank Space-->
<div id="date_container" class="row py-5">
<div class="col-md-2"></div>
<div class="col-md-8">
</div>
<div class="col-md-2"></div>
</div>
<!--END Date Container Blank Space-->
<div class="row pb-5">
<div class="col-md-2">
</div>
<div class="col-md-8">
<div class="card">
<h5 class="card-header">Contact Information</h5>
<div class="card-body">
<h5 class="card-title">Contact info and speaker brief</h5>
<p class="card-text">
Please fill out the contact form and explain what function/class the speaker will be presenting to, what topics you would like the speaker to cover and if you have any requests for type of speaker (male/female/sport/para athlete, etc.) under <em>Speaker Brief</em> section.</p>
<div class="form-floating mb-3">
<select class="form-select" id="presentation_form" name="presentation_form" aria-label="Presentation Form" value={{presentation_form}}>
<option value="1" selected>Face-to-Face</option>
<option value="2">Virtual</option>
</select>
<label for="presentation_form">Preferred Presentation Form</label>
</div>
<div class="form-floating mb-3">
<input required type="text" class="form-control" id="contact_name" name="contact_name" placeholder="John Doe" value={{contact_name}}>
<label for="contact_name">Contact Name</label>
<div class="invalid-feedback">
Please enter a valid contact name
</div>
</div>
<div class="form-floating mb-3">
<input required type="text" class="form-control" id="athlete" name="athlete" placeholder="Athlete Name" value={{athlete}}>
<label for="contact_name">Athlete Name</label>
<div class="invalid-feedback">
Please enter a valid contact name
</div>
</div>
<div class="form-floating mb-3">
<input required type="email" class="form-control" id="email" name="email" placeholder="name#example.com" value={{email}}>
<label for="email">Email</label>
<div class="invalid-feedback">
Please enter a valid email address
</div>
</div>
<div class="form-floating mb-3">
<input required pattern="^((\+61\s?)?(\((0|02|03|04|07|08)\))?)?\s?\d{1,4}\s?\d{1,4}\s?\d{0,4}$" type="text" class="form-control" id="phone" name="phone" placeholder="0400 000 000" value={{phone_number}}>
<label for="phone">Phone</label>
<div class="invalid-feedback">
Please enter a valid phone number
</div>
</div>
<div class="form-floating">
<textarea required class="form-control" placeholder="Leave a comment here" id="comments" name="comments" maxlength="500" value={{speaker_brief}}></textarea>
<label for="comments">Speaker Brief (Max 500 Characters)</label>
<div class="invalid-feedback">
Please explain the topics you want the speaker to present
</div>
</div>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
<!-- Form Validation Alert Box -->
<div class="row py-3" id="alert_box" style="visibility: hidden;">
<div class="col-2">
</div>
<div class="col-8">
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Oops!</strong> Some of the fields above need to be reviewed.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
</div>
<div class="col-2">
</div>
</div>
<!-- END Form Validation Alert Box -->
<!-- Submit Button DIV -->
<div class="row">
<div class="col-2">
</div>
<div class="col-8 d-flex flex-row-reverse">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<div class="col-2">
</div>
</div>
<!-- END Submit Button DIV -->
<div class="col-xs-12" style="height:200px;"></div>
</div>
<!-- hidden inputs -->
<div style="display: none; visibility: hidden;">
<input type="text" name="prev_time" id="prev_time">
<input type="text" name="prev_date" id="prev_date">
<input type="text" name="prev_duration" id="prev_duration">
<input type="text" name="prev_program" id="prev_program">
</div>
</form>
<script src="{% static 'vistours/js/form-validation.js' %}"></script>
<script>
document.getElementById("prev_time").value = sessionStorage.getItem('time');
document.getElementById("prev_date").value = sessionStorage.getItem('date');
document.getElementById("prev_duration").value = sessionStorage.getItem('duration');
document.getElementById("prev_program").value = sessionStorage.getItem('program');
</script>
</body>
</html>
I think your form might be invalid. Try to print form.errors in the else statement corresponding to your if form.is_valid() statement.
One other suggestion is to use Django form to generate the html instead of generating everything by yourself (which is prone to errors and hard to manage). You can still keep the form fields separated. Check out the URL below:
https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html#accessing-the-form-fields-individually
In my django project i have this model:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,)
u_fullname = models.CharField(max_length=200)
u_email = models.EmailField()
u_profile = models.CharField(max_length=1)
u_job = models.CharField(max_length=100, null=True, blank=True, default='D')
u_country = models.CharField(max_length=20, null=True, blank=True, default='Italy')
u_regdata = models.DateTimeField(auto_now=True)
stripe_id = models.CharField(max_length=100, null=True, blank=True)
activation_code = models.CharField(max_length=10)
u_picture = models.ImageField(upload_to='profile_images', blank=True)
u_active = models.BooleanField(default=False)
u_terms = models.BooleanField(default=False)
def __unicode__(self):
return self.u_profile
and a forms.py like this one:
from a_profile.models import UserProfile
class ProfileModelForm(ModelForm):
class Meta:
model = UserProfile
fields = ['u_fullname',
'u_job',
'u_country',
'u_email',
'u_terms',
]
def clean(self):
cleaned_data = super(ProfileModelForm, self).clean()
u_fullname = cleaned_data.get('u_fullname')
u_job = cleaned_data.get('u_job')
u_country = cleaned_data.get('u_country')
u_email = cleaned_data.get('u_email')
u_terms = cleaned_data.get('u_terms')
if not u_terms:
raise forms.ValidationError("Please read and accept our Terms of Service")
if not u_fullname and not u_job and not u_country and not u_terms:
raise forms.ValidationError('You have to write something!')
return cleaned_data
well, now in html i have to use different names for element related to form fields:
<form action="" method="POST">
{% csrf_token %}
{{ form.errors }}
<div class="row">
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="text" name="u_fullname_C" id="u_fullname_c"
placeholder="Company Name">
<i class="la la-building"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<select name="u_country_c" id="u_country_c"
value="{{ form.u_country }}">
<option selected="selected">Italy</option>
<option>Spain</option>
<option>USA</option>
<option>France</option>
</select>
<i class="la la-globe"></i>
<span><i class="fa fa-ellipsis-h"></i></span>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<select name="u_job_c" id="u_job_c" value="{{ form.u_job }}">
<option selected="selected">Technology</option>
<option>Healthcare</option>
<option>Building</option>
<option>Aerospace</option>
</select>
<i class="la la-industry"></i>
<span><i class="fa fa-ellipsis-h"></i></span>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="text" name="u_email_c" id="u_email_c"
placeholder="Enter a valid email"
value="{{ form.u_email }}">
<i class="la la-envelope"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="password" name="u_password_c" id="u_password_c"
placeholder="Password">
<i class="la la-lock"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="password" name="repeat-password_c"
id="repeat-password_c"
placeholder="Repeat Password"
onfocusout="return checkPass('C')">
<i class="la la-lock"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="checky-sec st2">
<div class="fgt-sec">
<input type="checkbox" name="u_terms_c" id="u_terms_c">
<label for="u_terms_c"><span></span></label>
<span></span>
</label>
<small>Yes, I understand and agree to the workwise Terms &
Conditions.</small>
</div><!--fgt-sec end-->
</div>
</div>
<div class="col-lg-12 no-pdd">
<button type="submit" name="company" value="submit"
onclick="return checkUserRegForm('C')">Get Started
</button>
</div>
</div>
</form>
at this point when i run my code and enter data into form, when i Submit i get a form error because forms don't see value into my fields:
ERROR-> {'u_fullname': [ValidationError(['This field is required.'])], 'u_email': [ValidationError(['This field is required.'])], 'all': [ValidationError(['Please read and accept our Terms of Service'])]}
How can i link my form fields name to my html element name value?
So many thanks in advance
Here's a link to docs on the subject rendering fields manually.
I looked for awhile and this is what I came up with. I apologize I left some stuff out. In your view if you are able to get 'country code' options and 'job' options you could look over them in them template.
I added value="{{ form.u_fullname }}", and value="{{ form.u_terms }}".
<form method="" action="">
{% csrf_token %}
{{ form.errors }}
<div class="row">
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type='text' name="u_fullname_C" id="u_fullname_c"
value="{{ form.u_fullname }}" placeholder="">
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<select name="u_country_c" id="">
{% for option in options %}
<option value="{{ option.pk }}">{{ option.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<select name="u_job_c" id="u_job_c" value="{{ form.u_job }}">
{% for job in jobs %}
<option value="{{ job.pk }}">{{ job.name }}</option>
{% endfor %}
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type='text' name='u_email_c' id='u_email_c' placeholder="" value="{{ form.u_email }}">
<i class="la la-envelope"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="password" name="u_password_c" id="u_password_c" placeholder="Password">
<i class=""></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="password" name="repeat-password_c" id="repeat-password_c" placeholder="" onfocusout="return checkPass('C')">
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="checky-sec st2">
<div class="fgt-sec">
<input type="checkbox" value="{{ form.u_terms }}" name="u_terms_c" id="u_terms_c">
<label for="u_terms_c"><span></span>
<span></span>
</label>
<small>Yes, I understand and agree to the workwise Terms &
Conditions.
</small>
</div>
</div>
</div>
<div class="col-lg-12 no-pdd">
<button type='submit' name='company' value='submit' onclick="return checkUserRegForm('C')">
Get Started
</button>
</div>
</div>
</form>
If you are using a class view
class ProfileView(CreateView):
form_class = UserProfileForm
success_url = '/'
def form_valid(self, form):
user_profile = form.save(commit=False)
user_profile.updated = datetime.datetime.now()
user_profile.save()
return super().form_valid(form)
Or a function view:
def user_profile_view(request):
if request.method == 'POST':
form = ProfileModelForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
fullname = cd['u_fullname']
UserProfile.objects.create(user=request.user, u_fullname=fullname)
return redirect('')
else:
form = ProfileModelForm()
Would you be able to provide your views.py file? I'm still semi new to Django so let me know if you are still having troubles.
I am trying to save students from addstudent form but it is not saving students and it is displaying error message 'error in form'.Is there any solutions for this code.I think the error is in html template.
Error is like this:
AttributeError at /students/add/student/
'ErrorDict' object has no attribute 'status_code'
Request Method: POST
Request URL: http://127.0.0.1:8000/students/add/student/
Django Version: 2.1.5
Exception Type: AttributeError
Exception Value:
'ErrorDict' object has no attribute 'status_code'
models.py
class Course(models.Model):
title = models.CharField(max_length=250)
basic_price = models.CharField(max_length=100)
advanced_price = models.CharField(max_length=100)
basic_duration = models.CharField(max_length=50)
advanced_duration = models.CharField(max_length=50)
class Student(models.Model):
name = models.CharField(max_length=100)
course = models.ManyToManyField(Course)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateField()
forms.py
class AddStudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
views.py
def addstudent(request):
courses = Course.objects.all()
if request.method == 'POST':
form = AddStudentForm(request.POST,request.FILES)
if form.is_valid():
student = form.save()
student.save()
messages.success(request,'student saved.')
return redirect('students:add_student')
# else:
# return HttpResponse(form.errors) --> it returns course
else:
form = AddStudentForm()
return render(request,'students/add_student.html',{'form':form,'courses':courses})
add_student.html
<form action="{% url 'students:add_student' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Course <span class="text-danger">*</span></h5>
<div class="controls">
<select name="course" id="select" required class="form-control">
<option value="">Select Your Course</option>
{% for course in courses %}
<option value="{{course.title}}">{{course.title}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<h5>Address<span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="address" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Phone Number <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="phone" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Email <span class="text-danger">*</span></h5>
<div class="controls">
<input type="email" name="email" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Date <span class="text-danger">*</span></h5>
<div class="controls">
<input type="date" name="joined_date" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Image <span class="text-danger">*</span></h5>
<div class="controls">
<input type="file" name="image" class="form-control" > </div>
</div>
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
You should output the value of form.errors as suggested in the comments to discover the exact error. However, I can see two immediate issues that are likely causing form validation to fail.
Firstly, because your form contains an image upload you must set the enctype to multipart/form-data in the template:
<form action="{% url 'students:add_student' %}" method="post" enctype="multipart/form-data">
Second, the uploaded image exists in request.FILES so you need to pass that to the form:
form = AddStudentForm(request.POST, request.FILES)
You have to save many to many field after save method.
if form.is_valid():
student = form.save(commit=False)
student.save()
form.save_m2m()