How to pass a form value to another view - django

How to get a form value form one view to another.
for example i would like to get the 'web_input' value from InputWebView() and pass it into DisplayWebView()
<form method="POST" action="">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.web_input }}
<input type="submit">
</form/>
def InputWebView(requests)
form = WebInputForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
return redirect('add_web', web_url=request.POST['web_input'])
def DisplayWebView(request, web_url):
url = web_url

You can use sessions to pass data from one view to another. In InputWebView:
def InputWebView(requests)
form = WebInputForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
request.session['web_input'] = request.POST['web_input']
return redirect('add_web')
In DisplayWebView:
def DisplayWebView(request):
url = request.session.get('web_input')

Related

django model based forms - why isn't form valid?

I'm trying to make model based form but something went wrong.
model:
class Topic(models.Model):
name = models.CharField(max_length=200)
icon = models.ImageField(upload_to = 'images/')
form:
class TopicCreationForm(ModelForm):
class Meta:
model = Topic
fields = '__all__'
view:
def TopicCreateView(request):
form = TopicCreationForm()
if request.method == 'POST':
form = TopicCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
print('aaa') # It displays in console
context = {'form':form}
return render(request, 'blog/topic_form.html', context)
my form html part
<form method="POST">
{% csrf_token %}
<fieldset >
<legend> New Topic</legend>
{{ form|crispy }}
</fieldset>
<div>
<input type="submit" value="submit" class="button-33" role="button">
</div>
</form>
where did i make mistake ?
You need to pass both request.POST and request.FILES [Django-doc], so:
def topic_create(request):
if request.method == 'POST':
form = TopicCreationForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
print('aaa') # It display in console
else:
form = TopicCreationForm()
context = {'form':form}
return render(request, 'blog/topic_form.html', context)
In the HTML form, you need to specify that the files should be encoded with the enctype="…" attribute [mdn]:
<form method="post" enctype="multipart/form-data">
…
</form>

My django form returns empty cleaned_data

I have a simple Form, view and a html that renders the form. but the problem is that the form always returns form.is_valid == False.
So I have checked the cleaned data but I noticed that self.cleaned_data returns an empty list.
Here is the relevant code:
class GraphForm(forms.Form):
from_month = forms.DateField(widget=forms.Select(choices=MONTHS))
from_year = forms.DateField(widget=forms.Select(choices=YEARS))
to_month = forms.DateField(widget=forms.Select(choices=MONTHS))
to_year = forms.DateField(widget=forms.Select(choices=YEARS))
def clean(self):
return self.cleaned_data <<< will always stay be empty
def showgraph(request):
if request.method == 'POST':
form = GraphForm(request.POST)
if form.is_valid():
>>> will never happen <<<
...
...
...
else:
form = GraphForm()
return render(request, 'graph.html', {"form": form})
<form method="post">
{% csrf_token %}
{{ form.from_month }}
{{ form.from_year }}
<br>
{{ form.to_month }}
{{ form.to_year }}
<br>
<p align="center">
<button type="submit" class="btn btn-primary">send</button>
</p>
</form>
Can anyone help with this peculiar problem?
The <form> tag should have action besides method so that the submit button can work, like this.
<form action="{% url 'name_of_the_view' %}" method="post">
...
</form>
If the code doesn't reach inside form.is_valid(), then it means the form is not valid, add an else to if and print the form.errors() and return the same form to template also add form error in the template to see the errors.
def showgraph(request):
if request.method == 'POST':
form = GraphForm(request.POST)
if form.is_valid():
>>> will never happen <<<
else:
print(form.errors())
else:
form = GraphForm()
return render(request, 'graph.html', {"form": form})
Add error for each field:
<span class="text-danger">{{field.errors.as_text|cut:'* '}}</span>

request.FILES empty, though file is present in request

Following the example on the django website I'm trying to upload a file, perform checks on the contents, then feedback to the user and store the file contents.
However, I'm having trouble with the request.FILES which is always empty. My code is as follows (note the output after the print statements):
**forms.py**
class UploadFileForm(forms.Form):
data_import = forms.FileField()
class Meta:
model = Recipe
fields = ('data_import',)
**view**
def recipes_list(request):
template = 'recipes/recipes_list.html'
if request.method == 'GET':
user = request.user
queryset = Recipe.objects.filter(user=user)
form = UploadFileForm()
return render(request, 'recipes/recipes_list.html', context={'recipes': queryset, 'form': form})
elif request.method == 'POST':
print(request.FILES) # <MultiValueDict: {}>
print(request.POST) # <QueryDict: {'csrfmiddlewaretoken': ['...'], 'data_import': ['recette.json']}>
form = UploadFileForm(request.POST, request.POST.data_import)
if form.is_valid():
return HttpResponseRedirect(template)
else:
print(form.errors)
**template**
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">submit</button>
</form>
The error I'm getting is:
<ul class="errorlist"><li>data_import<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
But i can see that the file is uploaded, and is in the request.POST.get('data_import').
I would like to run validation on the form, but I can't do this if request.FILES is empty.
I'm clearly doing something wrong, can someone please point me in the right direction?
<form method="post" enctype= multipart/form-data>
{% csrf_token %}
{{ form }}
<button type="submit">submit</button>
</form>
change your form to the upper one

Including the template doesn't return form field

Here is my form
Class SearchForm(forms.Form):
pub_from = forms.CharField(max_length=20)
pub_to = forms.CharField(max_length=20)
and my SearchView is
def SearchView(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
pub_date_from = form.cleaned_data['pub_date_from']
pub_date_to = form.cleaned_data['pub_date_to']
#form.save()
return HttpResponseRedirect("/admin/")
else:
return render_to_response("search_form.html", {"form":form}, context_instance=RequestContext(request))
else:
form = SearchForm()
context = {"form":form}
return render_to_response("search_form.html", context, context_instance=RequestContext(request))
and my search_form.html is
<form action="" method="get">{% csrf_token %}
{{ form }}
<input type="submit" value="submit">
When I render the form singly it shows the form field and now when I inherit it to another template in category.html doing {% include "search_form.html" %} it only displays the submit button not the form field.
I dont know what am I doing wrong.
What is this???? <form action="" method="get">
the form method is a POST!
This was used by our throwing-stones ancestors:
<input type="submit" value="submit">
We now use button instead of input

Django POST to other view

I have the following form that lives on the site root at /
<form action='/play/' method='post'>
{% csrf_token %}
{{ form.player_name }}
<input id='play' type='submit' value='Play'>
</form>
then I have the view that validates this form:
def login(request):
context = {}
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/play/')
else:
context.update(dict(form=form))
else:
context.update(dict(form=LoginForm(initial={'player_name':'Please tell us your name'})))
return render_to_response('login.html', context, context_instance=RequestContext(request))
And the actual play view:
def play(request):
p1 = briscola.Player(request.POST['player_name'])
The problem is that of course the redirect looses the POST data. But why doesn't it POST directly to the play view by itself when the form.is_valid?