I am coding a basic login and register page app in Django/Python
Currently, after someone logs in, it redirects them back to the register page. I am trying to change the redirect path to "home/"
Please see the following code:
URLS.PY:
from django.contrib import admin
from django.urls import path , include
from accounts import views as v
from main import views as views
urlpatterns = [
path('admin/', admin.site.urls),
path('home/' , views.home , name = 'home'),
path('', v.register , name='register'),
path('' , include('django.contrib.auth.urls') , name = 'login'),
]
Views.py:
from django.shortcuts import render , redirect
from .forms import RegisterForm
# Create your views here.
def register(response):
if response.method == "POST":
form = UserCreationForm(response.POST)
if form.is_valid():
form.save()
return redirect("/home")
else:
form = RegisterForm()
return render(response, "registration/register.html", {"form":form})
Login.html
{% extends "main/base.html"%}
{% block title %}
Login here
{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<form class="form-group" method="post">
{% csrf_token %}
{{ form|crispy }}
<p>Don't have an account ? Create one </p>
<button type="submit" class="btn btn-success">Login</button>
</form>
{% endblock %}
Register.html
{% extends "main/base.html"%}
{% block title %}Create an Account{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<form method="POST" class="form-group">
{% csrf_token %}
{{ form|crispy }}
<p>Already have an account? Login here</p>
<button type="submit" class="btn btn-success">Register</button>
</form>
{% endblock %}
You can use this in settings.py file to redirect user after login :-
LOGIN_REDIRECT_URL = 'home/'
Related
Hi I'm new to Django and struggling with Django and csrf_token is getting 403 forbidden error even its included in the form template can some one explains me what's the issue here I have searched for answers but none worked for me when I inspect I can see the csrf token in the form Thanks In advance
template.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block body %}
<form action="{% url 'newPage'%}" method="post">
{% csrf_token %}
{{form}}
<br>
<input type="submit" value="Save">
</form>
{% endblock %}
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<str:name>", views.title, name="title"),
path("search/", views.search , name="search"),
path("NewPage/", views.newpage, name="newPage")
]
# views.py
def newpage(request):
if request.method == 'POST':
form = request.POST()
print(form.is_valid())
if form.is_valid():
title = form.cleaned_data.get('title')
content = form.cleaned_data.get('content')
util.save_entry(title, f'# {title}\n\n{content}')
return HttpResponseRedirect(reverse('encyclopedia:title'))
else:
form = newEntry()
return render(request, "encyclopedia/newentry.html", { "form": form })
else:
form = newEntry()
return render(request, "encyclopedia/newentry.html", { "form": form })
I have a view in views.py:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
print(uploaded_file_url)
context = {
'uploaded_file_url': uploaded_file_url
}
return render(request, 'simple_upload.html', context)
return render(request, 'simple_upload.html')
Then, a url in urls.py:
urlpatterns = [
path('', views.project_index, name='project_index'),
path('<int:pk>/', views.project_detail, name='project_detail'),
path('upload/', views.simple_upload, name='upload')
]
And when I hit the route /projects/upload, instead of a form I get an empty page. However, the simple_upload.html route has this structure:
{% extends "base.html" %}
<h1>H</h1>
{% load static %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: {{ uploaded_file_url }}</p>
{% endif %}
<p>Return to home</p>
{% endblock %}
You can see, I'm getting a blank page.
No errors are occurred.
I figured out the problem. You have to write {% block page_content %} in the template instead of {% block content %}, because in the base.html I have this line:
{% block page_content %}{% endblock %}
I don't know why I am getting a 404 error on the page flights/1 when clearly, I have a url pattern for
<int:flight_id> (flights is a app). Help!
My urls.py for the project
from django.contrib import admin
from django.urls import path
from django.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('flights/', include('flights.urls'))
]
My urls.py for the flights app
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<int:flight_id>", views.flight, name="flight"),\
]
And the views.flight
def flight(request, flight_id):
flight = Flight.objects.get(id=flight_id)
return render(request, "flights/flight.html", {
"flight": flight,
"passengers": flight.passengers.all(),
"non_passengers": Passenger.objects.exclude(flights=flight).all()
})
Template
{% extends "flights/layout.html" %}
{% block body %}
<h1>Flight {{ flight.id }}</h1>
<ul>
<li>Origin: {{ flight.origin }}</li>
<li>Destination: {{ flight.destination }}</li>
<li>Duration: {{ flight.duration }}</li>
</ul>
<h2>Passengers</h2>
<ul>
{% for passenger in passengers %}
<li>{{ passenger }}</li>
{% empty %}
<li>No passengers.</li>
{% endfor%}
</ul>
<h2>Add Passenger</h2>
<form method="POST" action="{% url 'flight' flight.id book %}">
{% csrf_token %}
<select name="passengers">
{% for passenger in non_passengers %}
<option value="{{ passenger.id }}">{{ passenger }}</option>
{% endfor %}
</select>
</form>
Back to Flight List
{% endblock %}
With layout.html being html boilerplate code
I am trying to save post data for a custom user registration form but I can't identify where I am going wrong. I am suspecting the problem is in mainapp/urls. I have done some research on the subject read the following
documentation,Question on StackOverflow,Question on StackOverflow and many others but I cannot find the problem.
template
{% extends 'base.html'%}
{% load staticfiles %}
{% block content%}
{% load bootstrap %}
<div class = "signup-box">
<h2>Sign up</h2>
<form class="form-horizontal" action="signup" method="post">
{% csrf_token %}
<!-- {{ form|bootstrap }} -->
{{ form.username.label }}
{{ form.username }}
{{ form.first_name.label }}
{{ form.first_name }}
{{ form.last_name.label }}
{{ form.last_name }}
{{ form.email.label }}
{{ form.email }}
{{ form.password1.label }}
{{ form.password1 }}
{{ form.password2.label }}
{{ form.password2 }}<br>
<input type="submit" value="Submit" />
</form>
</div>
{% endblock %}
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home),
url(r'^login/$', views.login, name='login'),
url(r'^signup/$', views.signup, name='signup'),
]
Views.py
from django.shortcuts import render, redirect
from .forms import RegistrationForm
from .models import User
from django.contrib import messages
from django.http import HttpResponse
# Create your views here.
def register_page(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse('<h1>The form is valid!<h1>')
else:
form = RegistrationForm(request.POST)
args = {'form':form}
return render(request, 'signup', args)
else:
form = RegistrationForm()
return render(request, 'signup.html', {'form': form})
I get the following error after submitting the form
The current path, register_page/register_page/signup, didn't match any of these.
The problem is the URL you are posting to. The action of your form is a relative path, "signup"; because it has no leading slash it will always be appended to the current path.
You could fix this by prepending a slash, but you should actually not do this; you should post to the same URL as you came from, so action=".".
Note, there are various other errors with your code, not least the fact that you unnecessarily re-instantiate the form if it fails validation, so you will never see any validation errors.
I was trying to add an editing/deleting function for a bookmarks app.
I get the following error:
My Urls.py file is the following:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'myproject.views.home', name='home'),
# url(r'^myproject/', include('myproject.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'bookmarks.views.index', name='home'),
url(r'^bookmarks/$', 'bookmarks.views.index', name='bookmarks_view'),
url(r'^tags/([\w-]+)/$', 'bookmarks.views.tag'),
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'})
url(r'^delete/(\d+)/$', 'bookmarks.views.delete'),
url(r'^edit/(\d+)/$', 'bookmarks.views.edit'),
)
The views.py file:
...remaining code
def delete(request, bookmark_id):
if request.method == 'POST':
b = get_object_or_404(Bookmark, pk=int(bookmark_id))
b.delete()
return redirect(index)
def edit(request, bookmark_id):
b = get_object_or_404(Bookmark, pk=int(bookmark_id))
context = {
'form' : BookmarkForm(instance=b),
}
return render(request, 'edit.html', context)
The bookmark widget in index.html
{% block bookmark_widget %}
{% if request.user %}
<div id="new-bookmark-widget">
<form method="post" action="{% url bookmarks.views.index %}">
{% csrf_token %}
<h3>Bookmark</h3>
{{ form.as_p }}
<p><button id="new-bookmark-submit">Submit</button>Submit</button>
</form>
</div>
{% endif %}
{% endblock %}
The relevant div in base.html
<div id="container">
<div id="header">
{% block bookmark_widget %}
{% endblock %}
<div id="authentication">
{% if user.is_authenticated %}
Hi {{user}}! Logout
{% else %}
Login
{% endif %}
</div>
<h1>My bookmarking app</h1>
</div>
<div id="content">
<h2>{% block subheader %}{% endblock %}</h2>
{% block content %}
Sample content -- you should never see this, unless an inheriting template fails to have any content block!
{% endblock %}
</div>
<div id="footer">
All copyrights reserved
</div>
</div>
The complete bookmark.html file:
<li>
<a class="bookmark-link" href="{{ bookmark.url }}">{% if bookmark.title %}{{ bookmark.title }}{% else %}{{ bookmark.url }}{% endif %}</a>
<div class="metadata"><span class="author">Posted by {{ bookmark.author }}</span> | <span class="timestamp">{{ bookmark.timestamp|date:"Y-m-d" }}</span>
{% if bookmark.tag_set.all %}| <span class="tags">
{% for tag in bookmark.tag_set.all %}
{{ tag.slug }}</span>
{% endfor %}
{% endif %}
</div>
{% if request.user.is_authenticated %}
<div class="actions"><form method=="POST" action="{% url bookmarks.view.delete bookmark.id %}>
{% csrf_token %}
<input type="submit" value="Delete">
</form> </div>
{% endif %}
I am new to Django, how do I handle error mistakes and how do I find the problem? I couldnt see it from the error message.
Thank you!
missing a comma on the following line:
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}), <-add here
I presume your comments section also lines up with the rest of your code and it is formatted incorrectly in your question
You're missing a comma at the end of this line:
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'})