Saving data after non-Django Form submission - django

I have a payment form that is made up of various elements.
Here my problem is that the card for a new stripe user isn't registered until after form submission.
I know that if my form has a newly added Address, I can use form.is_valid() but that doesn't apply if my address is one that is saved already. But is there a way I can set the card using stripe.PaymentMethod.list after the form is submitted, regardless of if the Django form is part of it?
form
<form method="POST" id="subscription-form" data-secret="{{client_secret}}">
{% csrf_token %}
<label class="block uppercase text-gray-600 text-xs font-bold mb-2">Payment Details</label>
{% if payment_methods %}
<div class="form-check my-3 bg-gray-200 p-2 rounded-md">
<input class="form-check-input" type="radio" name="payment-methods" id="add-new-card"
value="add-new-card" onclick="addCard()" {%if payment_methods %} {%else%}checked="checked" {%endif%}
required>
<label class="form-check-label" for="add-new-card">
Add new payment method
</label>
<div id="new-card" style="display: none;">
<label class="block uppercase text-gray-600 text-xs mb-2" for="cardholder-name">
Name on Card
</label>
<input id="cardholder-name"
class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
value="{{customer.name}}" detype="text">
<!-- placeholder for Elements -->
<label class="block uppercase text-gray-600 text-xs mb-2" for="card-element">
Card Details
</label>
<div id="card-element"
class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150">
<!-- A Stripe Element will be inserted here. -->
</div>
<div id="card-result"></div>
<div id="card-errors" class="my-2" role="alert"></div>
</div>
</div>
{% if saved_customer %}
{% for method in payment_methods %}
<div class="form-check my-3 bg-gray-200 p-2 rounded-md">
<input class="form-check-input" type="radio" name="payment-methods" id="{{method.card}}"
value="{{method.id}}" onclick="hideCard()" {% if forloop.first %} checked="checked" {%endif%}>
<label class="form-check-label" for="{{method.card}}">
{{method.card.brand}} ending in {{method.card.last4}}
</label>
</div>
{% endfor %}
{% endif %}
{% else %}
<div class="form-check my-3 bg-gray-200 p-2 rounded-md">
<input class="form-check-input" type="radio" name="payment-methods" id="add-new-card"
value="add-new-card" checked="checked"
required>
<label class="form-check-label" for="add-new-card">
Add new payment method
</label>
<div id="new-card">
<label class="block uppercase text-gray-600 text-xs mb-2" for="cardholder-name">
Name on Card
</label>
<input id="cardholder-name"
class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
value="{{customer.name}}" detype="text">
<!-- placeholder for Elements -->
<label class="block uppercase text-gray-600 text-xs mb-2" for="card-element">
Card Details
</label>
<div id="card-element"
class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150">
<!-- A Stripe Element will be inserted here. -->
</div>
<div id="card-result"></div>
<div id="card-errors" class="my-2" role="alert"></div>
</div>
</div>
{% endif %}
<label class="block uppercase text-gray-600 text-xs font-bold mb-2">Address</label>
<div id="address-list">
<div class="form-check my-3 bg-gray-200 p-2 rounded-md">
<input class="form-check-input" type="radio" name="addresses" id="new-address" value="new-address"
onclick="showAddress()" {%if addresses%} {%else%}checked="checked" {%endif%}>
<label class="form-check-label" for="new-address">
New Address
</label>
<span id="address-form"></span>
</div>
{% for address in addresses %}
<div class="form-check my-3 bg-gray-200 p-2 rounded-md">
<input class="form-check-input" type="radio" name="addresses" id="{{address.id}}"
value="{{address.id}}" onclick="hideAddress()" {% if forloop.first %} checked="checked"
{%endif%} required>
<label class="form-check-label" for="{{address.id}}">
{{address.name}} - {{address.line_1}}
</label>
</div>
{% endfor %}
</div>
<input type="hidden" id="email" name='email' value='{{customer.email}}'>
<div>
<p class="text-xs">By confirming, you agree that you will be charged immediately, and then monthly for
this product until cancelled</p>
<button id="submit" type="submit"
class="w-full mt-2 bg-blue-300 text-blue-900 font-medium rounded p-3">Confirm
and Pay</button>
</div>
</form>
view
#login_required
def subscription_new(request, product):
stripe.api_key = STRIPE_SECRET_KEY
title = "New Subscription for " + product
product = Product.objects.get(slug=product)
customer = Customer.objects.get(user=request.user.id)
addresses = Address.objects.filter(customer=customer)
current_day = datetime.date.today().day
# maintain order day in short months
if current_day > 28:
current_day = 1
stripe_amount = str(int(round(product.price, 2) * 100))
context = {
'title' : title,
'product' : product,
'customer' : customer,
'addresses' : addresses,
'current_day' : current_day,
'STRIPE_PUBLIC_KEY' : STRIPE_PUBLIC_KEY,
}
card = request.POST.get('payment-methods')
if customer.stripe_id:
payment_methods = stripe.PaymentMethod.list(
customer=customer.stripe_id,
type="card",
)
context['saved_customer'] = True
context['payment_methods'] = payment_methods
else:
print('no stripe id ')
new_customer = stripe.Customer.create(name=customer.name, email=customer.email)
customer.stripe_id = new_customer.id
customer.save()
context['saved_customer'] = False
intent = stripe.SetupIntent.create(customer=customer.stripe_id)
client_secret = intent.client_secret
context['client_secret'] = client_secret
if request.method == 'POST':
print("method is post")
address = request.POST.get('addresses')
if address == 'new-address':
form = AddressForm(request.POST)
address = form.save(commit=False)
address.customer = customer
address.save()
else:
address = Address.objects.get(id=address)
if customer.stripe_id:
payment_methods = stripe.PaymentMethod.list(
customer=customer.stripe_id,
type="card",
)
print("customer has id")
if card == "add-new-card":
payment_methods = stripe.PaymentMethod.list(
customer=customer.stripe_id,
type="card",
)
new_card = payment_methods.data[0]
# context['client_secret'] = client_secret
subscription = Subscription.objects.create(customer=customer, product=product, address=address, renewal_day=current_day, payment_method=new_card.id)
msg = 'Subscription created'
else:
subscription = Subscription.objects.create(customer=customer, product=product, address=address, renewal_day=current_day, payment_method=card)
msg = 'Subscription created'
messages.success(request, msg)
# If method is not post
else:
form = AddressForm()
context['form'] = form
return render(request, 'accounts/subscription_new.html', context)

Assuming AddressForm is a ModelForm, you can use it on an existing instance of a model as well:
address = Address.objects.get(id=address_id)
form = AddressForm(request.POST, instance=address)
Also, you can take other actions before saving the form. If you want the stripe payment method to be registered in order to save the form, register it first, then save the form.
If you want to customize the data stored on the address by AddressForm, just override the save method and modify self.instance before you call super().save().
Alternatively, just edit the Address object outside of the context of the form. There's nothing requiring database updates to happen inside a form save method

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 data is not going into post operation in django. How to do the Post call in this function?

I am working on a Django project where I have a form which I want to do POST. but everytime it went to the else part.
here's my view:
def ATFrun(request,test_case_ID):
if request.method == 'POST':
print("post")
url = 'http://www.google.com'
pi = APIDetails.objects.get(pk=test_case_ID)
atfParam= list(APIParameter.objects.values('id','parameterName','parameterValue').filter(TC_ID=pi))
fm = APIDetailsReg(request.POST, instance=pi)
req = fm.data
# req = request.POST
req_list = list(dict(req).values())
ATFparams_count = len(req_list)
ATFparams = ""
if ATFparams_count > 0:
for i in range(ATFparams_count-1):
ATFparams = ATFparams + req_list[i+1][0] + '=' + req_list[i+1][1] + '&'
data = ATFparams[:-1]
url = url + data
print('paramfinal',url)
if fm.is_valid():
fm.save()
fm = APIDetailsReg()
return HttpResponseRedirect('/TAFDashboard')
else:
print("not post")
pi = APIDetails.objects.get(pk=test_case_ID)
fm = APIDetailsReg(instance=pi)
atfParam= list(APIParameter.objects.values('id','parameterName','parameterValue').filter(TC_ID=pi))
atf = APIDetails.objects.all()
return render(request, 'hello/ATF_Run.html',{'ATF': atf, 'Param': atfParam})
here's my html form
<div class="panel panel-info atf-form">
<div class="panel-heading text-center" style="background-color: #660099;">
<h1 class="panel-title" style="color: white;">TAF Integration URL</h1>
</div>
<form style="margin-top: 10px;">
{% for param in Param %}
<div class="form-row">
<div class="form-group col-md-2">
<label for="param">TAF Parameter</label>
<input type="text" name="{{param.id}}" class="form-control" id="inputapi_param" value="{{param.parameterName}}" readonly>
</div>
{% if param.parameterName == 'api' or param.parameterName == 'callback' %}
<div class="form-group col-md-4">
<label for="val">TAF Value</label>
<input type="text" name="{{param.id}}" class="form-control" id="inputapi_val" value="{{param.parameterValue}}" readonly>
</div>
{%else%}
<div class="form-group col-md-4">
<label for="val">TAF Value</label>
<input type="text" name="{{param.id}}" class="form-control" id="inputapi_val" value="{{param.parameterValue}}" required>
</div>
{% endif %}
</div>
{% endfor %}
<div class="form-row ">
<div class="form-group col-md-12">
<button type="submit" class="btn btn-primary taf-btn"><b>Generate TAF URL</b></button>
</div>
</div>
</form>
</div>
can someone help with that post call? everytime it went to the else part but as per my requirement it should be in POST part.

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...