Django - Incorporating new models with their own pages - python

I have managed to set up one model within my Django project and can create posts within it and display those posts through views and templates, however, I don't appear to be able to do the same with the new Models I've created. I have attempted to do this as I have done with the initial Model, which is to set up its own html files, just as the first one, as well as similar entries in urls.py in the main project folder and views.py in the app folder.
Edit for more context: Basically, the Article model has been set up with the templates article_detail.html and article_list.html and all of the entries within that model are pulled from the Admin app and are viewable. I have created another model, Offensive, and would also like to do the same as with the Article entries, so I attempted to copy what I had done and made the Offensive model it's own templates (offensive_detail.html and offensive_list.html:).
This does not appear to have worked, however. Creating a link for Offensive on base_template.html does not go anywhere, it just stays on the same page. Does not re-direct to the offensive details page that will show the list of offensive articles.
My intent is to have different categories aligned with different models and have all of those categories and corresponding pages as links within a navbar.
I'm not entirely sure where I'm going wrong, or even if I'm anywhere near right.
Help would be very much appreciated.
Here is the folder structure of my project
Files under the app folder:
article_detail.html:
{% extends 'base_layout.html' %}
{% block content %}
<div class="article-detail">
<div class="article">
<h2>{{ article.title }}</h2>
<p>{{ article.body }}</p>
<p>{{ article.date }}</p>
</div>
</div>
{% endblock %}
article_list.html:
{% extends 'base_layout.html' %}
{% block content %}
<h1>Articles List</h1>
<div class="articles">
{% for article in articles %}
<div class="article">
<h2>{{ article.title }}</h2>
<p>{{ article.date }}</p>
</div>
{% endfor %}
</div>
</body>
{% endblock %}
offensive_detail.html:
{% extends 'base_layout.html' %}
{% block content %}
<div class="offensive_articles">
<div class="offensive_list">
<h2>{{ offensive_article.title }}</h2>
<p>{{ offensive_article.body }}</p>
<p>{{ offensive_article.date }}</p>
</div>
</div>
{% endblock %}
offensive_list.html:
{% extends 'base_layout.html' %}
{% block content %}
<h1>Offensive Articles List</h1>
<div class="offensive_articles">
{% for offensive_article in offensive_articles %}
<div class="offensive_article">
<h2>{{ offensive_article.title }}</h2>
<p>{{ offensive_article.date }}</p>
</div>
{% endfor %}
</div>
</body>
{% endblock %}
models.py:
from django.db import models
from PIL import Image
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField() # URL of post
body = models.TextField()
date = models.DateTimeField(auto_now_add=True) # auto populate with the current time
thumb = models.ImageField(default='default.jpg', blank=True)
# add in author
def __str__(self):
return self.title
class Offensive(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField() # URL of post
body = models.TextField()
date = models.DateTimeField(auto_now_add=True) # auto populate with the current time
thumb = models.ImageField(default='default.jpg', blank=True)
def __str__(self):
return self.title
urls.py:
from django.urls import path
from django.conf.urls import url
from . import views
app_name = 'articles'
urlpatterns = [
url(r'^$', views.article_list, name="list"),
url(r'^$', views.offensive_list, name="offensive_list"),
url(r"^(?P<slug>[\w-]+)/$", views.article_detail, name="detail"),
url(r"^(?P<slug>[\w-]+)/$", views.offensive_detail, name="offensive_detail"),
]
views.py:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Article, Offensive, Defensive, Fitness, Coding
def article_list(request):
articles = Article.objects.all().order_by('date')
return render(request, 'articles/article_list.html', {'articles': articles})
def about(request):
#return HttpResponse('about')
return render(request, 'about.html')
def article_detail(request, slug):
#return HttpResponse(slug)
article = Article.objects.get(slug=slug)
return render(request, 'articles/article_detail.html', { 'article':article })
def offensive_list(request):
offensive_articles = Offensive.objects.all().order_by('date')
return render(request, 'articles/offensive_list.html', { 'offensive_article': offensive_article })
def offensive_detail(request, slug):
#return HttpResponse(slug)
offensive_article = Offensive.objects.get(slug=slug)
return render(request, 'articles/offensive_detail.html', { 'offensive_article': offensive_article })
From main folder "website":
ursl.py:
"""website URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url, include
from . import views
from articles import urls
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.conf import settings
from articles import views as article_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^articles/', include('articles.urls')),
url(r'^about/$', views.about),
url(r'^$', article_views.article_list, name="home"),
url(r'^offensive/', include('articles.urls')),
url(r'^$', article_views.offensive_list, name="offensive"),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
base_template.html:
{% load static %}
<!-- Bootstrap CDN -->
<link rel="stylesheet" href="{% static 'styles.css' %}" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Orbitron:wght#900&display=swap" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<!-- this will apear everywhere -->
<!DOCTYPE html>
<html>
<head>
<title>Articles</title>
<nav class="navbar navbar-dark bg-dark">
<div class="container-fluid">
<!-- Logo -->
<div class="navbar-header">
<!-- <button class="navbar-toggler navbar-toggler-left" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button> -->
<a class="navbar-brand" href="{% url 'home' %}" style="font-family: 'Montserrat', sans-serif; font-family: 'Orbitron',sans-serif; color:red;">Neophyte</a>
</div>
<!-- Item -->
<div>
<ul class="nav navbar-nav">
<li class="active">
<a href="{% url 'offensive' %}" style="font-family: 'Montserrat', sans-serif; font-family: 'Orbitron',sans-serif; color:white"> Offensive
</a>
</li>
</div>
</div>
</nav>
</head>
<body>
<div class="wrapper">
{% block content %}
{% endblock %}
</div>
</body>
</html>
<!-- <img src="{% static 'Neophyte_logo.jpg' %}"/> -->
<!-- href="{% url 'offensive' %}" -->

Your urls seem a bit out of sync. You've got articles.urls included twice and two matching patterns for 'r'^$'.
What you have:
url(r'^admin/', admin.site.urls),
url(r'^articles/', include('articles.urls')),
url(r'^about/$', views.about),
url(r'^$', article_views.article_list, name="home"),
url(r'^offensive/', include('articles.urls')),
url(r'^$', article_views.offensive_list, name="offensive"),
What I think you might want:
url(r'^admin/', admin.site.urls),
url(r'^articles/', include('articles.urls')),
url(r'^offensive/', include('offensive.urls')),
url(r'^about/$', views.about),
# pick one of the following that you want for the root url
# currently will match the first one.
url(r'^$', article_views.article_list, name="home"),
url(r'^$', article_views.offensive_list, name="offensive"),
Or if it is just models separating, put it all in one?
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^articles/', views.article_list, name="article_list"),
url(r"^articles/(?P<slug>[\w-]+)/$", views.article_detail, name="article_detail"),
url(r'^offensive/', views.offensive_list, name="offensive_list"),
url(r"^offensive/(?P<slug>[\w-]+)/$", views.offensive_detail, name="offensive_detail"),
url(r'^about/$', views.about),
url(r'^$', views.about, name="home"),
]
Also, you probably want to be using the newer Path, instead of the url (https://docs.djangoproject.com/en/3.1/topics/http/urls/#example)

Related

Unable to solve thisReverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P<id>[0-9]+)$']

I have a navbar in my template in which I am trying to add an active class, however, whenever I do such, I get this error:
NoReverseMatch at /
Reverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P<id>[0-9]+)$']
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P<id>[0-9]+)$']
Exception Location: C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix
Python Executable: C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.2
Python Path:
['C:\\Users\\Abdullah\\Desktop\\Blog\\my_blog',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\Abdullah\\AppData\\Roaming\\Python\\Python39\\site-packages',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
Server time: Wed, 21 Apr 2021 09:38:37 +0000
here is my base.html:
`{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="{% static 'css/base.css' %}">
<link rel="stylesheet" href="{% static 'css/posts.css' %}">
{% url 'posts' as posts %}
<nav>
<ul>
<li><a class="nav_a {% if request.path == posts %} active {% endif %}" href="{% url 'posts' %}">Blogs</a></li>
{% if request.user.is_authenticated %}
<li><a class="nav_a" href="{% url 'myposts' %}">Welcome {{ request.user }}</a></li>
<li><a class="nav_a" href="{% url 'post' %}">Post</a></li>
<li><a class="nav_a" href="{% url 'myposts' %}">My Posts</a></li>
<li><a class="nav_a" href="{% url 'logout' %}">Logout</a></li>
{% else %}
<li><a class="nav_a" href="{% url 'signup' %}">Signup</a></li>
<li><a class="nav_a" href="{% url 'login' %}">Login</a></li>
{% endif %}
</ul>
</nav>
<br>
<body>
{% block content %}
{% endblock %}
</body
</html>`
here is my urls.py:
`"""my_blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from blog_app import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.posts, name='posts'),
path('signup', views.signup, name="signup"),
path('login', auth_views.LoginView.as_view(template_name='blog_app/login.html'), name='login'),
path('logout', auth_views.LogoutView.as_view(template_name='blog_app/logout.html'), name='logout'),
path('post', views.post, name='post'),
path('myposts', views.myposts, name='myposts'),
path('delete_post/<int:id>', views.delete_post, name='delete_post'),
path('edit_post/<int:id>', views.edit_post, name='edit_post'),
path('read_post/<int:id>', views.read_post, name='read_post')
]`
posts views.py:
`def posts(request):
posts = Post.objects.all()
return render(request, 'blog_app/posts.html', {'posts': posts})
`
here is my blog_app/posts.html:
`{% extends 'blog_app/base.html' %}
{% block content %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% for post in posts %}
<div>
<h2>{{ post.title }}</h2>
<button>Read blog</button>
<h4>Posted by {{ post.author }} on {{ post.datetime }}</h4>
<br>
</div>
{% endfor %}
{% endblock %}`
models.py:
`from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import datetime
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(to=User, on_delete=models.CASCADE)
date_time = timezone.now()
# datetime = models.DateTimeField(auto=timezone.now)`
Also pls suggest way to add active link class as I am unable to do that.

Password reset not redirecting to template html file in django

I am trying to use a template html file for my password reset form. But it is not redirecting to my template file rather it is redirecting ti Django administration page. I don't want to use django administration page for resetting the password change link.
password_reset_form.html:
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" href="{% static 'employeeregistration/css/master.css' %}">
</head>
<body>
{% load bootstrap4 %}
<div class="container title">
<h2 style="text-align:center; padding-top:100px;">Reset your password</h2>
</div>
<div class="container">
<form method="POST" action="{% url 'password_reset' %}">
{% csrf_token %}
{{ form.as_p }}
{% buttons %}
<button type="submit" class="btn btn-primary">Send confirmation mail</button>
{% endbuttons %}
</form>
</div>
</body>
</html>
urls.py:
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'registration'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name="registration/login.html"), name='login'),
path('password_reset/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset_form.html"), name='password_reset'),
# path('password_reset/password_reset_done/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset_done.html"), name='password_reset_done'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('signup/', views.EmployeeSignUp.as_view(), name='signup'),
]
views.py:
from django.contrib.auth import login, logout
from django.contrib.auth.mixins import(LoginRequiredMixin,
PermissionRequiredMixin)
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic import CreateView
from . import forms
class EmployeeSignUp(CreateView):
"""
Views for employee sign up
"""
form_class = forms.NewEmployeeRegistrationForm
success_url = reverse_lazy("login")
template_name = 'registration/signup.html'
class AdminView(TemplateView):
template_name = 'registration/admin.html'
project urls.py:
from django.contrib import admin
from django.urls import path, include
# from django.contrib.auth import views
from . import views
urlpatterns = [
path('', views.HomePage.as_view(), name='home'),
path('admin/', admin.site.urls),
path('about/', views.AboutView.as_view(), name='about'),
path('registration/', include("django.contrib.auth.urls")),
path('registration/', include('registration.urls', namespace='registration')),
# path('registration/password_reset', include('registration.urls', namespace='password_reset')),
# path('registration/password_reset_done', include('registration.urls', namespace='password_reset_done')),
]
Since you have specified a namespace, in the action attribute in password_reset_form.html, you have to first specify the name of the namespace the name of the view separated by a colon. You can find the appropriate documentation here
So you have to change password_reset_form.html to-
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" href="{% static 'employeeregistration/css/master.css' %}">
</head>
<body>
{% load bootstrap4 %}
<div class="container title">
<h2 style="text-align:center; padding-top:100px;">Reset your password</h2>
</div>
<div class="container">
<form method="POST" action="{% url 'registration:password_reset' %}">
{% csrf_token %}
{{ form.as_p }}
{% buttons %}
<button type="submit" class="btn btn-primary">Send confirmation mail</button>
{% endbuttons %}
</form>
</div>
</body>
</html>
Also you have two paths in your root project urls.py which lead to the same url. So consider changing it to
from django.contrib import admin
from django.urls import path, include
# from django.contrib.auth import views
from . import views
urlpatterns = [
path('', views.HomePage.as_view(), name='home'),
path('admin/', admin.site.urls),
path('about/', views.AboutView.as_view(), name='about'),
# path('registration/', include("django.contrib.auth.urls")),
path('registration/', include('registration.urls', namespace='registration')),
# path('registration/password_reset', include('registration.urls', namespace='password_reset')),
# path('registration/password_reset_done', include('registration.urls', namespace='password_reset_done')),
]
I have commented out one url pattern which might be causing the issue.

I have a problem with the end of the tutorial djangogirls https://tutorial.djangogirls.org/fr/django_forms/

The error message is :
Template error:
In template H:\djangogirls\blog\templates\blog\base.html, error at line 12
Reverse for 'post_new' not found. 'post_new' is not a valid view function or pattern name.
The code and the traceback are available here:
http://dpaste.com/0TSA689
views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
from .forms import PostForm
from django.shortcuts import redirect
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
urls.py -blog
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new/', views.post_new, name='post_new'),
]
urls.py -mysite
from django.urls import path
from blog import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
post_detail
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h2>{{ post.title }}</h2>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
post list
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock content %}
blog base
{% load static %}
<head>
<title>Django Girls blog</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
</head>
<body>
<div class="page-header">
<span class="glyphicon glyphicon-plus"></span>
<h1>Django Girls Blog</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
Your mysite/urls.py is incorrect. You need to include the urls from your blog app:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
<div class="page-header">
<span class="glyphicon glyphicon-plus"></span>
<h1>Django Girls Blog</h1>
</div>
Your error is on this part of your code. It looks like in your 'urls.py' file you didn't add the new_post url name so django isn't able to find any url named "post_new". You should edit your urls file to something like this:
path('post/new/', views.post_new, name='post_new'),

Django 2.0 - Not a valid view function or pattern name (Customizing Auth views)

I´m working on a course exercise and I'm stuck for a few hours and I'm not sure what is causing the app to break, next, you will find the files involved and perhaps you can find out the solution. Thanks for your help!
Project structure
This error is being thrown when I log in:
Internal Server Error: /account/login/
...
django.urls.exceptions.NoReverseMatch: Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name.
[04/Apr/2018 17:12:15] "POST /account/login/ HTTP/1.1" 500 151978
At the end of the settings.py file
from django.urls import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_REDIRECT_URL = reverse_lazy('logout')
The urls.py file
from django.contrib.auth import views as auth_views
from django.urls import path
from . import views
app_name = 'account'
urlpatterns = [
# path('login/', views.user_login, name='login'),
path('', views.dashboard, name='dashboard'),
# login / logout urls
path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'),
path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'),
]
The views.py file
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
The base.html template
{% load staticfiles %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static "css/base.css" %}">
</head>
<body>
<div id="header">
<span class="logo">Bookmarks</span>
{% if request.user.is_authenticated %}
<ul class="menu">
<li> {% if section == "dashboard" %}class="selected"{% endif %}>My dashboard</li>
<li> {% if section == "images" %}class="selected"{% endif %}Images</li>
<li> {% if section == "people" %}class="selected"{% endif %}People</li>
</ul>
{% endif %}
<span class="user">
{% if request.user.is_authenticated %}
Hello {{ request.user.first_name }}, Logout
{% else %}
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
I appreciate your help. Thanks a lot!
You've set a namespace for your urls:
app_name = 'account'
You need to use that namespace when reversing urls with reverse/reverse_lazy or {% url %}:
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_REDIRECT_URL = reverse_lazy('account:logout')
Perhaps when specifying {% url 'appname:views' %} you specified the wrong appname
For example, like:
wrong - {% url 'accuant:dashboard' %}
right - {% url 'account:dashboard' %}

AttributeError at /home/ 'list' object has no attribute 'resolve'

I keep getting a 'AttributeError at /home/ 'list' object has no attribute 'resolve'' error. I've changed the code in multiple ways and read the docs, but I'm still confused.
'python manage.py findstatic /file/css/syle.css' didn't help much either.
from urls.py:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib import admin
from home import views
admin.autodiscover()
urlpatterns = [ patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^home/$', views.Home, name="home"),
url(r'^services/$', views.Services, name="services"),
url(r'^contact/$', views.Contact, name="contact"))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
from settings.py:
STATIC_URL = 'home/static/'
STATIC_ROOT = 'sitename/home/static/css.js'
STATIC_DIRS = 'home/static'
project structure:
sitename
db.sqlite3
home
__init.py
admin.py
models.py
static
home.html
services.html
contact.html
views.py
manage.py
mysite
__init.py
settings.py
urls.py
wsgi.py
What am I missing?
Also, I'd love your recommendations for reference material.
from home.html:
{% load staticfiles %}
{% block doctype %}<!DOCTYPE HTML>{% endblock %}
{% load i18n %}
<html>
<head>
<title>{% block title %}{% endblock %}{% trans "title" %}</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
{% block meta_tags %}{% endblock %}
<noscript>
<link rel="stylesheet" href="css/skel.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-wide.css" />
</noscript>
{% block stylesheet %}{% endblock %}
<script src="js/jquery.min.js"></script>
<script src="js/jquery.doc.min.js"></script>
<script src="js/doc.min.js"></script>
<script src="js/doc-layers.min.js"></script>
<script src="js/init.js"></script>
{% block js %}{% endblock %}
</head>
<body class="{% block bodyclass %}{% endblock%}">
{% block page %}
<div id="header">{% block header_navigation %}
<h1>{% trans "header/name of business" %}<em>content description</em></h1>
<nav id="nav">
<ul>
<li class="current">Home</li>
<li>Services</li>
<li>Contact Us</li>
</ul>
</nav>
{% endblock %}
</div>
<section class="wrapper style1">
<div class="container">
<div class="row 200%">
<section>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</div>
</div>
</section>
<div id="footer">
{% block footer %}
<div class="container">
<div class="row">
<section class="3u 6u(narrower) 12u$(mobilep)">
</section>
{% endblock %}
</div>
</div>
<div class="copyright">
<ul class="menu">
<li>© All rights reserved</li><li>Adapted by: me</li>, Original Design: someone else</li>
</ul>
</div>
</div>
{% endblock %}
</body>
</html>
You should remove square brackets around the patterns() and add staticfiles_urlpatterns() to the urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^home/$', views.Home, name="home"),
url(r'^services/$', views.Services, name="services"),
url(r'^contact/$', views.Contact, name="contact")
) + staticfiles_urlpatterns()
Change settings to:
STATIC_URL = '/static/'
STATIC_ROOT = '/absolute/path/to/static/dir/in/doc_root/'
# For example: /var/www/yoursite.com/static/
STATIC_ROOT should be set on production server. Development server ignores this setting.
STATIC_DIRS is not required for your project layout. Django automatically uses static directories in all apps from the INSTALLED_APPS as the source for static files.
To link to static assets you need to use the {% static %} template tag. For example instead of:
<link rel="stylesheet" href="css/style.css" />
code should be like this:
<link rel="stylesheet" href="{% static 'css/style.css' %}" />
BTW do not place templates into the static dir. manage.py collectstatic will make source code of these templates available for everyone. I suspect you don't want this :-)
the return type of static is a list, you should expand it:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
*static(settings.STATIC_URL, document_root=settings.STATIC_ROOT),
]

Categories