When i click submit it is showing csrf verification failed eventhough i used {% csrftoken %}
here my view.py:
#csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/login/')
else:
form = RegistrationForm()
catagories = Company_Profile.objects.all()
variables = RequestContext(request, {
'form': form,'catagories' : catagories
})
return render_to_response(
'index1.html',
variables
)
my html page index1.html s:
<div id="connect_signup_box" class="connect_box_form clearfix">{% csrf_token %}
<form enctype="application/x-www-form-urlencoded" class="global_form" action="" method="POST">{% csrf_token %}<div><div><h3>Create Account</h3>
<div class="form-elements" >
<div id="name-wrapper" class="form-wrapper"><div id="name-label" class="form-label"><label for="name" class="optional">Name</label></div>
<div id="name-element" class="form-element">
<input type="text" name="name" id="name" value="" class="signup-name"></div> </div>
<div id="username-wrapper" class="form-wrapper"><div id="username-label" class="form-label"><label for="id_username">Username:</label></div>
<div id="username-element" class="form-element">
<input id="id_username" max_length="30" name="username" required="True" type="text">
<div id="uJTtr4FGLy-wrapper" class="form-wrapper"><div id="uJTtr4FGLy-label" class="form-label"><label for="id_email">Email Id:</label></div>
<div id="uJTtr4FGLy-element" class="form-element">
<input id="id_email" max_length="30" name="email" required="True" type="text">
<p class="description">You will use your email address to login.</p></div> </div>
<div id="password-wrapper" class="form-wrapper"><div id="password-label" class="form-label"><label for="id_password1">Password:</label></div>
<div id="password-element" class="form-element">
<input id="id_password1" name="password1" type="password">
<p class="description">Passwords must be at least 6 characters in length. </p></div></div>
<div id="passconf-wrapper" class="form-wrapper"><div id="passconf-label" class="form-label"><label for="id_password2">Password (Confirm):</label></div>
<div id="passconf-element" class="form-element">
<input id="id_password2" max_length="30" name="password2" render_value="False" required="True" type="password">
<p class="description">Enter your password again for confirmation.</p></div> </div>
<p class="description">This will be the end of your profile link, for example: <br> </p></div></div>
</div></div>
<div id="terms-wrapper" class="form-wrapper"><div id="terms-label" class="form-label"> </div><div id="terms-element" class="form-element">
<input type="hidden" name="terms" value=""><input type="checkbox" name="terms" id="terms" value="1" tabindex="7">
<label class="null" for="terms">I have read and agree to the <a target="_blank" href="help/terms.html">terms of service</a>.</label></div></div>
<div id="submit-wrapper" class="form-wrapper"><div id="submit-label" class="form-label"> </div><div id="submit-element" class="form-element">
<input type="hidden" name="csrfmiddlewaretoken" value="vmGTjibc4wzzsrVshrElFs8J0T24UECG">
<input type="submit" class="btn btn-success" value="submit">
<input type="reset" class="btn" value="cancel">
</div></div></div></form> </div>
</div>
i am not using form.as_p since i need it individually to apply css..
please help me
edit:
i got the answer
the actual problem is i have hardcoded csrf i.e
so removed it and it works fine. thanks to # Daniel Roseman who noticed me that and thanks to all for helping me.
You should pass the RequestContext as the third argument of the render_to_response():
return render_to_response('index1.html',
{'form': form, 'catagories': catagories},
RequestContext(request))
Or, as a better option, use the render() function instead of the render_to_response():
from django.shortcuts import render
return render(request, 'index1.html', variables)
You need to move the {% csrf_token %} tag - put it within the form. Also, if you are using django.middleware.csrf.CsrfViewMiddleware, you do not have to manually csrf_protect your view.
And for the context instance, try doing it like this:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/login/')
else:
form = RegistrationForm()
catagories = Company_Profile.objects.all()
variables = {'form': form,'catagories' : catagories}
return render_to_response('index1.html', variables, context_instance=RequestContext(request))
Related
I'm working on a django project website. When submitting a form I need to save the data and show a message with from django.contrib import messagesmodule. It works perfectly with saving data but it never shows the message and redirecting to the same page.
Views.py class.
def showIndex(request):
if request.method == 'POST':
contact = Contact()
name = request.POST.get('name')
email = request.POST.get('email')
message = request.POST.get('message')
contact.name = name
contact.email = email
contact.message = message
print('yes and no ')
messages.success(request, 'Profile details updated.')
contact.save()
return render(request,'index.html')
return render(request,'index.html')
and this is the codes in index.html. I have created the form here.
<form method="POST" class="u-clearfix u-form-spacing-30 u-form-vertical u-inner-form" style="padding: 10px">
{% csrf_token %}
<div class="u-form-email u-form-group u-form-partition-factor-2">
<label for="email-319a" class="u-label u-text-body-alt-color u-label-1">Email</label>
<input type="email" placeholder="Enter a valid email address" id="email-319a" name="email" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" />
</div>
<div class="u-form-group u-form-name u-form-partition-factor-2">
<label for="name-319a" class="u-label u-text-body-alt-color u-label-2">Name</label>
<input type="text" placeholder="Enter your Name" id="name-319a" name="name" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" />
</div>
<div class="u-form-group u-form-message">
<label for="message-319a" class="u-label u-text-body-alt-color u-label-3">Message</label>
<textarea placeholder="Enter your message" rows="4" cols="50" id="message-319a" name="message" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required=""></textarea>
</div>
<div class="u-align-left u-form-group u-form-submit">
Submit
<input type="submit" value="submit" class="u-form-control-hidden" />
</div>
</form>
<div>
{%for message in messages%}
{{message}}
{%endfor%}
</div>
You have to pass the messages variable to the render method:
render(request,'index.html', {'messages': messages})
I can't render form username on the template. like I want to to render the form fields automatically which I defined in forms.py file but it's not working. here you go below for my detailed files
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
My views
from .forms import CreateUserForm
Registration
def regPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'web/car-finder-home.html')
html
<form class="needs-validation" method="POST" action="">
{% csrf_token %}
<div class="mb-4">
<label class="form-label text-light" for="signup-name">Username</label>
{{ form.username }}
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-email">Email address</label>
<input class="form-control form-control-light" type="email" id="signup-email" placeholder="Enter your email" required />
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-password">Password <span class="fs-sm opacity-50">min. 8 char</span></label>
<div class="password-toggle">
<input class="form-control form-control-light" type="password" id="signup-password" minlength="8" required />
<label class="password-toggle-btn" aria-label="Show/hide password"> <input class="password-toggle-check" type="checkbox" /><span class="password-toggle-indicator"></span> </label>
</div>
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-password-confirm">Confirm password</label>
<div class="password-toggle">
<input class="form-control form-control-light" type="password" id="signup-password-confirm" minlength="8" required />
<label class="password-toggle-btn" aria-label="Show/hide password"> <input class="password-toggle-check" type="checkbox" /><span class="password-toggle-indicator"></span> </label>
</div>
</div>
<div class="form-check form-check-light mb-4">
<input class="form-check-input" type="checkbox" id="agree-to-terms" required />
<label class="form-check-label" for="agree-to-terms">
<span class="opacity-70">By joining, I agree to the</span> Terms of use <span class="opacity-70">and</span> Privacy policy
</label>
</div>
<button class="btn btn-primary btn-lg w-100" type="submit">Sign up</button>
</form>
views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from .forms import CreateUserForm
def regPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
# consider adding a redirect page here this is a good approach
else:
context = {'form':form}
return render(request, 'web/car-finder-home.html',context) # your forgot to add context
Now inside your template you can access the form...
I didn't add in core urls.py
from my_app_name import urls
urlpatterns = [
path('cars/', views.regPage, name="register"),
]
xD
I am trying to submit a Message form for my Django Project but I keep receiving an error:
AttributeError at /
'MessageForm' object has no attribute 'cleaned_data'
I am not sure what is the reason for getting this error although I revised the https://docs.djangoproject.com/en/3.1/topics/forms/
Here is my views.py
def home(request):
if request.method == 'POST': #Check Post
form = MessageForm(request.POST)
if form.is_valid():
data = MessageForm() #Create Relationship with Model
data.name= form.cleaned_data['name']
data.email= form.cleaned_data['email']
data.message= form.cleaned_data['message']
data.ip = request.META.get('REMOTE_ADDR')
data.save()
messages.success(request,'Your Message has been sent, Thank you!')
return HttpResponseRedirect('base:home')
template_name = 'base/home.html'
form = MessageForm()
----------------------other unrelated contexts--------------------
context = {
'form': form,
}
return render(request, template_name, context)
Here is the urls.py
urlpatterns = [
path('', views.home,name='home')
]
Here is the template.html
<form class="form" id="form" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input name="name" id="form-name" type="text" placeholder="Your Name" class="form-control input" autocomplete="off"/>
<div id="name-error"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input name="email" id="form-email" type="email" class="form-control input" placeholder="Your E-Mail" autocomplete="off">
<div id="email-error"></div>
</div>
</div>
</div>
<div class="form-group">
<textarea name="message" id="form-message" class="form-control input" rows="7" placeholder="Your Message here ..." autocomplete="off"></textarea>
<div id="message-error"></div>
</div>
<!-- Messages -->
{% if messages %}
{% for message in messages %}
<div class="container">
<div class=" alert alert-{{ message.tags }}">
{{ message }}
</div>
</div>
{% endfor %}
{% endif %}
<!-- Messages -->
<input id="form-submit" type="submit">
<div class="send-message" >
Send <i class="ni ni-send"></i>
</div>
</form>
You are constructing a new form, but that does not make much sense. Once your orignal form is validated, you can save that form, so:
def home(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.instance.ip = request.META.get('REMOTE_ADDR')
form.save()
messages.success(request,'Your Message has been sent, Thank you!')
return redirect('base:home')
# …
I have form, user must fill it and submit but I have no reaction from this form
First I thought there is a problem with action directive of the form, so used redirect method in the views but no help
def organization_info(request):
organization_form = OrganizationInformationForm()
context = {
'organization_form': organization_form
}
if request.method == "POST":
print("POST")
organization_form = OrganizationInformationForm(request.POST, request.FILES)
if organization_form.is_valid():
print("VALID")
new_org = OrganizationInformation.objects.create(**organization_form.cleaned_data)
print("FILLED")
return redirect(organization_list)
return render(request, 'organization_form.html', context)
<form method="POST" enctype="multipart/form-data" class="form-horizontal">
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-sm-4 control-label">Organization Name:</label>
<div class="col-sm-4">
{{ organization_form.name }}
</div>
.
.
<div class="form-group">
<div class="col-sm-4 col-sm-offset-4">
<button type="submit" class="btn btn-pink">Submit</button>
</div>
</div>
</form>
I only have the "POST" printed on the log no any errors
add form handler path in action and try again
<form method="POST" enctype="multipart/form-data" class="form-horizontal" action={'your form handler path'}>
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-sm-4 control-label">Organization Name:</label>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-4">
<button type="submit" class="btn btn-pink">Submit</button>
</div>
</div>
</form>
You need to add an action attribute to your form.
<form method="POST" enctype="multipart/form-data" class="form-horizontal" **action="url-of-handler"**>
</form>
More on this topic: https://www.w3schools.com/tags/att_form_action.asp
I am passing context from view.py file
def change_password(request,pk=None):
user = MyUser.objects.get(pk=pk)
if request.method == "POST":
form = PasswordChangeForm(user=user, data=request.POST)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return render(request, "nurse/change_password.html", {"user_id":user.id}) // passing user_id as context
I can see this value in my html file
<div class="form-group">
<label class="control-label allign col-sm-3" > {{user_id}} Old Password </label> // user_id is giving the right value
</div>
But when i try to fetch the same in action than it is not working:
<form class="form-horizontal login-box2" action="{% url 'booking:change_password' user_id %}" role="form" method="post"> // not getting user_id here
<div class="form-group">
<label class="control-label allign col-sm-3" > {{user_id}} Old Password </label> // getting user_id here
</div>
<div class="form-group">
<li> <button type="submit" class="btn btn-primary f-w-b f-s-18">Change</button> </li>
</div>
</form>
Can anyone tell me what i am doing wrong?
Thanks
EDITED
adding urls.py code:
url(r'^change_password/(?P<pk>[0-9]+)/$',views.change_password,name='change_password'),