View not receiving POST data from image upload page - python

I've seen similar questions but can't figure this out, I have a program that upload pictures on a model:
views.py:
def upload_pic(request):
if request.method == "POST":
image_form = ImageUploadForm(request.POST, request.FILES)
if image_form.is_valid():
image_form.save()
return HttpResponse('success')
else:
return HttpResponse('fail')
return render(request, 'tracker/upload_pic.html', {"image_form": image_form})
template:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<body>
<form method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ image_form.img }}
<input type="submit" value="submit" />
</form>
</body>
</html>
urls.py:
urlpatterns = [
url(r'^upload_pic', views.upload_pic, name='upload_pic')
]
Just trying to save to the user model so I can retrieve it later, but I can't access any POST data, I've also tried add action = "{% url upload_pic %}" to my form in the HTML template, but I get the NoReverseMatch error
class ImageUploadForm(forms.ModelForm):
#model to store the information about the pictures
class Meta:
model = ExtendedProfile
exclude = ()

You need to add action on your form so it will retrieve the url name.
<form action="{% url 'upload_pic' %}" method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ image_form.img }}
<input type="submit" value="submit" />
</form>
You forgot the '' on upload_pic.

Related

Don't return forms in context if they are not altered?

In my HTML-file I have a submit button (click_button) to do stuff and a submit button for a Django form (form_submit).
All submits are redirected to one View-function (get_post_from_submit). If using the return render() function, I always have to return the context including the form, but I have no information of the form when I pressed the click_button.
Is there any way to not return the form again?
home.html
....
<body>
{% load bootstrap4 %}
<form action="" method="POST" novalidate>
{% csrf_token %}
{% bootstrap_form form %}
</form>
<form action="" method="POST" novalidate>
{% csrf_token %}
<button class="btn btn-primary" name="click_button" type="submit">Grafik</button>
</form>
</body>
....
views.py
def get_post_from_submit(request):
if request.method == 'POST':
if "book_field" in request.POST:
# Do Stuff
form = form_book(request.POST)
if "click_button" in request.POST:
# Do Stuff
# Here the form always gets a reset, because I have no Info about the form in POST but it is needed as context...
form = form_book()
return render(request, 'home.html',{"form": form})
One method would be to encapsulate just one form tag across both sections.
<form action="" method="POST" novalidate>
{% bootstrap_form form %}
<input type="submit" name="action" value="FormSubmit"/>
{% csrf_token %}
<input type="submit" name="action" value="Grafik"/>
</form>
Using name="action" you can differentiate the POST action in the view like so:
def get_post_from_submit(request):
if request.method == 'POST':
form = form_book(request.POST)
if request.POST['action'] == 'FormSubmit':
[...]
elif request.POST['action'] == 'Grafik':
[...]
return render(request, 'home.html',{"form": form})
The form_book will no be able to retain the form data whenever the Grafik POST type is send to the view.

What is the simplest way to get user input in Django?

I want to get some user input, process it a little and present the same to the user. I need not save the inout to the database. What is the simplest way to do that in Django
In the html template
<form method="POST">
{% csrf_token %}
{{ form.name of field in forms.py }}
</form>
In the views.py
if request.POST:
form = formName(request.POST)
if form.is_valid():
variable: form.cleaned_data['name of field in forms.py']
this is a simple example
views.py
def test_form(request):
if request.method == "POST":
user = request.POST.get('username')
if user == "mark":
return HttpResponse('hello mark')
return render(request, "form.html")
urls.py
path ('form/', test_form, name="form")
form.html
<form method="POST" action="{% url 'form' %}">{% csrf_token %}
<input type="text" name="username">
<input type="submit" name="submit">
</form>

Django url parameters in html code

I am trying to pass the id of a todolist item to my html code so that everything works when I am editing the todolist item and I click submit.
In views.py:
def edit(request, id):
todo = Todo.objects.get(id=id)
context = {
'todo': todo
}
if(request.method == 'POST'):
title = request.POST['title']
text = request.POST['text']
todo.title = title
todo.text = text
todo.save()
return redirect('/todos')
else:
return render(request, 'edit.html', context)
In urls.py:
url(r'^details/(?P<id>\w{0,50})/edit/$', views.edit, name='edit')
In HTML:
<h2>Edit Todo- {{ todo.title }}</h2>
<form action="{% url 'edit' request.todo.id %}" method="post">
{% csrf_token %}
<label for="title">Title</label> <br/>
<input type="text" name="title" id="title"/>
<br>
<label for="text">Text</label> <br/>
<textarea type="text" name="text" id="text"></textarea>
<br><br>
<input type="submit" value="Submit"/>
</form>
I think the problem is in my url in the html code. I can't figure out how to pass my todolist item's id parameter.
The error I keep getting is
invalid literal for int() with base 10: ''
Please help
The problem is there:, do not use "request", the object sent through context is "todo":
<form action="{% url 'edit' todo.id %}" method="post">{% csrf_token %}
Or you may leave it blank. Blank means the current displayed views
<form action="" method="post">{% csrf_token %}

Django url not found upon submitting form

My apologies if the question is stupid, I am a newbie to this. I am creating a django web application. I have created a form inside it. When I submit the form, it says 'url' not found even though the same URL loads fine for the first time when opening the form. This is whats confusing me. Here is my code:
#forms.py
class Recipe_ruleForm(forms.ModelForm):
class Meta:
model = Recipe_rule
fields = ('content',)
#urls.py
url(r"^create_recipe_rule/(?P<recipe_pk>[0-9]+)/$",views.create_recipe_rule, name="create_recipe_rule"),
#views.py
def create_recipe_rule(request, recipe_pk):
form = Knowledgebase_ruleForm
selected_recipe = Recipe.objects.get(pk = recipe_pk)
if request.method == 'POST':
form = Recipe_ruleForm(request.POST)
if form.is_valid():
#current_user = request.user
data = form.cleaned_data
recipe_rule_data=Recipe_rule.objects.create(recipe=selected_recipe, content=data['content'])
recipe_rule_data.save()
recipe_rule = Recipe_rule.objects.get(pk = recipe_rule_data.pk)
recipe=selected_recipe
recipe = Recipe.objects.get(pk = recipe.pk)
return redirect('recipe_detail', pk=recipe.pk)
else:
messages.error(request, "Error")
return render(request, 'create_recipe_rule.html' , {'form': form})
Here is the error when I submit the form:
Page not found (404) Request Method: POST Request
URL: http://[ip_adress]:[port]/create_recipe_rule/
UPDATE:
Here is my template:
{% extends "account/base.html" %}
{% load i18n %}
{% load bootstrap %}
{% block body_class %}applications{% endblock %}
{% block head_title %}{% trans "Create recipe" %}{% endblock %}
{% block body %}
<form action="/create_recipe_rule/" method="post">
{% csrf_token %}
<div class="form-group">
<label for="{{ form.content.label }}">{{ form.content.label }}:</label>
<textarea type="{{ form.content.type }}" name="{{ form.content.name }}" max_length="500" class="form-control" id="{{ form.content.id }}"></textarea>
</div>
<input class="btn btn-default" type="submit" value="submit">
</form>
{% endblock %}
You have action="/create_recipe_rule/", which is missing the recipe id.
One option is to simply remove the action from the form, then your browser will submit the request to the current url.
<form method="post">
If you do want to include the form action, then first you need to update your view so that it includes the recipe id in the template context.
return render(request, 'create_recipe_rule.html' , {'form': form, recipe_id: recipe_id })
Then you can update the form action to include the recipe id.
action="/create_recipe_rule/{{ recipe_id }}"
It's good practice to use the {% url %} tag, so that you are not hardcoding urls in the template:
action="{% url 'create_recipe_rule' recipe_id %}"

django-why this form is always invalid

i have created a form with minimal fields(for testing) , but it never enters form.is_valid()
Here is the minimal code
in the models.py
from django.db import models
class sample(models.Model):
field1=models.CharField(max_length=100)
field2=models.CharField(max_length=100)
in the forms.py
from django.forms import ModelForm
from app.models import sample
class someform(ModelForm):
class Meta:
model=sample
in the views.py
some imports
def index(request):
return render(request, 'app/index.html')
def contact(request):
if request.method=='POST':
form=someform(request.POST)
if form.is_valid():
field1=form.cleaned_data['field1']
field2=form.cleaned_data['field2']
return HttpResponse("valid")
else:
return HttpResponse("invalid")
else:
form=someform()
return HttpResponse("error")
The problem is , it never enters (if form.is_valid()) . Am i missing something ? please help
in the index.html
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input type="submit" id="submit" name="submit">
</form></body></html>
First pass your form to index.html, when the request is not POST in views.py:
else:
form=someform()
return render(request, 'index.html', locals())
In template you should make it like this:
<form action="contact" method="POST" xmlns="http://www.w3.org/1999/html">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn">Submit</button>
</form>
When receiving the POST query, Django is looking for the 2 fields of IDs id_field1 and id_field2, litteraly, thus your HTML is to be the following:
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="id_field1" name="field1">
<input type="text" id="id_field2" name="field2">
<input type="submit" id="submit" name="submit">
</form>
</body>
</html>
Another solution is to use the {{ form.as_p }} or {{ form.as_table }} to render the inputs inside or tags automatically.
You could also add {{ form.non_field_errors }}, {{ form.field1.errors }}, and {{ form.field2.errors }} in your current HTML to display the form errors when validation fails.

Categories

Resources