Forbidden (403) CSRF verification failed Request aborted - django

I am getting a 403 error while I tried most of the responses in the forum to the same problem, but no luck! This registration code is originally from tango with django site, but it is not working on django 1.10.
Any help would be appreciated, here are the files I use:
views.py:
def register(request):
# Like before, get the request's context.
context = RequestContext(request)
# A boolean value for telling the template whether the registration was successful.
# Set to False initially. Code changes value to True when registration succeeds.
registered = False
# If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST':
# Attempt to grab information from the raw form information.
# Note that we make use of both UserForm and UserProfileForm.
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
# If the two forms are valid...
if user_form.is_valid() and profile_form.is_valid():
# Save the user's form data to the database.
user = user_form.save()
# Now we hash the password with the set_password method.
# Once hashed, we can update the user object.
user.set_password(user.password)
user.save()
# Now sort out the UserProfile instance.
# Since we need to set the user attribute ourselves, we set commit=False.
# This delays saving the model until we're ready to avoid integrity problems.
profile = profile_form.save(commit=False)
profile.user = user
# Did the user provide a profile picture?
# If so, we need to get it from the input form and put it in the UserProfile model.
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
# Now we save the UserProfile model instance.
profile.save()
# Update our variable to tell the template registration was successful.
registered = True
# Invalid form or forms - mistakes or something else?
# Print problems to the terminal.
# They'll also be shown to the user.
else:
print (user_form.errors, profile_form.errors)
# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else:
user_form = UserForm()
profile_form = UserProfileForm()
# Render the template depending on the context.
return render_to_response(
'heaven/register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home,name='home'),
url(r'^home/', views.home, name='home'),
url(r'^register/', views.register, name='register'), # ADD NEW PATTERN!
]
html template:
<!DOCTYPE html>
<html>
<head>
<title>Heavenly</title>
<style>
*{font-family:Arial}
h1 {color:red;}
</style>
</head>
<body>
<h1>Register with Heavenly</h1>
{% if registered %}
<strong>thank you for registering!</strong>
Return to the homepage.<br />
{% else %}
<strong>register here!</strong><br />
<form id="user_form" method="post" action="/register/"
enctype="multipart/form-data">
{% csrf_token %}
<!-- Display each form. The as_p method wraps each element in a paragraph
(<p>) element. This ensures each element appears on a new line,
making everything look neater. -->
{{ user_form.as_p }}
{{ profile_form.as_p }}
<!-- Provide a button to click to submit the form. -->
<input type="submit" name="submit" value="Register" />
</form>
{% endif %}
</body>
</html>

https://docs.djangoproject.com/en/1.10/releases/1.10/#features-removed-in-1-10
The dictionary and context_instance parameters for the following functions are removed:
django.shortcuts.render()
django.shortcuts.render_to_response()
django.template.loader.render_to_string()
Use render instead.
https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render

Related

Django update view only seems to work with regex urls

I am getting my hands dirty with Django and have a simple use case in which i have to create a function based view for updating a Model. Below is my function based view function:
def update_post(request, id=None):
obj = get_object_or_404(PostModel, id=id)
form = PostModelForm(request.POST or None, instance=obj)
if form.is_valid():
obj = form.save(commit=False)
print(f"The object that i am going to save is {form.cleaned_data}")
obj.save()
messages.success(request, f"Updated object with id {id}")
return HttpResponseRedirect(f"/blog/read/{id}")
context = {
"form": form
}
return render(request, "blog/update-post.html", context)
Below is my update-post.html:
<html>
<form method="POST" action="."> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="Change">
</form>
</html>
And this is my urls.py file :
from django.urls import path, include
from django.conf.urls import url
from .views import list_posts, read_post, create_post, update_post
app_name = "blog"
urlpatterns = [
path('posts/', list_posts, name="list"),
path('read/<int:id>', read_post, name="read"),
path("create/", create_post, name="create"),
#url(r'^(?P<id>\d+)/edit/$', update_post, name="update")
path("update/<int:id>", update_post, name="update"),
]
The update view only seems to work when i use the above regex url pattern for editing the post .
Otherwise i get the below error message:
Can someone please tell me where i am going wrong with this.

Django: form works in index but not in a particular page

I'm having multiple forms around my website.
However, a have a particular form that is working in the home page (index.html), but when coping this particular form in a section of my site it doesn't work anymore (on this section, if I return to home everything works as expected).
What am I missing?
Views.py:
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from .models import Treasure, TamaniosCantidades
from .forms import TreasureForm, TamaniosCantidadesForm, LoginForm
from django.contrib.auth import authenticate, login, logout
# Create your views here.
def index(request):
treasures = Treasure.objects.all()
form = TreasureForm()
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/index.html', {'treasures': treasures,
'form': form,
'tamanioscantidades_form': tamanioscantidades_form})
def productos(request):
treasures = Treasure.objects.all()
form = TreasureForm()
return render(request, 'main_app/productos.html', {'treasures': treasures,
'form': form})
def die_cut(request):
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/die-cut-stickers.html', {'tamanioscantidades_form': tamanioscantidades_form})
def post_tamanioscantidades(request):
form = TamaniosCantidadesForm(request.POST)
if form.is_valid():
tamanioscantidades = TamaniosCantidades(tamanios=form.cleaned_data['tamanios'],
cantidades=form.cleaned_data['cantidades'])
# tamanioscantidades = tamanioscantidades_form.save(commit = False)
# tamanioscantidades.usuario = request.user
tamanioscantidades.save()
return HttpResponseRedirect('/')
def post_treasure(request):
form = TreasureForm(request.POST)
if form.is_valid():
treasure = Treasure(name=form.cleaned_data['name'],
value=form.cleaned_data['value'])
treasure.save()
return HttpResponseRedirect('/')
urls.py:
app_name = 'main_app'
urlpatterns = [
path('', views.index),
path('productos/', views.productos),
path('productos/die-cut-stickers', views.die_cut, name='die-cut-stickers'),
path('post_url/', views.post_treasure, name='post_treasure'),
path('post_url_tamanioscantidades/', views.post_tamanioscantidades, name='post_tamanioscantidades'),
]
*html**:
<div class="col-md-6 border border-primary rounded border-3">
<div class="m-5">
<div class="row">
<form action="post_url_tamanioscantidades/" method="post">
{% csrf_token %}
{{ tamanioscantidades_form.as_p }}
<input type="submit" value="Submit"/>
</form>
</div>
</div>
As I said, this form works in home, but when coping the same code in a section of my site the submit button does not save the form in database.
It returns:
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/productos/post_url_tamanioscantidades/
Using the URLconf defined in gallito.urls, Django tried these URL patterns, in this order:
admin/
productos/
productos/die-cut-stickers [name='die-cut-stickers']
post_url/ [name='post_treasure']
post_url_tamanioscantidades/ [name='post_tamanioscantidades']
accounts/
The current path, productos/post_url_tamanioscantidades/, didn't match any of these.
The problem is the form is being submitted to http://127.0.0.1:8000/productos/post_url_tamanioscantidades/ which does not exist instead you want it to submit at http://127.0.0.1:8000/post_url_tamanioscantidades/
So in your form html start the form action with /
<form action="/post_url_tamanioscantidades/" method="post">

"user = authenticate(request, username=username, password=password)" user is none

def login_page(request):
form = LoginForm(request.POST or None)
context = {
"form": form
}
print("User logged in")
#print(request.user.is_authenticated())
if form.is_valid():
print(form.cleaned_data)
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username, password=password)
print(user)
print(request.user.is_authenticated())
if user is not None:
print(request.user.is_authenticated())
login(request, user)
# Redirect to a success page.
context['form'] = LoginForm()
return redirect("/")
else:
# Return an 'invalid login' error message.
print("Error")
return render(request, "auth/login.html", context)
Hello, I have started playing around in Django, but in a tutorial, when a tutor clicks submit, it authenticates the user ... I found almost the same problem on stack overflow already, but problem is, that a guy had a string instead of variables ( username = 'username' ) but problem is that when I click submit I get an error :
User logged in
{'username': 'test123', 'password': 'test'}
None
False
Error
User logged in is just a string in print()
None <- print(user)
False <- print(request.user.is_authenticated())
Error <- else: print("Error")
I am struggling for an hours with this problem ( we have the same version of Django ) Django==1.11.4
So I am not totally sure what exactly is causing your problems here.
I know this probably isn't what they do in the tutorial, but my suggestion to you would be to use the built in Django authentication views. That way you don't have to repeat code that is already done for you.
The views are very simple to use. All you need to do is set the proper route in your URL and then create a template under the directory 'registration/login.html'.
First set proper settings in your settings.py file(I'm including the login and logout steps because they go hand-in-hand):
LOGIN_REDIRECT_URL = '/page/you/redirect/to/'
LOGOUT_REDIRECT_URL = '/your/login/page/'
Then set URLs:
urls.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.conf import settings
urlpatterns = [
url(r'^login/$', auth_views.login, {'redirect_authenticated_user': True},name='login'),
url(r'^logout/$', auth_views.logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'),
]
Then finally in your templates folder that is within the same app as the urls.py file where you put the login and logout routes, create a folder named "registration" and create an html file called "login.html".
Finally, your "login.html" file can simply be this:
{% block title %}Login{% endblock %}
{% block content %}
<body>
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
{% endblock %}
When you want to logout, just put a button wherever you want and link it to "/logout". And after that, authentication is done!

How to make form in _base.html

I need to make form in header section of site. This form will be available for all pages in my site. For example, i have in my app "accounts":
forms.py
class SignupForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('phone',)
views.py
def signup(request):
form = SignupForm(request.POST or None)
# CODE #
ctx = {
'form': form,
}
return render(request, 'accounts/signup.html', ctx)
urls.py
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('signup/', views.signup, name='signup'),
]
accounts/signup.html
{% block signup %}
{{ form }}
{% endblock %}
If I add{% include 'accounts/signup.html' %} to my _base.html, I don't, get form - {{ form }} but all other content will be included.
And can you tell me how exactly get form for all pages in site? Is it the correct approach?
Use a custom templatetag to initialize an empty form and display it from wherever you want - just make sure the action attribute of the HTML <form> tag points to your signup view.

Wrong form is being displayed in a Django project

I have a django project I created. This django project is split into two apps, the user and common. I have a method in the user app that allows the user to submit a form which will create a new Django user. Once the form is submitted and process I want to redirect the user to the testing page in the common app and display a html template that says testing page. Everything is working, the form is being processed and the redirect is occuring. I know this because the url changed to the expected url which will display the html testing page. For some reason, even though the url is transfering to the correct one, the html template being displayed is actually the signup form html template not the correct template.
Here is the code from the common app:
views.py
# testing method
def test(request):
return render(request, 'common/test.html')
urls.py:
urlpatterns = [
url(r'^test/$', views.test, name='test'),
]
test.html:
{% extends "base.html" %}
{% block standard %}
<p>testing page</p>
{% endblock %}
here is the redirect from the users app:
this is in the signup def after the user has been created
return redirect('test')
here is the entire signup method:
# have a user signup and create his account
def Signup(request):
# check to see if form is submitted
if request.method == "POST":
# grab the form and information
form = SignupForm(request.POST)
# validating form
if form.is_valid():
# grab the form content
cd = form.cleaned_data
username = cd['username']
password = cd['password']
verify = cd['verify']
email = cd['email']
# check if passwords match
if password == verify:
# create safe passwords
secure_password = make_password(password)
# save username in sessions
# request.session['username'] = username
return redirect('test')
else:
# redirec to original forms
message = "Passwords did not match"
# users form
form = SignupForm()
# everything required for the template
parameters = {
'message':message,
'form':form,
}
# display html template
return render(request, 'user/Signup.html', parameters)
else:
# the signing up form
form = SignupForm()
message = "Please fill out the entire form"
# everything that needs to be passed to html template
parameters = {
'form':form,
'message':message,
}
# render the template
return render(request, 'user/Signup.html', parameters)