Submitting dynamically created input field in django - django

am working on a project with Django, i dynamically created an input field and am trying to submit it, but i could not do so, i searched online and i saw that it could be done with formset_factory but when i tried it, i got this error
CatName = int(float(request.POST.get('CatName')))
TypeError: float() argument must be a string or a number, not 'NoneType'
here is my code
the form.html
<form action="." method="post" id="PostCat__form">{% csrf_token %}
<input type="hidden" name="deyHidden" value="category_hidden">
{% comment %} {{ catForm | crispy }}
<input type="hidden" name="deyHidden" value="category_hidden"> {% endcomment %}
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<div class="form-group">
<h6 id="PostCat__show"></h6>
<img src=" {% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PostCat__img">
<button class="btn btn-outline-info" type="submit" id="PostCat__submit">Create</button>
</div>
</form>
the model.py
class Category(models.Model):
CatName = models.CharField(max_length=100)
the view.py
myFormCat = CatPostForm(request.POST)
CatName = int(float(request.POST.get('CatName')))
# print(CatName)
formset = formset_factory(FormsetForm, CatName=CatName)(request.POST)
if myFormCat.is_valid() and formset.is_valid():
for form_c in formset:
if not form_c.cleaned_data['CatName']:
Category.objects.get_or_create(CatName=CatName)
response_data = {
'SType': 'success',
'message': "Saved Successfully"
}
return HttpResponse(json.dumps(response_data), content_type="application/json")
the forms.py
class CatPostForm(forms.ModelForm):
class Meta:
model=Category
fields = ['CatName']
pls how can i do it so that i can successfully submit the form,

on your views.py
from django.forms import formset_factory
CatPostFormSet = formset_factory(CatPostForm)
catformset = CatPostFormSet() #this goes to your page context. do the validations here also after the post
on your form.html
<form method="post">
{{ formset.management_form }}
{{formset}}
</form>

Related

pass data to form filed in django templae

How can I pass data to form fields in django templat ? , for example I have below code in my project:
<td class="col-3">
{{form.number|as_crispy_field}}
</td>
Can I use
<td class="col-3">
{{form.number}} = 10
</td>
in django template ?
#mosi -
<td class="col-3">
{{form.number}} = 10
</td>
No, you cannot use this. If you are planning to pass data from views to template then do something like this
Let's say you have a form something like this
forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=254)
views.py
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass # your logic here
else:
form = ContactForm()
return render(request, 'home.html', {'form': form})
template.html
<form method="post" novalidate>
{% csrf_token %}
{{ form.name }}
{{form.email}}
<button type="submit">Submit</button>
</form>
OR
Simply
<form method="post" novalidate>
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
Now, if you want to set initial values to your form in template
Lets say you have the following
class ContactForm(forms.Form):
name = forms.CharField(max_length=30,initial='test')
Then in your template you do something like this
<form method="post" novalidate>
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<button type="submit">Submit</button>
</form>
Now, in case of an UpdateView where data is pulled in dynamically from the Database based on let's say product id. The following is just an example
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = (
"created_by",
"slug",
)
class ProductUpdateView(UpdateView):
# specify the model you want to use
model = Product
form_class = ProductForm
template_name = "catalog/product/update_product.html"
product_update.html
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
{{ form.as_p}}
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
Or
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<input type="text" name="description" id="description" value="{{ form.description.value }}">
.........
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>

I don't understand why my form is not validating in django

I am still new to django. Playing around with a leadmanager app and I don't know why my form is not validating.
views
def index(request):
lead=LeadForm()
if request.method == 'POST':
lead=LeadForm(request.POST)
if lead.is_valid():
messages.success(request, f'Thank you for registering. Someone will be contacting you soon.')
return redirect('index')
else:
lead=LeadForm()
messages.error(request, f'Something went wrong. Please try again later.')
return render(request, "frontend/index.html", {'lead':lead})
in index.html
<form action="" method="POST" class="lead-form">
{% csrf_token %}
<fieldset class="lead-info">
<div class="form-control">
<label for="">Full Name</label>
{{ lead.fullname }}
</div>
<div class="form-control">
<label for="">Email</label>
{{ lead.email }}
</div>
<div class="form-control">
<label for="">Phone</label>
{{ lead.phone }}
</div>
<div class="form-control">
<label for="">City</label>
{{ lead.city }}
</div>
</fieldset>
<button type="submit" class="btn-pill">Submit</button>
</form>
in forms.py
class LeadForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = Lead
fields = ['fullname', 'email', 'phone', 'city', 'contact_preference']
widgets = {'contact_preference': forms.RadioSelect }
Any help is appreciated. contact_preference is rendering FYI, I just cut the code to keep this question not that long.

Forbidden (403) CSRF verification failed

When I click on ok button in add_tech.html then it will redirect me on upload_type.html.
But it show error while clicking on ok button.
ERROR -
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
My template(add_tech.html) -
<form action="/uploads/type/" method="post">
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
My Template(upload_type.html)-
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
</form>
My View.py -
def upload_type(request):
if request.method =='POST':
details = NameForm(request.POST)
if details.is_valid():
return render(request, "core/upload_type.html", {'form':details})
else:
details = NameForm()
return render(request, 'core/upload_type.html', {'form': details})
My Url.py -
urlpatterns = [
url(r'^uploads/type/$', views.upload_type, name='upload_type'),]
My form.py -
from uploads.core.models import Name
class NameForm(forms.ModelForm):
class Meta:
model = Name
fields = ('your_name', )
My Models.py-
class Name(models.Model):
your_name = models.CharField(max_length=100)
You need to have the csrf token like this for your post method in the django template
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
For POST request, csrf token is required. So in your template, add `{% csrf_token %}.
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
From the Docs:
Django ships with an easy-to-use protection against Cross Site Request
Forgeries. When submitting a form via POST with CSRF protection
enabled you must use the csrf_token template tag as in the preceding
example.

Custom Django forms within template and hidden inputs

Very, very quick question. I'm rendering my own custom forms within my html template...how would I go about submitting the hidden input when the user submits that form?
template.html
<form class="contact-form" name="contact-form" method="post" action=".">
{% csrf_token %}
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="four">Your Text</label>
<textarea class="form-control" type="text" name="{{ comment_form.content.name }}" {% if comment_form.content.value %}value="{{ comment_form.content.value }}"{% endif %} placeholder="" required="required" id="four"></textarea>
</div>
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary pull-right">Submit Comment</button>
</div>
</form>
form.py
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
content_type = forms.CharField(widget=forms.HiddenInput)
object_id = forms.IntegerField(widget=forms.HiddenInput)
#parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False)
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Comment
fields = ('content',)
You can add this part to you forms.py file (in CommentForm class) :
hidden_field=forms.CharField(widget=forms.HiddenInput())
I hope it will work.let me know

django-ckeditor request dont get changes in form

I have one form called in ajax function, this function return one django form with one ckeditor field.
This field is displayed without problems, but when I make a request, the field value, dont sended in request, but if I make another, in the same form, with the same values, the value is update and is sended in request.
My form field
class EditCommentForm(IdeiaForm):
content = forms.CharField(
max_length=settings.COMMENT_TEXT_LIMIT if hasattr(settings, "COMMENT_TEXT_LIMIT") else 10000,
required=True,
widget=CKEditorWidget(config_name='question')
)
comment_id = forms.IntegerField(required=True)
My html template
<form class="create-comment" data-group-class=".comment-group" data-ajaxform="true" data-toggle="replace" class="create-comment" data-update="#{{ to_update }}" action="{% url 'comment:edit' %}" method="post">{% csrf_token %}
<div class="comment-group create-comment-body{% if form.content.errors %} has-error{% endif %}">
<textarea name="content" class="form-control" placeholder="Deixe seu comentário">{{ instance.content }}</textarea>
<span class="help-block"></span>
</div>
<input name="comment_id" value="{{ instance.id }}" type="hidden"/>
<div class="create-comment-footer">
<input type="submit" value="Editar" class="btn btn-primary">
</div>
</form>