Error retrieving value textarea's value from form in Django - django

I am new to Django. I am trying to create a simple form that has text area in it. I can't seem to retrieve the value from textarea
Here's my form:
<form method="POST" class="ui form" action="">
{% csrf_token %}
<div class="field">
<label>Title</label>
<input type="text" name="title"/>
<label> Content</label>
<textarea rows="8" name="content" ></textarea>
</div>
<button type="submit" class="ui primary button">Create</button>
</form>
Here's my how I handle the form
def createArticle(request):
if(request.method == 'POST'):
form = ArticleForm(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
body = form.cleaned_data['content']
username = request.session['email']
user = User.objects.get(username=username)
I am getting this error KeyError at /create/article/
'content' at this line body = form.cleaned_data['content']
Here's the content from my post request
csrfmiddlewaretoken'CgCwDF1d03KGIxsmM2Z4hhStBRIxw9hlh1ACtYXpBWXLLvYJq2tfdO7lqds7EVxI'
title'dsadasdasdsadsadasdsadasdsadsad'
content'<p>sadasdsadasdasdasdsadasdasdsadsadsadasdsadsadsadsadsadsadsadasdasd</p>\r\n'
I am guessing the <p> tag in content is what causing the error but I have no idea idea how to get rid of that.

You'll need to define name and id attributes for the form, and also define a form attribute for the textarea whose value would be the value of the form's id attribute.
<form method="POST" class="ui form" action="" id="content" name="content">
{% csrf_token %}
<div class="field">
<label>Title</label>
<input type="text" name="title"/>
<label> Content</label>
<textarea rows="8" form="content" ></textarea>
</div>
<button type="submit" class="ui primary button">Create</button>
</form>

Related

how to grab a data from existing field in Django

I have a web page that I have to connect with Django. So I have an existing form with input and submit button. I have created a model and form. I put {{form}} tag and a little unstyled form appeared. but I want to grab a data from the one in HTML file. The code:
form file:
class NumberForm(ModelForm):
class Meta:
model = Number
fields = "__all__"
HTML:
<form action="#" method="post">
{% csrf_token %}
{{ form }}
<div class="line>
<input type="text" class="form-control" name="phoneNumber" id="phoneNumber2" value="" placeholder="+7 (___) ___-__-__">
<button class="button_blue">t</button>
</div>
<label class="container_checkbox">
<input type="checkbox" checked="checked">
<span class="checkmark"></span>
</label>
</form>

Submitting dynamically created input field in 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>

How do i push uploaded image file in my template input for update in django 2.0

I want to open a particular record in html template in update mode for which i want every value which was inserted before for this record be in those field, i got every required value in field for text field but in file field which contains image ,it shows no file selected where as i want the image file name(url) in there.
I havent used django form rather i used normal bootstrap forms.
models.py
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
body = models.TextField()
image = models.ImageField(upload_to='images/') # i m facing problem for this field
icon = models.ImageField(upload_to='images/') # i m facing problem for this field as well
url = models.TextField()
votes_total = models.IntegerField(default=1)
hunter = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
def summary(self):
return self.body[:100]
def short_pub_date(self):
return self.pub_date.strftime('%b %e %Y')
#
views.py
def myproducts_update(request,product_id):
product = get_object_or_404(Product,pk=product_id)
print(product.image) # this prints the name of the file (images/37003.jpeg)
return render(request,'products/myproducts_update.html',{'product':product})
templates(myproducts_update.html)
{% extends 'base.html' %}
{% block content %}
{% if error %}
{{error}}
{% endif %}
<br>
<br>
<div class="container">
<div class="jumbotron">
<h2>Update Product</h2>
<form action="{% url 'create' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="email" value={{product.title}} placeholder="please enter title" name="title" required>
</div>
<div class="form-group">
<label for="body">Description:</label>
<input type="text" class="form-control" id="body" value={{product.body}} placeholder="Description" name="body" required>
</div>
<div class="form-group">
<label for="url">URL:</label>
<input type="text" class="form-control" id="url" value={{product.url}} placeholder="please enter url" name="url" required>
</div>
<br>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="icon">
<strong>Icon:</strong></label>
<input type="file" id="icon" name="icon" value={{product.icon}} required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="url">
<strong>Image:</strong></label>
<input type="file" id="image" placeholder="please enter url" name="image" value={{product.image}} required>
</div>
</div>
</div>
<br>
<input type="submit" value="Update Product" class="btn btn-primary">
</form>
</div>
</div>
{% endblock %}
Link which contains image of form where i have problem
I am having trouble in getting the url of the image in the templates,guys please help me
Thanks in advance!
Try something like this in your <form>:
<div class="margintop50px">
<img {% if object.image %} src="{{ object.image.url }}" {% else %} alt="You have no image." {% endif %}>
<input type="file" name="image" accept="image/*">
</div>
UPDATE:
I just checked your views.py. Sorry for not noticing sooner, but your myproducts_update() function never .save()'s anything, so nothing will show because of that. Try changing that function to something like the following. It assumes the product has already been created somewhere else because I don't know of any other views you made to get this far (maybe you originally added all pics/text from the admin panel? And personally, I would change the names of your function(s) because your form goes to 'create', but the function you showed states that this is about updating it, and that's generally not a clear path to follow when designing it because createing something is different from 'update'ing it. So if the following still doesn't work, I'll need to see your 'create' view, and the urlpatterns for all these functions).
Either way, there are better ways to improve the following (such as what I talked about above), but this is all I can give you without knowing that stuff:
views.py
def myproducts_update(request,product_id):
product = get_object_or_404(Product,pk=product_id)
if request.method == 'POST':
product.body = request.POST.get('body', False)
product.title = request.POST.get('title', False)
product.url = request.POST.get('url', False)
product.icon = request.FILES.get('icon', False)
product.image = request.FILES.get('image', False)
product.save()
return render(request,'products/myproducts_update.html',{'product':product})
And then use the example template above to get it to show on that page.

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>

django model form with bootstrap doesn't work

I am making a website using django but I have a problem with my modelforms. This is my working form code in my html-file:
<form class="form-horizontal" role="form" method="post" action="">
<div class="form-group">
{% csrf_token %}
{{ form.as_p }}
</div>
<input type="submit" value="Inschrijven!" class="btn btn-primary" />
</form>
If i use this code, everything works fine, when I fill in the form and press send, I can see the information from my admin-page.
I now tried to style my form using bootstrap:
<form class="form-horizontal" role="form" method="post" action="">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label class="col-sm-4 control-label">{{ field.label }}</label>
<div class="col-sm-4">
<input type="text" class="form-control" placeholder="{{field.label}} ingeven">
</div>
</div>
{% endfor %}
<input type="submit" value="Inschrijven!" class="btn btn-primary">
</form>
Now I have a nice bootstrap layout but if I fill in the form, I can't see the information at my admin-page.
Does somebody know how I can fix this so I can keep the nice layout and still have my form to work?
When you output Django HTML form, you will notice that it creates input elements with the following ID and Name attributes of the element.
Eg
class MyForm...
name = ...
age = ...
HTML
<input type='text' id='id_name' name='name' ...
<input type='text' id='id_age' name='age'...
To fix your issue, in your HTML add the following attribute to the HTML input field you're generating
id="id_{{field.name}}" name="{{field.name}}"
Reasoning:
When the form is submitted, the browser will send form encoded data in the form of name=value pair, which then arrives in form of dict in request.POST and when fed into Django form, it pre fills the form by matching the Django form attribute name to POST values.