Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['employees\\/edit\\/(?P<pk>[0-9]+)\\/$'] - django

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.

Related

My urls is not updating correctly adding some extra path itself

I want to update the leads while doing so
If you look on the url section it says update_lead/1 which is perfectly right but when i hit update lead i am getting extra update lead in the url section due to which django cant reach its function i am very confuse about it please help
here are my codes from update_lead.html
{% extends 'base.html' %}
{% block exhead %}
{% endblock exhead %}
{% block body %}
<div class="container">
<h2>Update Lead</h2>
<form action="update_lead_handle" method="POST">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Name</label>
<input type="text" class="form-control" id="inputEmail4" required name="name" value="{{lead.name}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Subject</label>
<input type="text" class="form-control" id="inputPassword4" name="subject" required value="{{lead.subject}}">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Email</label>
<input type="email" class="form-control" id="inputAddress" name="email" placeholder="abc#email.com" value="{{lead.email}}">
</div>
<div class="form-group col-md-6">
<label for="inputAddress2">Contact Number</label>
<input type="number" class="form-control" id="inputAddress2" name="number"value = "{{lead.mobile_no}}" placeholder="99XX80XXXX">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="inputState">Source</label>
<select id="inputState" class="form-control" name="source" >
<option selected value="{{lead.source}}">{{lead.source}}</option>
{% for x in source %}
<option value="{{x.name}}">{{x.name}}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState">Assign To</label>
<select id="inputState" class="form-control" name="assign">
<option selected value="{{lead.assign_to}}">{{lead.assign_to}}</option>
{% for x in agent %}
<option value="{{x.name}}">{{x.name}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="inputState">Status</label>
<select data-target="secondList" class="firstList selectFilter form-control" name="state">
<option selected value="{{lead.state}}">{{lead.state}}</option>
<option data-ref="one">Fresh</option>
<option data-ref="two">Open</option>
<option data-ref="pending">Pending</option>
<option data-ref="close">Close</option>
</select>
<!-- <select id="subject" class="form-control" name="source" >
<option selected value="{{lead.state}}">{{lead.state}}</option>
</select> -->
</div>
<div class="form-group col-md-4">
<label for="inputState">If Pending / Close</label>
<select data-target="thirdList" class="secondList selectFilter form-control" name="pending_close">
<option value="-1">Select</option>
<option data-ref="A" data-belong="close">We Cant Do</option>
<option data-ref="A" data-belong="close">Low Budget</option>
<option data-ref="B" data-belong="close">Client Converted</option>
<option data-ref="C" data-belong="pending">Pending With Customer</option>
<option data-ref="D" data-belong="pending">Pending On Us</option>
<option data-ref="E" data-belong="pending">Pending With Process</option>
<!-- <option data-ref="F" data-belong="three">Second Three</option> -->
</select>
<!-- <select id="topic" class="form-control" name="assign">
<option selected value="{{lead.assign_to}}">{{lead.assign_to}}</option>
</select> -->
</div>
</div>
<!-- <div class="form-group">
<label for="exampleFormControlTextarea1">Initial Followup</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="followup" value=""></textarea>
</div> -->
<button type="submit" class="btn btn-primary">Update Lead </button>
</form>
</div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(".selectFilter").on("change", function () { var e = $(this).data("target"), i = $(this).find(":selected").data("ref"); $("select." + e).val("-1"), null == i ? $("select." + e).find("option").each(function () { console.log("inside undefined"), $(this).removeAttr("disabled hidden") }) : $("select." + e).find("option").each(function () { var e = $(this).data("belong"), t = $(this).val(); i != e && -1 != t ? ($(this).prop("disabled", !0), $(this).prop("hidden", !0)) : ($(this).prop("disabled", !1), $(this).prop("hidden", !1)) }) });
</script>
{% endblock body %}
here are my codes from urls.py
from django.contrib import admin
from django.urls import path
from home import views
urlpatterns = [
path('',views.index,name="index"),
# create agent
path('create_agent_page',views.create_agent_page,name="create_agent_page"),
path('create_agent',views.create_agent,name="create_agent"),
path('signup_page',views.signup_page,name="signup_page"),
path('login_page',views.login_page,name="login_page"),
path('signup_handle',views.signup_handle,name="signup_handle"),
path('login_handle',views.login_handle,name="login_handle"),
path('logout_handle',views.logout_handle,name="logout_handle"),
#Lead handleing
path('create_lead',views.create_lead_page,name="create_lead"),
path('follow_up/<int:id>',views.follow_up,name="follow_up"),
path('update_lead/<int:id>',views.update_lead,name="update_lead"),
path('update_lead_handle',views.update_lead_handle,name="update_lead_handle"),
# path('update_lead',views.update_lead,name="update_lead"),
path('creat_handle_lead',views.creat_handle_lead,name="creat_handle_lead"),
path('lead_list',views.lead_list,name="lead_list"),
]
here are the two views which are requested
def update_lead(request,id):
leads = Lead.objects.get(id = id)
followup = Followup.objects.all
agent = Agent.objects.all
source = Source.objects.all
print(f"the leads are {leads}")
context = {"lead":leads,"followup":followup,"agent":agent,"source":source}
# context = {"lead":leads,"followup":followup}
return render(request,"home/update_lead.html",context)
def update_lead_handle(request):
if request.method == "POST":
organization=get_object_or_404(Organization,user=User.objects.get(username=request.user.username))
name = request.POST.get('name')
subject = request.POST.get('subject')
email = request.POST.get('email')
subject = request.POST.get('subject')
number = request.POST.get('number')
assign= request.POST.get('assign')
source_o= request.POST.get('source')
followup= request.POST.get('followup')
status= request.POST.get('state')
pending_close= request.POST.get('pending_close')
x = Lead.objects.update(name=name,organ = organization,mobile_no = number,source = source_o,subject = subject,message = followup,email= email,assign_to = assign,state = status,closed_or_pending = pending_close)
x.save()
return HttpResponse("The lead has been updated successfully")
else:
return HttpResponse("Babe you are going wrong ")
Kindly put a slash before the update_lead_handle in your form action let it be "/update_lead_handle"

how to creater a signup register form with my own reqired field form in django?

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.

Django forms using html elements with different name from moels field

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.

Django image upload with js plugin issue

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 %}

form data is not received

I am using Django and Bootstrap on frontend to write a single profile editing module.
Plain form from Django is ugly, so I did some custimizing on the form. Here is the HTML form:
<form actoin="{% url 'edit_profile' %}" method="post">
{% csrf_token %}
<div class="form-group row">
<label for="chineseName" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
<input name="chinese_name" class="form-control" id="chineseName" placeholder="name" value="{{form.chinese_name.value}}">
</div>
</div>
<div class="form-group row">
<label for="gender" class="col-sm-2 control-label">gender</label>
<div class="col-sm-10">
<label class="radio-inline">
{% if form.gender.value == "M" %}
<input type="radio" name="gender" id="gender1" value="M" checked> Male
{% else %}
<input type="radio" name="gender" id="gender2" value="M"> Male
{% endif %}
</label>
<label class="radio-inline">
{% if form.gender.value == "F" %}
<input type="radio" name="gender" id="gender1" value="F" checked> Female
{% else %}
<input type="radio" name="gender" id="gender2" value="F"> Female
{% endif %}
</label>
</div>
</div>
<div class="form-group row">
<label for="age" class="col-sm-2 control-label">age</label>
<div class="col-sm-10">
<input name="age" class="form-control" id="age" placeholder="年龄" value="{{form.age.value}}">
</div>
</div>
<div class="form-group row">
<label for="phone" class="col-sm-2 control-label">phone</label>
<div class="col-sm-10">
<input name="phone" class="form-control" id="phone" placeholder="phone" value="{{form.phone.value}}">
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default col-xs-12" id="confirm" style="display:none;">confirm</button>
</div>
</div>
</form>
Somehow request.POST is not receiving data from this form. When I switch this long HTML snippet into {{form}}, everything is fine.
So view function is correct. Is there anything wrong with this template file, especially the form part?
You should add the css in the form class, for example if you are using ModelForm:
self.fields['phone'].widget.attrs['placeholder'] = self.fields['phone'].label
or if you are using Form :
phone = forms.CharField(widget=forms.TextInput(attrs={'placeholder' : 'phone'))
Nothing looks out of order at first look. One way to debug further would be to instantiate the form and print it. Then compare everything, especially the <form> tag and <input> tags.