Django selected value using manual render form in django - django

I'm trying to implement CRUD operations in django, however, I'm stuck in the edit operation.
After passing the data to edit template I need to show the selected values of operating system dropdown list, how can I achieve that?
I utilized the manual rendering of django form with the following code in the template:
<div class="form-group row">
<label class="col-sm-3 col-form-label">Operating System</label>
<div class="col-sm-9">
<select class="form-control" name="os_id" id="os_id" required>
<option value="">--Select--</option>
{% for os in os %}
<option value="{{ os.id}}">{{ os.key_name}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Title</label>
<div class="col-sm-9">
<textarea class="form-control" id="title" name="title" rows="3" required>{{ servicedesk.title }}</textarea>
</div>
</div>
here's the view code:
def edit(request, id):
servicedesk=Servicedesk.objects.get(id=id)
softwares=Software.objects.all
os=OperatingSystem.objects.all
context = {'servicedesk':servicedesk, "softwares":softwares, "os":os}
return render(request, 'servicedesks/edit.html', context)
and the model:
class OperatingSystem(models.Model):
key_name = models.CharField(max_length=100,null=True)
key_description = models.CharField(max_length=255,null=True)
class Meta:
db_table = "operating_systems"
def __str__(self):
return self.key_name
class Software(models.Model):
key_name = models.CharField(max_length=100,null=True)
key_description = models.CharField(max_length=255,null=True)
class Meta:
db_table = "softwares"
def __str__(self):
return self.key_name
class Servicedesk(models.Model):
os_id=models.ForeignKey(OperatingSystem, on_delete=models.SET(0))
software_id = models.ForeignKey(Software, on_delete=models.SET(0))
title = models.CharField(max_length=255,null=True)
I tried this but it's not working:
<div class="form-group row">
<label class="col-sm-3 col-form-label">Operating System {{os_id}}</label>
<div class="col-sm-9">
<select class="form-control" name="os_id" id="os_id" required>
<option value="">--Select--</option>
{% for os in os %}
{% if os.id == servicedesk.os_id %}
<option value="{{os.id}}" selected>{{os.key_name}}</option>
{% endif %}
<option value="{{ os.id}}">{{ os.key_name}}</option>
{% endfor %}
</select>
</div>
</div>

Related

Image not getting uploaded in Django

I tried to save a record using two different methods but both are not working.
Django Form
Models (create method)
1 I have created a ModelForm
class ProductForm(ModelForm):
class Meta:
model= ProductDetails
fields= ("name","category","subcategory","price","mrp","product_details","main_img","img1","img2","img3")
labels={
"name":"Product Name",
"product_details":"Description",
"category":"Category",
"subcategory":"Sub-Category",
"price":"Price",
"mrp":"MRP",
"main_img":"Main Image",
"img1":"Image 1",
"img2":"Image 2",
"img3":"Image 3",
}
widgets = {
'name':forms.TextInput(attrs={'class':'form-control validate',}),
'product_details':forms.TextInput(attrs={'class':'form-control validate',}),
'category':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}),
'subcategory':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}),
'price':forms.TextInput(attrs={'class':'form-control validate',}),
'mrp':forms.TextInput(attrs={'class':'form-control validate',}),
'main_img':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img1':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img2':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img3':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
}
Models File
# For Product details
class ProductDetails(models.Model):
name= models.CharField(max_length=100)
price= models.FloatField()
mrp= models.FloatField()
main_img = models.ImageField(upload_to='product_img')
img1 = models.ImageField(upload_to='product_img')
img2 = models.ImageField(upload_to='product_img')
img3 = models.ImageField(upload_to='product_img')
category = models.ForeignKey(Category, related_name='produits', on_delete=models.CASCADE)
subcategory = models.ForeignKey(SubCategory, related_name='produits', on_delete=models.CASCADE)
product_details = RichTextField(blank=True, null=True)
trending = models.BooleanField(default=False)
def __str__(self):
return self.name
Method 1
Save record using form.save()
getting Form validation error
I have tried by removing main_img,img1,img2,img3 from all place (Forms.py, template, views,py). Then there is not validation error and record is getting saved successfully.
The validation error is just because of some issue with the image uploading
print(form.errors)= <ul class="errorlist"><li>main_img<ul class="errorlist"><li>This field is required.</li></ul></li><li>img1<ul class="errorlist"><li>This field is required.</li></ul></li><li>img2<ul class="errorlist"><li>This field is required.</li></ul></li><li>img3<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
def add_product(request):
if request.method == "POST":
form = ProductForm(request.POST or None, request.FILES or None)
print(form.errors )
if form.is_valid():
category_id = request.POST.get('category')
subcategory_id = request.POST.get('subcategory')
category= Category.objects.get(id=int(category_id))
subcategory= SubCategory.objects.get(id=int(subcategory_id))
form.category = category
form.subcategory = subcategory
form.save()
return redirect("/dashboard/products")
form = ProductForm()
categories=Category.objects.all()
subcategories=SubCategory.objects.all()
return render(request, "01-add-product.html", "form":form,"categories":categories,"subcategories":subcategories})
Method 2
Tried Saving records using models.save()
The record is getting saved but image is not getting uploaded to the media folder
On saving record from Django-admin the image is getting uploaded to proper place i.e. /media.product_img/...
But From this outside HTML its showing the file name in Django-admin but the file is not available in media folder
I already added urlpattern + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my project/urls.py.
Also tried adding the same in urls.py of this app
Note = I have mentioned upload_to=product_img in my model (this may be important to know)
def add_product(request):
if request.method == "POST":
name = request.POST['name']
product_details = request.POST['product_details']
category_id = request.POST.get('category')
subcategory_id = request.POST.get('subcategory')
category= Category.objects.get(id=int(category_id))
subcategory= SubCategory.objects.get(id=int(subcategory_id))
price = request.POST['price']
mrp = request.POST['mrp']
main_img = request.POST['main_img']
img1 = request.POST['img1']
img2 = request.POST['img2']
img3 = request.POST['img3']
product = ProductDetails.objects.create(name=name,product_details=product_details,category=category,subcategory=subcategory,price=price,mrp=mrp,main_img=main_img,img1=img1,img2=img2,img3=img3)
product.save()
Here is my template
{% extends '01-admin-base.html' %}
{% load static %}
{% block content %}
<div class="container tm-mt-big tm-mb-big">
<div class="row">
<div class="col-xl-9 col-lg-10 col-md-12 col-sm-12 mx-auto">
<div class="tm-bg-primary-dark tm-block tm-block-h-auto">
<div class="row">
<div class="col-12">
<h2 class="tm-block-title d-inline-block">Add Product</h2>
</div>
</div>
<div class="row tm-edit-product-row">
<div class="col-xl-6 col-lg-6 col-md-12">
<form action="" method="post" class="tm-edit-product-form">
{% csrf_token %}
{{form.media}}
<div class="form-group mb-3">
<label
for="name"
>Product Name
</label>
{{form.name}}
</div>
<div class="form-group mb-3">
<label
for="category"
>Category</label
>
<select
class="custom-select tm-select-accounts"
id="category" name="category"
>
<option selected>Select category</option>
{% for category in categories %}
<option value="{{category.id}}">{{category.name}}</option>
{% endfor %}
</select>
</div>
<div class="form-group mb-3">
<label
for="subcategory"
>Sub Category</label
>
<select
class="custom-select tm-select-accounts"
id="subcategory" name="subcategory"
>
<option selected>Select sub-category</option>
{% for subcategory in subcategories %}
<option value="{{subcategory.id}}">{{subcategory.name}}</option>
{% endfor %}
</select>
</div>
<div class="row">
<div class="form-group mb-3 col-xs-12 col-sm-6">
<label
for="price"
>Price
</label>
{{form.price}}
</div>
<div class="form-group mb-3 col-xs-12 col-sm-6">
<label
for="mrp"
>MRP
</label>
{{form.mrp}}
</div>
</div>
<div class="form-group mb-3">
<label
for="description"
>Description</label
>
{{form.product_details}}
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-12 mx-auto mb-4">
<div class="custom-file mt-3 mb-3">
<label>Main Image</label>
{{form.main_img}}
</div>
<br><br>
<label>Images</label>
<div class="custom-file mt-3 mb-3">
{{form.img1}}
</div>
<div class="custom-file mt-3 mb-3">
{{form.img2}}
</div>
<div class="custom-file mt-3 mb-3">
{{form.img3}}
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary btn-block text-uppercase">Add Product Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
Please help me to get solution for this.
You need to add enctype="multipart/form-data"> in Html form so:
<form action="/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>

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"

Display & Update in same Django form

[A newbie Question] I have a form that shows the student details (query filtered by learner_code). I have an edit button that removes the "disabled" tag from fields & let user edit the form details. I have a Save button as well. I want to save the update back to the same entry in Student model.
My views.py :
query = None
if 'learner_code' in request.GET:
query = request.GET['learner_code']
try:
student_details = Student.objects.get(learner_code=query)
except:
messages.error(request, f'Student Not Found !')
return redirect('viewstudent')
else:
context = { 'student_details' : student_details}
return render(request, 'students/viewstudent.html', context)
elif 'learner_code' in request.POST :
# Save the data back to the table
else:
return render(request, 'students/createstudent.html')
My model looks like :
class Student(models.Model):
pay = (('FULL', 'FULL'),('EMI', 'EMI'))
learner_code = models.CharField(max_length=15, null=False, primary_key=True)
certificate_name = models.CharField(max_length=150, null=False)
contact1 = models.CharField(max_length=10, null=False)
contact2 = models.CharField(max_length=10)
batch = models.CharField(max_length=10)
doj = models.DateField(null=False, default=localtime(now()).date())
payment_method = models.CharField(choices=pay, max_length=4, default='FULL')
total_paid = models.IntegerField(default=0)
def __str__(self):
return self.learner_code
My forms.py is :
class StudentCreationForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
My Template looks like :
{% block content %}
<div class="container mx-auto mt-3">
{% block form %}
<form class="form-row mr-auto" action="" method="get">
<input type="text" class="form-control" name="learner_code" id="search" placeholder="Learner Code" style="width: 20pc;">
<button class="btn btn-success" type="submit">Search</button>
</form>
{% if messages %}
{% for message in messages %}
<div class="container-fluid">
<div class="alert alert-{{ message.tags }}">{{ message }}</div>
</div>
{% endfor %}
{% endif %}
<hr>
<h2>STUDENT DETAILS</h2>
<div class="row my-2">
<div class="col-6">
<label for="id"><h6>LEARNER CODE : </h6></label>
<input type="text" name="id" id="id" placeholder="{{ student_details.learner_code }}" disabled style="width: 20pc;">
</div>
<div class="col-6">
<label for="name"><h6>CERTIFICATE NAME : </h6></label>
<input type="text" name="name" id="name" placeholder="{{ student_details.certificate_name }}" disabled style="width: 20pc;">
</div>
</div>
<div class="row my-2">
<div class="col-6">
<label for="contact1"><h6>CONTACT NUMBER : </h6></label>
<input type="number" name="contact1" id="contact1" placeholder="{{ student_details.contact1 }}" disabled style="width: 20pc;">
</div>
<div class="col-6">
<label for="contact2"><h6>ALT. CONTACT NO. : </h6></label>
<input type="number" name="contact2" id="contact2" placeholder="{{ student_details.contact2 }}" disabled style="width: 20pc;">
</div>
</div>
<div class="row my-2">
<div class="col-6">
<label for="batch"><h6>BATCH : </h6></label>
<input type="text" name="batch" id="batch" placeholder="{{ student_details.batch }}" disabled style="width: 20pc;">
</div>
<div class="col-6">
<label for="doj"><h6>DATE OF JOINING : </h6></label>
<input type="text" name="doj" id="doj" placeholder="{{ student_details.doj }}" disabled style="width: 20pc;">
</div>
</div>
<div class="container-fluid mx-auto mt-5">
<button onclick="edits()">Edit</button>
<form action="" method="post">
{% csrf_token %}
<button type="submit">Save</button>
</form>
</div>
<hr>
<h2>FINANCIAL INFORMATION</h2>
<div class="row my-2">
<div class="col-6">
<label for="tenure"><h6>PAYMENT TENURE : </h6></label>
<input type="text" name="tenure" id="tenure" placeholder="{{ student_details.payment_method }}" disabled style="width: 20pc;">
</div>
<div class="col-6">
<label for="paid"><h6>TOTAL PAID : </h6></label>
<input type="number" name="paid" id="paid" placeholder="{{ student_details.total_paid }}" disabled style="width: 20pc;">
</div>
</div>
{% endblock form %}
</div>
<script>
function edits()
{
document.getElementById("id").removeAttribute("disabled")
document.getElementById("id").setAttribute("value","{{ student_details.learner_code }}")
document.getElementById("name").removeAttribute("disabled")
document.getElementById("name").setAttribute("value","{{ student_details.certificate_name }}")
document.getElementById("contact1").removeAttribute("disabled")
document.getElementById("contact1").setAttribute("value","{{ student_details.contact1 }}")
document.getElementById("contact2").removeAttribute("disabled")
document.getElementById("contact2").setAttribute("value","{{ student_details.contact2 }}")
document.getElementById("batch").removeAttribute("disabled")
document.getElementById("batch").setAttribute("value","{{ student_details.batch }}")
document.getElementById("doj").removeAttribute("disabled")
document.getElementById("doj").setAttribute("value","{{ student_details.doj }}")
}
</script>
{% endblock content %}
You can use django model form and instance of the query to pre-populate the form to display and update in the same form
def your_view(request):
form = StudentCreationForm()
if request.method == "POST":
student_details = Student.objects.get(learner_code=query)
# To pre-populate the form with values using instance
form = StudentCreationForm(request.POST, instance=student_details)
if form.is_valid():
form.save()
return redirect('your_url')
return render(request, "students/createstudent.html", {'form': form })

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 inline formset : DELETE fied in form.visible_fields?

Maybe someone could explain this to me.
With the following models:
class ContactEmail(models.Model):
# Documentation
__doc__ = _(u'Stores an e-mail address for a contact.')
# Enums
CATEGORIES = (
(0, _(u'Personal')),
(1, _(u'Professional')),
)
# Attributes
category = models.IntegerField(choices=CATEGORIES, verbose_name=_(u'category'), help_text=_(u'This values indicates wheter the address is for personal or professional use.'))
email_address = models.EmailField(max_length=255, unique=True, verbose_name=_(u'e-mail address'), help_text=_(u'A valid e-mail address.'))
contact = models.ForeignKey('Contact', related_name=u'emails', verbose_name=_(u'contact'), help_text=_(u'The contact whose the e-mail address is.'))
priority_level = models.PositiveSmallIntegerField(verbose_name=_(u'priority level'), help_text=_(u'An integer used to define a priority level for e-mail addresses of a contact.'))
# Methodes
def __unicode__(self):
return u'%(mail)s' % {u'mail': self.email_address}
# Meta-data
class Meta:
verbose_name = _(u'E-mail')
verbose_name_plural = _(u'E-mails')
unique_together = ('contact', 'priority_level')
class Contact(models.Model):
pass
And the following ModelForms:
class ContactCreateForm(forms.ModelForm):
# Documentation
__doc__ = _(u'A custom form for Contact model.')
# Methods
def __init__(self, *args, **kwargs):
super(ContactCreateForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
if name != 'image':
if field.widget.attrs.has_key('class'):
field.widget.attrs['class'] += ' form-control'
else:
field.widget.attrs.update({'class':'form-control'})
# Meta-data
class Meta:
model = Contact
exclude = ['second_names', 'suffix', 'dob', 'skype_account',]
class ContactEmailCreateForm(forms.ModelForm):
# Documentation
__doc__ = _(u'A custom form for ContactEmail model.')
# Methods
def __init__(self, *args, **kwargs):
super(ContactEmailCreateForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
if field.widget.attrs.has_key('class'):
field.widget.attrs['class'] += ' form-control'
else:
field.widget.attrs.update({'class':'form-control'})
# Meta-data
class Meta:
model = ContactEmail
I'm trying to set up a create contact form that includes a formset for Emails (intention is to use django-dynamic-formset to dynamically adds form just like the Admin does - and actuall it works). Here's the view:
class ContactCreateView(LoginRequiredMixin, CreateView):
template_name = u'frontend/contacts/create.html'
model = Contact
form_class = ContactCreateForm
def get_context_data(self, **kwargs):
context = {
'emails' : inlineformset_factory(parent_model=Contact, model=ContactEmail, form=ContactEmailCreateForm, extra=1),
}
context.update(kwargs)
return super(ContactCreateView, self).get_context_data(**context)
django-dynamic-formset requires you to set can_delete=True which is set by default in inlineformset_factory. And this parameter adds a DELETE field to each form of your formset.
Until here, nothing to complain about. Except that it adds this fields to form.visible_fields which is, IMO, kind of disturbing since this field is hidden if there is no form.instance:
# create.html
<fieldset class="emails">
<legend>{% trans "E-mail(s)" %}</legend>
{{ emails.management_form }}
{% for form in emails %}
<div class="inline-form-emails">
{{ form.media }}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
<div class="form-group">
<label for="{{ field.html_name }}" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
{{ field.label }} {% if field.field.required %}<span style="color: #a60000;">*</span>{% endif %}
</label>
<div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
{{ field }}
<span class="help-block">{{ field.help_text }}</span>
</div>
</div>
{% endfor %}
</div>
{% endfor %}
</fieldset>
As you can see the output:
<fieldset class="emails">
<legend>E-mail(s)</legend>
<input id="id_emails-TOTAL_FORMS" name="emails-TOTAL_FORMS" type="hidden" value="1"><input id="id_emails-INITIAL_FORMS" name="emails-INITIAL_FORMS" type="hidden" value="0"><input id="id_emails-MAX_NUM_FORMS" name="emails-MAX_NUM_FORMS" type="hidden" value="1000">
<div class="inline-form-emails dynamic-form">
<input id="id_emails-0-contact" name="emails-0-contact" type="hidden">
<input id="id_emails-0-id" name="emails-0-id" type="hidden">
<div class="form-group">
<label for="emails-0-category" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
Category <span style="color: #a60000;">*</span>
</label>
<div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
<select class="form-control" id="id_emails-0-category" name="emails-0-category">
<option value="" selected="selected">---------</option>
<option value="0">Personal</option>
<option value="1">Professional</option>
</select>
<span class="help-block">This values indicates wheter the address is for personal or professional use.</span>
</div>
</div>
<div class="form-group">
<label for="emails-0-email_address" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
E-mail address <span style="color: #a60000;">*</span>
</label>
<div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
<input class="form-control" id="id_emails-0-email_address" maxlength="255" name="emails-0-email_address" type="text">
<span class="help-block">A valid e-mail address.</span>
</div>
</div>
<div class="form-group">
<label for="emails-0-priority_level" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
Priority level <span style="color: #a60000;">*</span>
</label>
<div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
<input class="form-control" id="id_emails-0-priority_level" name="emails-0-priority_level" type="text">
<span class="help-block">An integer used to define a priority level for e-mail addresses of a contact.</span>
</div>
</div>
<div class="form-group">
<label for="emails-0-DELETE" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
Delete
</label>
<div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
<input type="hidden" name="emails-0-DELETE" id="id_emails-0-DELETE">
<span class="help-block"></span>
</div>
</div>
<a class="delete-row" href="javascript:void(0)">remove</a></div><a class="add-row" href="javascript:void(0)">add another</a>
</fieldset>
Anyone has a clue ?
As mentioned here, the problem came from the django-dynamic-form library !
Just in case someone fall into the same trap...