My url template not work - python

I have a problem with my template tag url. The redirect not work when i click on button.
Django version => 1.9
Python version => 2.7
In my urls.py(main) i have:
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from memoryposts.views import home, profile, preregistration
urlpatterns = [
url(r'^$', home, name="home"),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', admin.site.urls),
url(r'^memory/', include("memoryposts.urls", namespace="memory")),
url(r'^avatar/', include('avatar.urls')),
url(r'^accounts/', include('registration.backends.hmac.urls')),
url(r'^preregistration/', preregistration, name="preregistration"),
url(r'^profile/', profile, name="profile"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In my urls.py(apps) i have:
from django.conf.urls import url
from django.contrib import admin
from .views import (
memory_list,
memory_create,
memory_detail,
memory_update,
memory_delete,
)
urlpatterns = [
url(r'^$', memory_list, name='list'),
url(r'^create/$', memory_create, name='create'),
url(r'^(?P<slug>[-\w]+)/$', memory_detail, name='detail'),
url(r'^(?P<slug>[-\w]+)/edit/$', memory_update, name='update'),
url(r'^(?P<slug>[-\w]+)/delete/$', memory_delete, name='delete'),
]
In my views.py(apps) i have:
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from .forms import PostForm
def home(request):
return render(request, "base.html")
def profile(request):
return render(request, "profile.html")
def preregistration(request):
return render(request, "preregistration.html")
def memory_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request,"Succès !")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "memory_create.html", context)
def memory_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
context = {
"title":instance.title,
"instance":instance,
}
return render(request, "memory_detail.html", context)
def memory_list(request):
queryset = Post.objects.all()
context = {
"object_list": queryset,
}
return render(request, "memory_list.html", context)
def memory_update(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request,"Mis à jour !")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title":instance.title,
"instance":instance,
"form": form,
}
return render(request, "memory_create.html", context)
def memory_delete(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Supprimer !")
return redirect("posts:list")
In my template html i have:
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' %}"> Update</a></button>
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:delete' %}"> Delete</a></button>
The redirect not work with this template tag.
can you help me please :) ?

From doc here URL dispatcher
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' %}"> Update</a></button>
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:delete' %}"> Delete</a></button>
You should put what you 'slug' in your button, like this (if slug is 200)
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' 200 %}"> Update</a></button>
Usually will look like this:
{% for slug in slug_list %}
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' slug %}"> Update</a></button>
{% endfor %}

Related

HttpResponseRedirect Reverse not working Django

I am trying to redirect my page after submitting a like button to the same page but I keep getting a
NoReverseMatch at /score/like/2
Here is the urls
urlpatterns = [
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('', PostListView.as_view(), name='score'),
path('<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('like/<int:pk>', LikeView, name='like_post'),
Here is the views
def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
post.likes.add(request.user)
return HttpResponseRedirect(reverse('post-detail', args=[str(pk)])) <-----Error highlighting here
here is the templates
<form action="{% url 'score:like_post' post.pk %}" method='POST'>
{% csrf_token %}
<button type='submit' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button>
</form>
<strong>{{post.total_liked}} Likes </strong>
Given the template your urls.py specify an app_name. You need to use that as prefix in the name of the view.
Furthermore you can make use of redirect(…) [Django-doc] which calls reverse and wraps the result in a HttpResponseRedirect (so it removes some boilerplate):
from django.shortcuts import redirect
def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
post.likes.add(request.user)
return redirect('score:post-detail', pk=pk)

Django registration is not working

I am trying to add a user registration page but its showing
NoReverseMatch at /register/
Here is my project urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('pages.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
]
Pages urls.py
from django.urls import path
from .views import *
from django.contrib.auth import views
app_name = 'pages'
urlpatterns = [
path('', home_view, name='home'),
path('register/', register_user, name='register'),
]
Pages views.py
def home_view(request, *args, **kwargs):
return render(request, 'home.html', {})
def register_user(request, *args, **kwargs):
if request.method=='POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
context = {'form': form}
return render(request, 'register.html', context)
register.html
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<h2>Register here</h2>
<body>
<form method="post" action="{% url 'register' %}">
{% csrf_token %}
{% if form.errors %}
<p>Invalid details</p>
{% endif %}
{{ form }}
<input type="submit" value="Register">
</form>
</body>
</html>
All is fine but still it's showing error
NoReverseMatch at /register/
Reverse for 'register' not found. 'register' is not a valid view function or pattern name.
In the urls.py file, you specified a namespace:
from django.urls import path
from .views import *
from django.contrib.auth import views
app_name = 'pages'
urlpatterns = [
path('', home_view, name='home'),
path('register/', register_user, name='register'),
]
This means that in order to refer to such named view, you need to prefix it with the namespace. So that means in the template you need to write it like:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<h2>Register here</h2>
<body>
<form method="post" action="{% url 'pages:register' %}">
{% csrf_token %}
{% if form.errors %}
<p>Invalid details</p>
{% endif %}
{{ form }}
<input type="submit" value="Register">
</form>
</body>
</html>
Furthermore the redirect(..) should be rewritten the same way:
def register_user(request, *args, **kwargs):
if request.method=='POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('pages:home')
else:
form = UserCreationForm()
context = {'form': form}
return render(request, 'register.html', context)

Django POST request redirects to empty url after submitting form

I have a login form with POST method and when I submit the login data, it goes straight to the empty url and doesn't execute the login method in views.py. Ideally, after I submit the form in www.url.com/login via submit button, it should return a HttpResponse but instead, it takes me to www.url.com/
I am new to Django, I'd appreciate it if you could look into it. Thanks!
home.html
<center><h1>Welcome to my website</h1>
<form method='POST'> {% csrf_token %}
{{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
</center>
urls.py
from django.contrib import admin
from django.urls import path
from .views import home, login
urlpatterns = [
path('', home),
path('login/', login),
path('admin/', admin.site.urls),
]
forms.py
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control", "placeholder":"Your username"}))
password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"form-control", "placeholder":"Your password"}))
views.py
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import render
from .forms import LoginForm
def home(request):
context={
"form": "Test"
}
return render(request, "home.html", context)
def login(request):
login_form = LoginForm(request.POST or None)
context={
"form": login_form
}
if login_form.is_valid():
username = login_form.cleaned_data.get('username')
password = login_form.cleaned_data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
#request.user.is_authenticated()
login(request, user)
return HttpResponse("You are now logged in")
else:
return HttpResponse('Error')
return render(request, "home.html", context)
First, you should set an attribute action in the form which set a url to send.
Second, a url value in action must be clear. It's not a matter of Django but HTML.
I'd like to recommend you to use absolute path. If you use relative path, a slash string would be added whenever you send a request.
<form action="/login/" method='POST'>
{% csrf_token %}
{{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
This is because your form doesn't contain action, i.e. where should the POST call be made with the user credentials.
Try following change in home.html:
<center><h1>Welcome to my website</h1>
<form action="" method='POST'> {% csrf_token %}
{{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
</center>
Following the answers before, it would be a good practice to use named patterns instead of fixed urls.
# urls
...
path('login/', login, name='login'),
...
# template
<form action="{% url 'login' %}" method='POST'>
So if you change for example
login/
for
accounts/login/
You don't have to change the template as well.
urlpatterns = [
re_path('^$', home_page),
re_path('^admin/', admin.site.urls),
re_path('^register/$', register_page, name='register'),
re_path('^login/$', login_page, name='login'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I solved this by adding ^$to the beginning and end of the patterns.

accounts is not a registered namespace

in this django tutorial, we are creating a blogsite, at this pont we are creating a login form for users, unfortunately im getting and error saying that "accounts" is not a registered namespace, how do i fix this?
my urls.py file for the app "accounts":
from django.conf.urls import url
from.import views
appname= 'accounts'
urlpatterns=[
url(r'^signup/$', views.signup_view, name= "signup"),
url(r'^login/$', views.login_view, name = "login" ),
]
my views.py for the app:
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
def signup_view(request):
if request.method== 'POST':
form= UserCreationForm(request.POST)
if form.is_valid():
form.save()
#log the user in
return redirect('narticle:list')
else:
form=UserCreationForm()
return render (request,'accounts/accounts_signup.html', {'form': form})
def login_view(request):
if request.method == "POST":
form = AuthenticationForm(data= request.POST)
if form.is_valid():
return redirect('narticle:list')
else:
form = AuthenticationForm()
return render(request, 'accounts/login.html',{'form': form})
my base layout is:
{% load static from staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Narticle</title>
<link rel="stylesheet" href="{%static 'styles.css'%}">
</head>
<body>
<div class="wrapper">
<h1> narticle </h1>
{% block content %}
{% endblock %}
</div>
</body>
</html>
the template for login is:
{% extends 'base_layout.html'%}
{%block content%}
<h1> log in</h1>
<form class="site-form" action="{% url 'accounts:login' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" name="log_in" value="login">
</form>
{% endblock %}
these are my base urls:
from django.conf.urls import url, include
from django.contrib import admin
from. import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include ('accounts.urls')),
url(r'^narticle/', include ('narticle.urls')),
url(r'^about/$', views.about),
url(r'^$',views.homepage),
]
urlpatterns+= staticfiles_urlpatterns()
urlpatterns+= static(settings.MEDIA_URL, document_root= settings.
MEDIA_ROOT)
Believe it's because you missed the underscore:
from django.conf.urls import url
from.import views
# app_name not appname
app_name= 'accounts'
urlpatterns = [
url(r'^signup/$', views.signup_view, name= "signup"),
url(r'^login/$', views.login_view, name = "login" ),
]
You missed namespace in project urls.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include ('accounts.urls', namespace='accounts')),
url(r'^narticle/', include ('narticle.urls')),
url(r'^about/$', views.about),
url(r'^$',views.homepage),
]

Django urls.py not rendering correct template

This is my urls.py
"""s7h URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^articles/', include('article.urls')),
url(r'^',include('django.contrib.auth.urls')),
url(r'^projects/', include('project.urls')),
#Serve Media Files
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
#subscribe
url(r'^subscribe/$', 'article.views.subscribe'),
url(r'^verify/$', 'article.views.activateSubscriber'),
# user auth urls
url(r'^home/$', 's7h.views.home'),
url(r'^', 's7h.views.home'),
url(r'^accounts/login/$', 's7h.views.login'),
url(r'^accounts/auth/$', 's7h.views.auth_view'),
url(r'^accounts/logout/$', 's7h.views.logout'),
url(r'^accounts/loggedin/$', 's7h.views.loggedin'),
url(r'^accounts/invalid/$', 's7h.views.invalid_login'),
# user registration urls
url(r'^accounts/register/$', 's7h.views.register'),
url(r'^accounts/register_success/$', 's7h.views.register_success'),
url(r'^accounts/register_auth/$', 's7h.views.register_auth'),
url(r'^contact/$', 's7h.views.contact'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
handler400 = 's7h.views.custom_400'
handler403 = 's7h.views.custom_403'
handler404 = 's7h.views.custom_404'
handler500 = 's7h.views.custom_500'
if not settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
This is my views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect
from django.contrib import auth,messages
from django.core.context_processors import csrf
from django.template import RequestContext
from django.template.loader import get_template
from forms import MyRegistrationForm
from article.models import Article, ArticleCategory
from project.models import Project, ProjectCategory
def home(request):
args={}
article = Article.objects.earliest("-pub_date")
project = Project.objects.earliest("-pub_date")
article_category = ArticleCategory.objects.all()
project_category = ProjectCategory.objects.all()
args.update(csrf(request))
args['article'] = article
args['project'] = project
args['project_categories'] = project_category
args['article_categories'] = article_category
args['loggedin'] = request.session.get('email', None)
return render_to_response('home.html', args)
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
request.session['email'] = user.email
return render(request, "loggedin.html", locals(),context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/accounts/invalid/')
def loggedin(request):
return render_to_response('loggedin.html', {})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/accounts/login/')
This is my template for login
{% extends "user_forms.html" %}
{% block title %}
S7H - Login
{% endblock %}
{% block main %}
<span class="fa fa-user bigicon"></span>
<h2>Enter Details</h2>
<form action = "/accounts/auth/" method = "POST">{% csrf_token %}
<p><input type="text" name="username" required placeholder="Username" autofocus></p>
<p><input type="password" name="password" required placeholder="Password"></p>
<button class="btn btn-default" type="submit" name="submit" />Sign In</button>
Sign Up
</form>
<small>Forgot your password?</small><br />
{% if messages %}
{% for message in messages %}
<small {% if message.tags %} class="{{message.tags}}" {% endif %}>{{message}}</small>
{% endfor %}
{% endif %}
{% endblock %}
Now when I do http://127.0.0.1:8000/accounts/login/ , Django should render login.html because url accounts/login/ leads me to def login(request): and there in render_to_response() I have mentioned login.html to get rendered but instead of it, Django renders my home.html file. URL of the browser changes to http://127.0.0.1:8000/accounts/login/ when I press the login button on my home page but it keeps on rendering the same home.html template.
This thing is happening with other urls also. Every url is rendering home.html template.
I double checked all my urls, views and templates, I have not been able to figure out my mistake. Django is also not giving any Exceptions and Error messages.
Also in the terminal the HTTP response is 200 OK :/
[08/Jun/2015 01:38:40]"GET /accounts/login/ HTTP/1.1" 200 10201
Help me!
Your s7h.views.home pattern has no terminating $ so it matches every URL.

Categories

Resources