Django Document upload issue does not show "no file selected" - django

I have the following form:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
This produces a form which produces (in [] brackets denotes a button):
**Document:**
[Choose File] no file selected
[Upload]
When I use the following form:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.document }}
<button type="submit">Upload</button>
</form>
I don't get the "no file selected" part in Safari but I do in chrome. Is there some sort of "form.something" that will allow me to have it shown in whatever browser.
Form is as follows:
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('document', )
Model is as follows:
class Document(models.Model):
user = models.ForeignKey(User)
document = models.ImageField(upload_to=user_directory_path)
uploaded_at = models.DateTimeField(auto_now_add=True)
HTML Output for the manual example (in chrome):
<form method="post" enctype="multipart/form-data">
<input type='hidden' name='csrfmiddlewaretoken' value='2ZMTQTumTh5DS4nwVvAZv3IUSpM2o5LB' />
<input id="id_document" name="document" type="file" />
Document
<button type="submit">Upload</button>
</form>
HTML Output for the manual example (in safari):
<form method="post" enctype="multipart/form-data">
<input type='hidden' name='csrfmiddlewaretoken' value='DTLKigyikubFrJqrh4AHR61Lmkyutrsw' />
<input id="id_document" name="document" type="file" />
Document
<button type="submit">Upload</button>
</form>
HTML Output for the automatic example (in safari):
Document:
Upload
Many thanks, Alan.

Have you included (request.FILES) in your views.py file if not add like this .
def view(request):
if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
#Then Save your 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>

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>

Error retrieving value textarea's value from form in 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>

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>

form.is_valid() returning false

I have a Model class.
class Search(forms.Form):
query=forms.CharField()
And, a view function.
def search(request):
c = {}
c.update(csrf(request))
if request.method == 'POST':
form = Search(request.POST)
if form.is_valid():
search_query=form.cleaned_data['query']
return HttpResponse("your query: %s" %search_query , c)
else:
return HttpResponse(form , c)
else:
return render_to_response('polls/search.html', c)
And, here is my search.html:
<form action="/polls/search" method="post">{% csrf_token %}
<p><label for="query_label">query:</label>
<input type="text" name="query_txt" id="query_txt_id" /></p>
<input type="submit" value="Submit" />
</form>
After giving some characters as input, it always show me the following as plain text(Not as error).
"A server error occurred. Please contact the administrator."
The id of your query field is incorrect. Django expects it to be id_query.
You don't need to hardcode your form inputs. If you include {{ form.as_p }} in your template, Django will render the form correctly.
<form action="/polls/search" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
If you really want to hardcode the form in the template, start with the working html that Django produces, and customize it from there. Note that the forms in your template and the snippet below do not display errors. See the docs on customizing the form template for more details.
<form action="/polls/search" method="post">{% csrf_token %}
<p><label for="id_query">Query:</label> <input type="text" name="query" id="id_query" /></p>
<input type="submit" value="Submit" />
</form>