How to unfollow url in django? - python

I created this simple code to learn about login and registration in django. My views.py is
def index(request):
products = Product.objects.all()
return render(request,'index.html',{'products':products})
def register(request):
return render(request,'register.html')
def login(request):
return render(request,'login.html')
def logout(request):
return HttpResponse('logout')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('register/', views.register),
path('login/', views.login),
path('logout/', views.logout),
]
base.html
Register
Login
<h3>Base html </h3>
{% block content %}
{% endblock %}
register.html
{%extends 'base.html'%}
<h1>Register</h1>
{% block content %}
{% endblock %}
login.html
{%extends 'base.html'%}
<h1>Login</h1>
{% block content %}
{% endblock %}
At http://127.0.0.1:8000/ when I click Register link it follows to http://127.0.0.1:8000/register page but when I click the 'Register link at that page it follows to http://127.0.0.1:8000/register/register which gives 404 error. How do I unfollow url that is instead of going to http://127.0.0.1:8000/register/register it has to go http://127.0.0.1:8000/register/?

in your base. html you should generally specify a link with {% url 'register' %}
So like that:
Register
But to use it, in you settings.py you should specify the directory where your templates are stored relative to the base directory of your project
TEMPLATES = [
{
...
'DIRS': [
os.path.join(BASE_DIR, 'your/way/to/templates'),
],
...
]
Also import os.path at the top of settings.py
EDIT
when you specify your urls.py, you should give name to every url.
path('register/', views.register, name='register'),
so in Register you call the name of the url

Haven't seen your base urls from project side but seems your are doing this way in my guess
you can remove register from base urls of project file
path(
'register/',
include('register.urls'),
),

The best practice for this problem to name the URLs. Just give them names and refer to that names in the HTML file
My solution:
urls.py
urlpatterns = [
path('', views.index),
path('register/', views.register,name="register"),
path('login/', views.login,name="login"),
path('logout/', views.logout,name="logout"),
]
base.html
Register
Login
<h3>Base html </h3>

Related

Not able to navigate between two templates in a Django application

I have a ran into a difficulty when navigating between different templates in a Django (v3.2) application. The app is called 'manage_remittance'.
The default landing page (which uses template manage_remittance/templates/manage_remittance/view_remittance.html) for the app should show a list of items (list is not relevant at the moment), and at the top of that list there should be a link, leading to another page in the same app, which would allow to add new items to the list.
The form that is invoked first is here:
manage_remittance/templates/manage_remittance/view_remittance.html
{% extends "root.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% url 'manage_remittance:remittance_add' as remittance_add %}
{% block title %}
VIEW REMITTANCES PAGE
{% endblock title %}
{% block content %}
<div class="list-group col-6">
Click here to add remittance data
</div>
I want to be able to get to another template (manage_remittance/templates/manage_remittance/remittance_add.html), but the {{ remittance_add }} has no value.
In addition, when I specify exact name of the html file (remittance_add.html) in the a href (see above), and click on it, I get a following error:
Using the URLconf defined in sanctions_project.urls, Django tried these URL patterns, in this order:
admin/
[name='login']
login/ [name='login']
logout/ [name='logout']
manage_remittance/ [name='view_remittance']
manage_remittance/ remittance_add/ [name='create_remittance']
^static/(?P<path>.*)$
^media/(?P<path>.*)$
The current path, manage_remittance/remittance_add.html, didn’t match any of these.
What am I doing wrong here?
fragment of urls.py for the project:
urlpatterns = [
path('admin/', admin.site.urls),
path('', login_view, name='login'),
path('login/', login_view, name='login'),
path('logout/', logout_view, name='logout'),
path('manage_remittance/', include('manage_remittance.urls')), # namespace='manage_remittance'
]
urls.py at manage_remittance app:
from .views import (
CreateRemittanceInfo,
RemittanceListView
)
app_name = 'manage_remittance'
urlpatterns = [
path('', RemittanceListView.as_view(), name='view_remittance'),
path('remittance_add/', CreateRemittanceInfo.as_view(), name='create_remittance'),
]
views.py at manage_remittance app:
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views.generic import ListView
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Remittance
class CreateRemittanceInfo(LoginRequiredMixin, CreateView):
model = Remittance
fields = ['remittance_text']
template_name_suffix = '_add'
class RemittanceListView(ListView):
model = Remittance
template_name = 'manage_remittance/view_remittance.html'
It seems that you have an issue in your urls:
manage_remittance/ remittance_add/ [name='create_remittance']
the name does not match with
manage_remittance:remittance_add
It seems quite simple: in your template, you should display a list, which is not the case. Have a look at Django User Guide: https://docs.djangoproject.com/fr/3.2/ref/class-based-views/generic-display/
It should look like
{% for object in object_list %}
<p>{{object.remittance_text}}</p>
{% endfor %}

why my app_name show as plural by s by navigation into URL link? [login]

when I do submit this form why has been submitted by accounts/profile? I've no any file called accounts basically. my app_name calls account not accounts.
so, How can I submit my form according to app_name that I using Image Error
urls.py
from . import views
from django.conf.urls import url
from django.contrib.auth.views import LoginView, logout
app_name = 'account'
urlpatterns = [
# /account/
url(r'^$', views.index, name="home"),
# /account/login/
url(r'^login/$', LoginView.as_view(template_name='account/login.html'), name='login_page'),
# /account/logout/
url(r'^logout/$', logout, {'template_name': 'account/logout.html'}, name='logout'),
# /account/register/
url(r'^register/$', views.register, name='register'),
# /account/profile/
url(r'^profile/$', views.view_profile, name='view_profile'),
# /account/profile/edit/
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
# /account/profile/edit/
url(r'^change-password/$', views.change_password, name='change_password'),
]
login.html
{% extends 'base.html' %}
{% block title %} Login {% endblock %}
{% block body %}
<div class="container">
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</div>
{% endblock %}
I've no more files to explain that
I think these files just show you what happens when logged in
You must provide LOGIN_REDIRECT_URL.
If LoginView called via POST with user submitted credentials, it tries to log the user in. If login is successful, the view redirects to the URL specified in next. If next isn’t provided, it redirects to settings.LOGIN_REDIRECT_URL (which defaults to /accounts/profile/). If login isn’t successful, it redisplays the login form. See Django documentation

Custom logout page not landing

On clicking logout button the custom landing page is not landing,but the default django-admin page is landing!
hey! I am trying to learn django from the book django2 by example so i created a dashboard page which is having a logout button but on clicking the button it shows the django-admin landing page and not the one I created !
urls.py(main-project)
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('account.urls')),
]
urls.py(account-app)
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
# post views
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='log_out'),
path('', views.dashboard, name='dashboard'),
# change password urls
path('password_change/',auth_views.PasswordChangeView.as_view(),
name='password_change'),
path('password_change/done/',auth_views.PasswordChangeDoneView.as_view(),
name='password_change_done'),
]
It should show thisenter image description here but apparantely it's showing the django-admin default logout pageenter image description here
logged_out.html
{% extends "base.html" %}
{% block title %}Logged out{% endblock %}
{% block content %}
<h1>Logged out</h1>
<p>You have been successfully logged out. You can <a href="{% url
"login" %}">log-in again</a>.</p>
{% endblock %}
update- got the solution.
Nevermind! I got the solution, I just have to mention my application before the django.contrib.admin as both of the app and default admin shares the same urls and views. So in order to view mine custom pages I have to change the settings in the INSTALLED_APPS as per the above settings..

Django url page not found

So I have been trying to access a project post that I have created for my website, but every time I click on it the url can't be found. I am not sure why.
My code is below:
mywebsite/urls.py
from django.contrib import admin
from django.urls import re_path, include
from django.conf import settings
from django.conf.urls.static import static
#re_path(r'^admin/', admin.site.urls),
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^', include('home.urls')),
re_path(r'^projects/', include('projects.urls', namespace="create_post")),
re_path(r'^contact/', include('contact.urls')),
]
projects/urls.py
from django.urls import re_path, include
from . import views
# urls for projects page
app_name = 'create_post'
urlpatterns = [
re_path(r'^$', views.retrieve_projects, name="retrieve_projects"),
#re_path(r'^create/$', views.CreateProjectsView.as_view(), name="create_projects"),
re_path(r'^create/$', views.CreateProjectsView.as_view(), name="create_projects"),
re_path(r'^(?P<slug>[\w-]+)/$', views.details_of_project, name="details_of_project"),
re_path(r'^(?P<slug>[\w-]+)/update/$', views.update_projects, name="update_projects"),
re_path(r'^(?P<slug>[\w-]+)/delete/$', views.delete_projects, name="delete_projects"),
]
# To make images work
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
projects/views.py
# Function to retrieve all different projects
def retrieve_projects(request):
# Retrieves objects based on latest publish date
projects_list = Projects.objects.all().order_by("-publish_date")
context = {
'projects_list': projects_list,
}
return render(request, 'projects/projects.html', context)
projects/projects.html
<h1>asdasdasdasdasdasdas</h1>
{% if projects_list %}
<ul>
{% for project in projects_list %}
<h2>{{project.title}}</h2>
<h2>{{project.description}}</h2>
<h2>{{ project.publish_date }}</h2>
{% endfor %}
</ul>
{% endif %}
The error returns page not found
try this

Django URL error when using forms

I am fairly new to Django and I am totally stuck on what is causing this error. I have done lots of searching but to no avail! Any help would be super appreciated.
The actual form works fine but when I try and submit the input data I get the error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
^$ [name='home']
^patientlist [name='patient_list']
^patientdetail/(?P<pk>\d+)/$ [name='patient_detail']
^add_patient/$ [name='add_patient']
The current URL, spirit3/add_patient/, didn't match any of these.
My urls.py in the mysite directory looks like:
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('spirit3.urls')),
]
My urls.py in the app looks like:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^patientlist', views.patient_list, name='patient_list'),
url(r'^patientdetail/(?P<pk>\d+)/$', views.patient_detail, name='patient_detail'),
url(r'^add_patient/$', views.add_patient, name='add_patient'),
]
The relevant part of views.py:
def add_patient(request):
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save(commit=True)
return redirect('home')
else:
print form.errors
else:
form = PatientForm()
return render(request, 'spirit3/add_patient.html', {'form':form})
And the html looks like:
{% extends 'spirit3/base.html' %}
{% block content %}
<body>
<h1> Add a Patient </h>
<form action="/spirit3/add_patient/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create Patient" />
</form>
</body>
{% endblock %}
Thanks in advance! :)
the form "action" attribute is wrong... seeing your urls configuration you dont have a /spirit3/add_patient/ url, I think It is /add_patient/
or you could just use a form tag without an "action" it will post to the current page:
<form role="form" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create Patient" />
</form>
Hope this helps
As pleasedontbelong mentionned, there's indeed no url matching "/spirit3/add_patient/" in your current url config. What you have in tour root urlconf is:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('spirit3.urls')),
]
This means that urls with path starting with "/admin/" are routed to admin.site.urls, and all other are routed to spirit3.urls. Note that this does NOT in any way prefixes urls defined in spirit3.urls with '/spirit3/', so in your case, all of these urls:
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^patientlist', views.patient_list, name='patient_list'),
url(r'^patientdetail/(?P<pk>\d+)/$', views.patient_detail, name='patient_detail'),
url(r'^add_patient/$', views.add_patient, name='add_patient'),
]
will be served directly under the root path "/" - ie, the add_patient view is served by "/add_patient/", not by "/spirit3/add_patient/".
If you want your spirit3 app's urls to be routed under "/spirit3/*", you have to specify this prefix in your root urlconf, ie:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^spirit3/', include('spirit3.urls')),
]
Note that you can use any prefix, it's totally unrelated to your app name.
As a last note: never hardcode urls anywhere, django knows how to reverse an url from it's name (and args / kwargs if any). In a template you do this with the {% url %} templatetag, in code you use django.core.urlresolvers.reverse().

Categories

Resources