I am using js plugin to upload image, first time when i select image from the plugin the form gets submitted. The issue is that i select the image first time but then i don't want that image and i click on it again to upload another image, the form does not get validated and fails to submit.
views.py
class SelectObituaryView(LoginRequiredMixin, TemplateView):
template_name = "website/obituary_select.html"
def get_context_data(self, **kwargs):
context = super(SelectObituaryView, self).get_context_data(**kwargs)
church_id = self.request.session.get('church_id', None)
if church_id:
samples = ObituarySample.objects.filter(organization__id=church_id)
context['obituary_samples'] = samples
context['church_cover'] = self.request.session.get('church_cover', None)
return context
#transaction.atomic
def post(self, request):
print("Entered function")
try:
data = request.POST.copy()
data['organization'] = request.session.get('church_id', None)
data['slug'] = data['name'].replace(' ', '-')
data['funeral_time'] = data['funeral_time'].replace(" ", "")
data['viewing_time'] = data['viewing_time'].replace(" ", "")
if len(request.FILES.getlist('gallery')) > 10:
messages.error(request, "Max gallery images limit exceeded.")
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
obituary_form = ObituaryForm(data=data, files=request.FILES)
# print("obituary form data",data)
print("before is valid")
if obituary_form.is_valid():
print("Inside is_valid")
obituary_instance = obituary_form.save(commit=False)
obituary_instance.image = obituary_instance.obituary_sample.background
obituary_instance.user = request.user
obituary_instance.save()
obituary_instance.update_slug_with_id()
#override profile_image
#imageName = os.path.basename(obituary_instance.profile_image.path)
imgArr = os.path.split(obituary_instance.profile_image.path)
image_data = request.POST['profile_image1']
b = json.loads(image_data)
head, data = b["output"]["image"].split(',')
binary_data = a2b_base64(data)
print(binary_data)
with open(obituary_instance.profile_image.path, 'wb+') as fh:
myfile = File(fh)
myfile.write(binary_data)
imprinted_image_path = apps.obituary.utils.imprint(obituary_instance, obituary_instance.obituary_sample)
# Save imprinted image in db
with open(imprinted_image_path, 'rb') as f:
data = f.read()
file_postfix = datetime.now().strftime("%Y%m%d-%H%M%S")
obituary_instance.image.save("%s%s.jpg" % ('obituary', file_postfix), ContentFile(data))
for gallery_image in request.FILES.getlist('gallery'):
GalleryImage.objects.create(obituary=obituary_instance, image=gallery_image)
return HttpResponseRedirect(reverse('obituary:preview', kwargs={'obituary_id': obituary_instance.id}))
else:
print("else")
messages.error(request, constants.OPERATION_UNSUCCESSFUL)
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
except Exception as e:
print(e)
print("except")
messages.error(request, "Unable to create, Please try again.")
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
html
{% extends "website/base.html" %}
{% load static %}
{% block javascript %}
<script>
// Submit post on submit
{# $('#create_obit').on('submit', function(event){#}
{# event.preventDefault();#}
{# alert("Aamixsh");#}
{# });#}
$("#create_obit").submit(function(evt){
//evt.preventDefault();
if($(this).find('input[name="profile_image"]').val() != "") {
$(this).find('input[name="profile_image"]').attr('name','profile_image1');
$(this).find(".slim").find('input[type="file"]').attr('name','profile_image');
return true;
}
});
$(document).ready(function(){
$('input[type="text"]').attr( 'autocomplete', 'off' );
$('.dateReadonly').attr( 'readonly', 'true' );
});
</script>
{% endblock %}
{% block body_block %}
<!-- Banner Area Start -->
<div class="banner-area">
<div class="overlay"></div>
<div class="img-holder">
<div class="holder"><img src="{{ church_cover }}" alt=""></div>
</div>
<div class="caption">
<div class="holder">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="banner">
<h2>Fill in Loved Ones Details</h2>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="section-space">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="row">
<h3 class="heading-title">Create an Obituary</h3>
<form class="setting-form" id="create_obit" action="{% url 'obituary:select' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
<div class="col-xs-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Name: <input type="text" maxlength="50" name="name" placeholder="Name*" class="form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Funeral Address: <input type="text" maxlength="50" name="address" placeholder="Funeral Address*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Date of Birth: <input type="text" id="datepicker1" name="date_of_birth" placeholder="Date of Birth*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Date of Death: <input type="text" id="datepicker2" name="date_of_death" placeholder="Date of Death*" class="dateReadonly form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Funeral Date: <input type="text" name="funeral_date" id="datepicker3" placeholder="Funeral Date*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Funeral Time: <input type="text" name="funeral_time" id="timepicker" placeholder="Funeral Time*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Surviving Family: <input type="text" maxlength="100" name="family_info" placeholder="spouse Mary Louise, and sons Joe, Ed, and Tim, etc. (Max Limit: 100 Characters)" class="form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Ways To Contribute: <input type="text" maxlength="40" name="memorial_donation_info" placeholder="e.g. Donation url or other Information* (Max Limit: 40 Characters)" class="form-control input-field" >
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Viewing Date: <input type="text" name="viewing_date" id="datepicker4" placeholder="Viewing Date*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Viewing Time: <input type="text" name="viewing_time" id="timepicker2" placeholder="Viewing Time*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Viewing Address: <input type="text" maxlength="50" name="viewing_address" placeholder="Viewing Address*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
Message: <textarea maxlength="500" name="message" id="" cols="30" rows="10" class="form-control input-field" placeholder="Message* (Max Limit: 500 Characters)" required></textarea>
</div>
</div>
</div>
<input type="hidden" name="obituary_sample" value="{{ obituary_form.obituary_sample.value }}" />
</div>
<div class="col-sm-12">
<h3>Upload Obituary Photo</h3>
<div class = "form-group">
Maximum image size is 8 MB. You can rotate and crop the uploaded image by using the control buttons at the bottom of the image.
<!-- original <input type="file" name="profile_image" placeholder="Obituary Image*" class="form-control input-field" required> -->
<input type="file" name="profile_image" placeholder="Obituary Image*" class="slim" required>
</div>
</div>
<div class="col-xs-12">
<h3>Upload Gallery Photos</h3>
<div class="dropzone" id="my-awesome-dropzone">
<div class="fallback">
(Maximum image size should be 8 MB)
<input type="file" name="gallery" multiple class="form-control input-field"/>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input type="checkbox" onchange="document.getElementById('create').disabled = !this.checked;" /> I understand, that the obituary cannot be edited once paid for!
</div>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<button type="submit" id="create" class="btn send-btn" disabled>Create</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Related
I'd like to get data from one form that has multiple textareas inside , In my views: 'compare_ingredients' I've tried requesting data from my form id 'compareform' also the textarea id 'ingredients', but when I enter something into one texture and click on submit it comes back as 'None' when I print. Here is my html and views:
html :
<div class="container-fluid">
<h4>Please enter in your ingredients:</h4>
<h6>(Seperate each item by comma)</h6>
<br>
<button class="add_item">Add Item</button>
<br>
<div class="row row-cols-1 row-cols-md-2 mx-auto">
<form action="{% url 'compare_ingredients' %}" method="POST" name="compareform" id="compare">
{% csrf_token %}
<br>
<button type="submit" class="btn btn-info sub_btn">Submit</button>
<button type="submit" class="btn btn-secondary back_button">
Back
</button>
<br>
<br>
<div class="row form_row">
<div class="col mb-4">
<h5>Item 1</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients1" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
<div class="col mb-4">
<h5>Item 2</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
views.py:
def compare_ingredients(request):
if request.method == "POST":
ingredients = request.POST.get('compareform')
print(ingredients)
return render(request, 'result/compare.html')
ok, I figured it out , the problem was in the html textarea I had the name of the form as 'compareform' when it should have been 'compare' :
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compare"></textarea>
then in my views I did:
ingredients1 = request.POST.get('ingredients1')
i am trying to create edit profile form, in which i am trying to data from edit profile form. i am getting all data in request.POST but i am getting empty {} using request.Files
view.py
class EditProfile(View):
template_name="todo_app/edit_profile.html"
def get(self,request,pk):
if request.user.is_authenticated:
user_id=pk
profile=UserProfile.objects.get(user=user_id)
content={
'profile':profile,
}
return render(request,self.template_name,content)
else:
return redirect('todo_app:login')
def post(self,request,pk):
request_data=request.POST
first_name=request_data.get('first_name')
last_name=request_data.get('last_name')
mob_no=request_data.get('mob_no')
address_1=request_data.get('address_1')
address_2=request_data.get('address_2')
gender=request_data.get('gender')
age=request_data.get('age')
state=request_data.get('state')
city=request_data.get('city')
country=request_data.get('country')
bio=request_data.get('bio')
# profile_pic=request.FILES['profile_pic']
print(request_data)
print("_"*123)
print(request.FILES)
return redirect('todo_app:edit_profile',pk)
and print result on console is
<QueryDict: {'csrfmiddlewaretoken': ['mkfuwR6Uc99svosQvsVpho11JOXOdESSmp2sm1ULDFrFu3UHRrkASTWeSyRwXyzH'], 'first_name': ['upasana'], 'last_name': ['kulshresths'], 'address_1': ['9 Purushottam Nagar'], 'address_2': ['Dayal Bagh'], 'mob_no': ['9087654321'], 'gender': ['Male'], 'age': ['12'], 'state': ['Uttar Pradesh'], 'city': ['Agra'], 'country': ['India'], 'bio': ['Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professo'], 'profile_pic': ['Screenshot from 2021-07-14 16-44-31.png']}>
___________________________________________________________________________________________________________________________
<MultiValueDict: {}>
edit_profile.html
<form method="POST" action="{% url 'todo_app:edit_profile' profile.user.id %}" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="first_name">First name</label>
<input type="text" class="form-control" id="first_name" value="{{profile.user.first_name}}" name="first_name" required>
</div>
<div class="col-md-6 mb-3">
<label for="last_name">Last name</label>
<input type="text" class="form-control" id="last_name" value="{{profile.user.last_name}}" name="last_name" required>
</div>
<div class="col-md-6 mb-3">
<label for="address_1">Address line 1</label>
<input type="text" class="form-control" id="address_1" value="{{profile.address_line_1}}" name="address_1" required>
</div>
<div class="col-md-6 mb-3">
<label for="address_2">Address line 2</label>
<input type="text" class="form-control" id="address_2" value="{{profile.address_line_2}}" name="address_2" required>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="mobile_no">Mobile No</label>
<input type="number" min="6000000000" max="9999999999" value="{{profile.user.mob_no}}" class="form-control" id="mobile_no" name="mob_no" required>
</div>
<div class="col-md-3 mb-3">
<label for="gender">Gender</label>
<select class="custom-select" id="gender" name="gender" required>
<option>Male</option>
<option>Female</option>
<option>🏳️🌈</option>
</select>
</div>
<div class="col-md-3 mb-3">
<label for="age">Age</label>
<input type="number" min="0" max="120" value="{{profile.age}}" class="form-control" id="age" name="age" required>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="State" class="form-label">State</label>
<input type="text" class="form-control" id="State" name="state" value="{{profile.state}}">
</div>
<div class="col-md-3 mb-3">
<label for="city" class="form-label">City</label>
<input type="text" class="form-control" id="city" name="city" value="{{profile.city}}">
</div>
<div class="col-md-3 mb-3">
<label for="country" class="form-label">Country</label>
<input type="text" class="form-control" id="country" name="country" value="{{profile.country}}" >
</div>
</div>
<div class="form-row">
<div class="col-md-10 mb-3">
<label for="bio">Bio</label>
<textarea class="form-control" placeholder="Leave a comment here" id="bio" style="height: 100px" name="bio">{{profile.bio}}</textarea>
</div>
<div class="col-md-2 mb-3 ml-auto mt-4">
<img src="{{profile.profile_pic.url}}" class="rounded-circle" width="100px" alt="...">
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="profile_pc_spam">Profile Pic</span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="profile_pic" name='profile_pic' >
<label class="custom-file-label" for="profile_pic">Choose file</label>
</div>
</div>
<div class="text-center">
<button class="btn my_button_delete mb-4 ustify-content-center" type="submit" >Submit form</button>
</div>
</form>
what am I doing wrong? i don't want to use django forms.
i try to search old question related this problem on stack overflow but i found that every one suggest using django form. if i missed any answer please tag me
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
Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
here is my example how my form feild look like
[enter link description here][1]
<form id="contact-form" method="post" action="/addyourschool/" role="form">
<input type="hidden" name="csrfmiddlewaretoken" value="vhcAZ5w1HpK2mUXMhdqHR1to9Yv2LeOB85E2kR7Z1ZsPo5fjtWZ5P7o23kj8lDsk">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">School Name</label>
<input type="text" name="schoolname" id="product" class="form-control ui-autocomplete-input" placeholder="Type few letter & select from down *" required="required" data-error="Lastname is required." autocomplete="off">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_cfschp">Can't find your School *</label>
<input id="form_cfschp" type="text" name="form_cfschpool" class="form-control" placeholder="Can't find your School *" required="required" data-error="Can't find your School">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Pessonname">Contact person Name *</label>
<input id="Pessonname" type="text" name="Pessonname" class="form-control" placeholder="Contact person Name *" required="required" data-error="Contact person Name ">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="DesignationatSchool">Designation at School(job title at this section) *</label>
<select id="DesignationatSchool" name="DesignationatSchool" class="form-control" required="required" data-error="Designation at School">
<option value=""></option>
<option value="Request principal">Principal</option>
<option value="Request quotation">Founder</option>
<option value="Request order status">Management</option>
<option value="Request copy of an invoice">Teachers</option>
<option value="Other">Others</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Enter your Password *" required="required" data-error="password">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Confirm Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Confirm Password *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email">Email *</label>
<input id="email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tel">Mobile No. *</label>
<input id="tel" type="tel" name="phone" class="form-control" placeholder="Please enter your Mobile No *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="text-center"> <input type="submit" class="btn btn-success btn-send" value="Register"></div>
<div class="text-center">Aready Register / have an account ? Login here</div>
</div>
</div>
</form>
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(max_length=50)
email = forms.EmailField(max_length=50)
subject = forms.CharField(max_length=50)
message = forms.CharField(widget=forms.Textarea)
You have to first create the forms.py file in your app as e.g(contact_us)
from django.shortcuts import render
from django.core.mail import send_mail
from .forms import RegisterForm
from django.http import HttpResponse
Create your views here.
def contact_us(request):
#request for POST
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
sender_name = form.cleaned_data['username']
sender_email = form.cleaned_data['email']
message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('New Enquiry', message, sender_email, ['example#gmail.com'])
return HttpResponse('Thanks for Contacting US')
else:
form = RegisterForm()
return render(request, 'Contactus/contact.html', {'form': form})
After created the forms you have to insert the forms class name in views.py to display the custom form on browser.
#Create Your Template
<form id="contactform" method="POST">
{% csrf_token %}
<div class="column one-second">
{{ form.username }}
</div>
<div class="column one-second">
{{form.email }}
</div>
<div class="column one">
{{ form.subject }}
</div>
<div class="column one">
{{ form.message }}
</div>
<div class="column one">
<input type="submit" value="submit">
</div>
</form>
After this you have to call the form in template. To display your own custom form.
As i did above.
Building an Employee application, After updating an Employee using a form, it just shows this error and the Url seems correct so I can really say where the error is coming from
I've crosschecked all my url patterns my views and my url in the form and also tried using the solution in this question, this gives me a bigger error
urls.py
urlpatterns = [
path('edit/<int:pk>/', views.edit, name = 'edit'),
]
views.py
#login_required(login_url='/accounts/login')
def edit(request, pk):
employ = get_object_or_404(Employee, id=pk)
logging.info(type(employ))
departments = Department.objects.all()
context = {
'employ': employ,
'departments':departments
}
if request.method == "POST":
first_name = request.POST['first_name']
last_name = request.POST['last_name']
name = last_name +' '+first_name
employee_id = request.POST['employee_id']
email = request.POST['email']
department = Department.objects.get(dept_name = request.POST['department'])
address = request.POST['address']
employment_type = request.POST['employment_type']
employment_status = request.POST['employment_status']
role = request.POST['role']
marital_status = request.POST['marital_status']
gender = request.POST['gender']
join_date = request.POST['join_date']
end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date']
location = request.POST['location']
credentials = request.POST['credentials']
passport = request.POST['passport']
hod = request.POST['hod']
phone_number = request.POST['phone_number']
date_of_birth = request.POST['date_of_birth']
date_added = datetime.now()
if Employee.objects.filter(employee_id = employee_id).exists() or Employee.objects.filter(email = email).exists():
messages.error(request, 'That ID/Email is Taken')
return redirect('edit')
else:
employee = Employee(first_name='first_name',last_name='last_name',email='email',
employee_id='employee_id',department='department',address='address',employment_type='employment_type',
employment_status='employment_status',role='role',marital_status='marital_status',gender='gender',join_date='join_date',
end_date='end_date',location='location',credentials='credentials',passport='passport',hod='hod',
phone_number='phone_number',date_added='date_added',date_of_birth='date_of_birth')
employee.save()
messages.success(request, 'Employee Created')
return redirect('all')
return render(request, 'employees/edit.html', context, employ)
edit.html
<form method = 'POST' action="{% url 'edit' pk=employ.pk %}" class="m-b-30" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for='first_name' class="control-label">First Name <span class="text-danger">*</span></label>
<input name='first_name' class="form-control" type="text" required value="{{employ.first_name}}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='last_name' class="control-label">Last Name</label>
<input name='last_name' class="form-control" type="text" required value="{{employ.last_name }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employee_id' class="control-label">Employee ID <span class="text-danger">*</span></label>
<input name='employee_id' class="form-control" type="number" required value="{{employ.employee_id }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='email' class="control-label">Email <span class="text-danger">*</span></label>
<input name='email' class="form-control" type="email" required value="{{employ.email }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='phone_number' class="control-label">Phone Number</label>
<input name='phone_number' class="form-control" type="text" required value="{{employ.phone_number }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='gender' class="control-label">Gender</label>
<select name = 'gender' class="form-control" value = "{{employ.gender}} " type="text" >
<option>select gender</option>
{% if employ.gender == 'Male' %}
<option selected ='selected'>Male</option>
{% else %}
<option selected ='selected'>Female</option>
{% endif %}
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='marital_status' class="control-label">Marital Status</label>
<select name='marital_status' class="form-control" value = "{{employ.marital_status}} " type="text" >
{% if employ.marital_status == 'Married' %}
<option selected ='selected'>Married</option>
{% else %}
<option selected ='selected'>Single</option>
{% endif %}
<option>select martial status</option>
<option>Married</option>
<option>Single</option>
<option>Single</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='date_of_birth' class="control-label">Date of Birth <span class="text-danger">*</span></label>
<input name='date_of_birth' class="form-control" type="date" required value="{{employ.date_of_birth|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='address' class="control-label">Address </label>
<input name='address' class="form-control" type="text" required value="{{employ.address }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='department' class="control-label">Department <span class="text-danger">*</span></label>
<select name = 'department' type="text" class="form-control" value = "{{employ.department}} " >
<option>select department</option>
{% for department in departments %}
{% if employ.department == department %}
<option selected ='selected'>{{employ.department}}</option>
{% endif %}
<option>{{department.dept_name}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employment_type' class="control-label">Employment Type </label>
<select id= "employment_type" name='employment_type' type="text" class="form-control" value = "{{employ.employment_type}} " >
{% if employ.employment_type == 'Contract' %}
<option selected ='selected'>Contract</option>
{% elif employ.employment_type == 'Fulltime' %}
<option selected ='selected'>Fulltime</option>
{% else %}
<option selected ='selected'>Intern</option>
{% endif %}
<option>select employment type</option>
<option>Contract</option>
<option>Fulltime</option>
<option>Intern</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='join_date' class="control-label">Join Date <span class="text-danger">*</span></label>
<input name='join_date' class="form-control " type="date" required value="{{employ.join_date|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6" id="end_date">
<div class="form-group">
<label for='end_date' class="control-label">End Date <span class="text-danger">*</span></label>
<input name='end_date' class="form-control " type="date" value="{{employ.end_date|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employment_status' class="control-label">Employment Status </label>
<select name='employment_status' type="text" class="form-control" value="{{employ.employment_status}}" >
{% if employ.employment_status == 'Active' %}
<option selected ='selected'>Active</option>
{% else %}
<option selected ='selected'>Inactive</option>
{% endif %}
<option>select employment status</option>
<option>Active</option>
<option>Inactive</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='role' class="control-label">Role </label>
<input name='role' class="form-control" type="text" required value="{{employ.role }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='location' class="control-label">Work Location </label>
<input name='location' class="form-control" type="text" required value="{{employ.location }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='hod' class="control-label">HOD </label>
<select name='hod' class="form-control" type="text" >
<option>Select HOD</option>
{% for department in departments %}
{% if employ.department.lead == department.lead %}
<option selected ='selected'>{{employ.department.lead}}</option>
{% endif %}
<option>{{department.lead}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='passport' class="control-label">Upload passport </label>
<input name='passport' type="file" accept="image/*" value="{{employ.passport }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='credentials' class="control-label">Add Credentials </label>
<input name='credentials' type="file" accept="image/*" value="{{employ.credentials }}">
</div>
</div>
</div>
<div class="m-t-20 text-center">
<button class="btn btn-primary">Update Employee</button>
</div>
</form>
it's meant to be submitted and routed to edit.hmtl in case there's any error while submitting
When you redirect to the edit view, you need to pass the primary key.
return redirect('edit', pk=employ.pk)
As an aside, it's not recommended to access values from request.POST directly. Have a look at Django forms.