django clear form field after a submit - python

I have an upload form,After every form submit,i want to clear the posted data,actually the form is holding the submitted data.I know that, this problem can be solved if i redirect my page to some other page,but i don't want to redirect my page,because after submitting data,an success message will show in that page.so how can i clear my form without redirecting my page?
this is my views.py file
def UserImageUpload(request):
if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
messages.add_message(request, messages.SUCCESS, 'Your Image upload is waiting for Admin approval')
newdoc = Photo(photo = request.FILES['photo'],watermarked_image=request.FILES['photo'],user = request.user,name = request.POST['name'],description = request.POST['description'],keyword = request.POST['Image_Keyword'],uploaded_time=datetime.datetime.now(),Certified=request.POST['Certification'])
newdoc.save()
else:
messages.add_message(request, messages.ERROR, 'Please Complete All Fields To Submit Your Image')
else:
form = DocumentForm()
uploaded_image = Photo.objects.all()
return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request))
and this is my forms.py file
from django import forms
class DocumentForm(forms.Form):
photo = forms.ImageField(
label='Select A file',)
name = forms.CharField(label='Image Name',max_length=50,widget=forms.TextInput(attrs={'class' : 'form-control',}))
Certification = forms.BooleanField(label='I certify that this is my original work and I am atlest 18 years of age')
description = forms.CharField(label='Image Description',max_length=500,widget=forms.TextInput(attrs={'class' : 'form-control',}))
Image_Keyword = forms.CharField(label='Keywords',widget=forms.TextInput(attrs={'class' : 'form-control',}))

I have solved it.In the views.py ,After saving form just assign the empty form , like that
def UserImageUpload(request):
if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
messages.add_message(request, messages.SUCCESS, 'Your Image upload is waiting for Admin approval')
newdoc = Photo(photo = request.FILES['photo'],watermarked_image=request.FILES['photo'],user = request.user,name = request.POST['name'],description = request.POST['description'],keyword = request.POST['Image_Keyword'],uploaded_time=datetime.datetime.now(),Certified=request.POST['Certification'])
newdoc.save()
#Assign the empty form,it will empty the form after a successful form submission
form=DocumentForm()
else:
messages.add_message(request, messages.ERROR, 'Please Complete All Fields To Submit Your Image')
else:
form = DocumentForm()
uploaded_image = Photo.objects.all()
return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request))
no need to Redirect Your page.

While Rego's answer is technically correct, Django best practices dictate that you do a HttpResponseRedirect after a form submission. This reduces the likelihood of accidental multiple submissions.
You have two options for sending data to the redirected page: you could either redirect to a page that indicates the form was submitted successfully, and/or you can use session variables.
http://docs.djangoproject.com/en/stable/topics/http/sessions/
Since you can't send your view's local variables to a view that you redirect to, you can save that data in session variables that will be available to any subsequent sessions until it expires or is deleted.
For instance, you could put the user's name in a session variable in one view:
# view.py (the one with the form)
request.session['name'] = form.cleaned_data['name']
And then in the view that processes your success notice:
# view.py (form submission successful)
string = "Hi there, " + request.session['name'] + "! How are you today?"
This is preferable to not doing a redirect as strongly suggested by the Django gods.

It is strongly advised to do a redirect after a form submission to prevent accidental duplicate submissions (see Post/Redirect/Get).
You can use Django's messages framework to show messages after the redirect. In your view:
from django.contrib import messages
from django.shortcuts import redirect, render
# ...
def UserImageUpload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
# ... (do something with the submitted form data here) ...
# The message that will be shown on subsequent displays of the template:
messages.add_message(request,
messages.SUCCESS,
'Your Image upload is waiting for Admin approval')
# Redirect back to this view.
# Attention: Change '...' to the name or URL of this view.
return redirect('...')
else:
form = DocumentForm()
return render(request, 'myprofile/user_image_upload.html', {
'form': form,
'uploaded_image': Photo.objects.all(),
})
Then, you need to adjust your template (i.e. myprofile/user_image_upload.html) to be able to show the message during the next rendering of the template. Add something like this to your template:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
Read the reference for more details about displaying messages in your template.

Related

How can I get information about the logged-in user in a Django application?

How can I get information about the logged-in user in a Django application?
What I want to do is get the user information from Logged-in user and put additional information and store in a database(models.py).
So in views.py:
def registerView(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login_url')
else:
form = UserCreationForm()
return render(request, 'main/register.html',{'form':form})
here how do I grab the users information
There are several ways for get information from authenticated user in django
1) In the view
You can use request.user like this :
def test_user(request):
if request.user.is_authenticated:
# Do some stuff with the user = request.user
my_user = request.user
my_user.email = 'demo_user#yopmail.com'
my_user.save()
else:
# The user is not authenticated
# You can't do anything i guess
return render(request, 'template/logged_in_user.html')
2) In the template
<!-- Show something to the authenticated user -->
{% if user.is_authenticated %}
<h1> Hi {{ user.name }} </h1>
{% else %}
<!-- Show something to the guess user -->
<h1> Hi Guess ! </h1>
{% endif %}

Display User Profile getting ERROR: 'AnonymousUser' object has no attribute '_meta'

I have a simple view that is suppose to check if there is post data,
if so update the user data using UserChangeForm. Else get the form
data of user and display.
Issue: AttributeError at /profile/edit 'AnonymousUser' object has no
attribute '_meta'
I think it might be this line in the edit_profile view
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
Not sure what. Here is the view.py edit_profile
def edit_profile(request):
# Handle post request - if the user submits a form change form details and pass the intance user
if request.method == 'POST':
form = UserChangeForm(request.POST, intance=request.user)
if form.is_valid():
form.save()
return redirect('accounts/profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
profile_edit.html
{% extends 'base.html' %}
{% block head %}
<title>Profile</title>
{% endblock %}
{% block body %}
<div class="container">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save Changes</button>
</form>
</div>
{% endblock %}
You can't update an AnnonymousUser (that is special user class set for not logged in users). One solution of your problem is to disallow viewing this page by not authenticated user by decorating your view using login_required decorator.
You got error because there is not user logged in.
You can instead use try method.
In your code use if user.is_authenticated
if user.is_authenticated():
if request.method == 'POST':
form = UserChangeForm(request.POST, intance=request.user)
if form.is_valid():
form.save()
return redirect('accounts/profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
else:
raise PermissionDenied

Django form.py not updating

I have been going through the Django forms 'tutorial'. Once I had read through the tutorial, I tried modifying it to suit my needs and customize it to learn it Django forms well. I discovered whenever I modified the form, the website would not update. I assume its an error with my code, but I have not been able to find it.
# views.py
def contact(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ContactForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/message_recived/')
# forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(label='Name', max_length=100)
email = forms.EmailField(label='Email', max_length=100)
message = forms.CharField(label='Message', max_length=500)
# models.py
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
message = models.CharField(max_length=500)
and here is the contact.html template:
#contact.html
{% extends "BlogHome/headerAndFooter.html" %}
{% block content %}
<script>
document.title = "Pike Dzurny - Contact"
</script>
<form action="/message_recived/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
Did I do something wrong? I have tried clearing my browsers cache, using a new browser, and obviously refreshing it.
Looks like your forget to render response inside your view.
Also you need to include form into context to render template right.
Try to change view as follow:
def contact(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ContactForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/message_recived/')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})

Django form in the base template. How to display validation error?

I use Django 1.8.14. I have Search form on every page of my website. I pass Search form to base template through context processor. Each time form sends data to /search/ view. And there is a problem. Django raises ValidationError on form, but it doesn't display anywhere. What is the correct way to display form errors in template, when form passes to base template through context processor and sends data to one view?
form.py:
class SearchForm(forms.Form):
search = forms.CharField(required = True,
max_length=255,
widget = forms.TextInput({'class':'form-control', 'type':'search','required':''})
)
def clean_search(self):
search = self.cleaned_data.get("search")
regex = myregex
if not re.match(regex, search):
print("ValidationError")
raise forms.ValidationError(u'Please enter a valid value')
return search
context processor:
from myproject.forms import SearchForm
def form_context(request):
context_dict = {}
context_dict['search_form'] = SearchForm()
return(context_dict)
my base template:
<form method="post" action="/search/">
{% csrf_token %}
{{ search_form.non_field_errors }}
{{ search_form.errors }}
{{ search_form.search }}
{{ search_form.search.errors }}
<button type="submit" class="btn btn-find">Search</button>
</form>
my seach view:
def search(request, template):
if request.method == 'POST':
search_form = SearchForm(request.POST)
if search_form.is_valid():
domen = search_form.cleaned_data['search']
try:
site = SitePage.objects.get(domen=domen)
path="/"+site.domen +"/"
return HttpResponseRedirect(path)
except:
site = None
else:
print search_form.errors
return render(request, template, context_dict)
If you Django is raising validation error how you want it to and now all you need is to display that validation error on your html templates then i suppose what you are looking for is Django Messages
See the official documentation for the same -> https://docs.djangoproject.com/en/1.8/ref/contrib/messages/
You need to pass the form once it is bound to the data (the POST request) and validated; right now your context only has a blank form which is why no errors are being displayed.
from django.shortcuts import redirect
def search(request, template):
search_form = SearchForm(request.POST or None, request.FILES or None)
if search_form.is_valid():
domen = search_form.cleaned_data['search']
results = SitePage.objects.filter(domen=domen)
if results.exists():
return redirect('/{}/'.format(results.domen))
return render(request, template, {'form': search_form})

Not able to redirect a Django form after submission

I am a newbie to Django and a form I created is giving me a bit of trouble.
I have create a form in Django for user authentication and login. But the form is not redirecting to the link I've specified after hitting submit. I think this is because the authentication function in views.py is returning the user as None. But this should not happen because the user exists in the database. I've confirmed this by going to http://127.0.0.1:8000/admin/, which is Django's internal developer server.
The URL that I'm trying to redirect it to exists. No problems there.
The python files related to this are:
forms.py:
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'email', 'password']
views.py:
I've omitted all the imports in the following code. No problems there.
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form.html'
def get(self, request): # This function is executed if the server obtains a GET request.
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
'''
The server gets a GET request every time a new user wants to register, i.e they want an empty form.
That's why we pass None in the function above.
It gets a POST request every time a filled form is submitted.
'''
def post(self, request): # This function is executed if the sever recevies a POST request.
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False) # This creates an object, but does not save it to the database.
# Therefore, we can do some changes.
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# Here, cleaned_data is converted data to suitable format. Like the date entered is converted to a
# suitable format as its format is different all around the world.
# Now you can change the username by user.username = 'some_name' or you can change the password by
# user.set_password(new_password)
user.save() # This line of code actually saves the code.
user = authenticate(username=username, password=password)
# This checks if the user actually exists in the database.
if user is not None:
if user.is_active: # This if the user is not banned or anything like that.
login(request, user) # This logs in the user.
return redirect('music:index') # Redirects the user to index page.
else:
return render(request, self.template_name, {'form': form})
else:
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# This returns the filled form again if the the form is not valid.
The registration form template is (html file) :
{% extends 'music/base.html' %}
{% block title%}Registration Form {% endblock %}
{% block body %}
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'music/index_style.css' %}" />
<div class="block">
<form action="" method="post" >
{% csrf_token %}
<fieldset> <!-- Gives it a better look by putting a heading and background around the form -->
<legend>Create a new account:</legend><!-- This the common heading for the form -->
{% include 'music/form_template.html' %}
<br>
<input type="submit" value="Submit">
</fieldset>
</form>
</div>
{% endblock %}>
The form_template.html included in the registration form template is:
{{ form.non_field_errors }}
{{ form.errors }}
{{ form.as_p }}
Also, one other thing that is not normal is that whenever I create a new user by using the above form, the password for that user is being shown as:
"Invalid password format or unknown hashing algorithm."
This can be seen at http://127.0.0.1:8000/admin/ where we can edit the current users.
There are a few issues here.
You correctly call save with commit=False, to allow you to set the hashed password before saving properly (as the comments state), but you never actually do so, so the user is saved with an unhashed password. This will never validate.
Similarly, you never set the user's is_active property, so the check a bit further down will always fail.
user = form.save(commit=False)
password = form.cleaned_data['password']
user.set_password(password)
user.is_active = True
user.save()

Categories

Resources