How do I get the post_detail page to work? - django

Following is my urls.py file:
from django.urls import path, re_path, include
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='list'),
path('<slug>/', views.post_detail, name='detail'),
]
My views.py file:
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list(request):
posts = Post.objects.all().order_by('date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, slug):
post_det = Post.objects.get(slug=slug)
return render(request, 'blog/post_detail.html', {'singlepost': post_det})
And my post_detail.html page:
{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
<div class="row">
{% for post in posts %}
<div class="post col-md-10 shadow mx-auto">
<!-- post-thumbnail -->
<div class="post-thumbnail">
<img src="{{singlepost.thumb.url}}">
</div>
<!-- /post-thumbnail -->
<h2 class="post-title bg-dark text-light pad1 text-center">{{ singlepost.title }}</h2>
<p class="post-content">{{ singlepost.body }}</p>
<p class="post-info grey border pad1">{{ singlepost.date }}</p>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
Screenshot from the error page:
Django - Page Not Found Error
What appears to be the problem here? Keep in mind that I'm new to django, however, this is the first time I come across an url such as the one noted in the error report.

I have made few changes,
In urls.py,
path('detail/<slug:slug>/', views.#restofyoururl ),
You have not added your homepage html, so check if you have added the url correctly. In your homepage html
<a href={% url 'blog:detail' post.slug %}> {{post.title}}#add as per your model </a>
Note : You can add class based view for your detail page.

Related

Cannot get url parameter to work in Django

I am trying to pass a parameter through the url in Django, but nothing seems to be working.
This is my views.py:
from django.shortcuts import render
def show_user_profile(request, user_id):
assert isinstance(request, HttpRequest)
return render(request, "app/show_user_profile.html", {'user_id': user_id})
This is currently my urls.py:
urlpatterns = [
path('', views.home, name='home'),
path('profile/', views.profile, name='profile'),
path(r'^show_user_profile/(?P<user_id>\w+)/$', views.show_user_profile, name="show_user_profile"),
path('admin/', admin.site.urls),
]
I've tried
http://localhost:50572/show_user_profile/aaa
http://localhost:50572/show_user_profile/aaa/
http://localhost:50572/show_user_profile/aaa//
http://localhost:50572/show_user_profile/?user_id=aaa
but I always get that same screen saying it can't find the url pattern.
But I've tried, all failed.
And neither does this:
path('show_user_profile/<int:user_id>/$', views.show_user_profile, name='show_user_profile')
This doesn't work either, by the way.
path(r'^show_user_profile/$', views.show_user_profile, name="show_user_profile"),
I've looked at the answers here and here, and I seem to be doing everything right. What am I missing?
EDIT:
Here's my show user profile template:
{% extends "app/layout.html" %}
{% block content %}
{% if request.session.uid %}
<div id="profile">
<div>
<span id="profile_prof_pic_content">
<img id="prof_pic" src="{{ user_data.prof_pic }}" width="100" height="100" />
</span>
<span>
{{ user_data.first_name }} {{ user_data.last_name }}
</span>
</div>
<div>
{{ user_data.prof_desc }}
</div>
</div>
{% else %}
<h2>You are not signed in. Log in to access this user profile.</h2>
{% endif %}
{% endblock %}
{% block scripts %}
{% load static %}
<script src="{% static 'app/scripts/jquery.validate.min.js' %}"></script>
Instead of this:
path(r'^show_user_profile/(?P<user_id>\w+)/$', views.show_user_profile, name="show_user_profile"),
Try this:
re_path(r'^show_user_profile/(?P<user_id>\w+)/$', views.show_user_profile, name="show_user_profile"),
And try to navigate on browser
Note: I have used re_path instead of path. you can check here

How to prevent redirect_to_login from targeting LOGIN_REDIRECT_URL

So in general when a user logs in, my app redirects him to dashboard-overview:
# settings.py
# Login and Logout target routes
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'dashboard-overview'
LOGOUT_REDIRECT_URL = '/'
However for a specific case I want the user to be redirected to 'calculator-page' using a helper function which doesn't work as the user is again redirected to the value of LOGIN_REDIRECT_URL.
# views.py
def render_calculator(request, slug):
"""
Renders the calculator page
"""
# Check for the user being authenticated
if not request.user.is_authenticated:
return redirect_to_login('calculator-page')
# routes to http://127.0.0.1:8000/login/?next=calculator-page which looks fine,
# but then it fails after login to re-route as specified and sends to
# 'dashboard-overview' again
else:
club_obj = Offer.objects.get(club__slug=slug)
# Create Context
context = {
'club_obj': club_obj,
}
return render(request, 'core/calculator.html', context)
# urls.py
from django.urls import path, include
from django.contrib.auth import views
from applications.user import views as user_views
urlpatterns = [
# Login View
path('login/', views.LoginView.as_view(template_name='user/login.html'), name="login"),
path('logout/', views.LogoutView.as_view(), name="logout"),
# Sign Up
path('signup/', user_views.signup, name='signup'),
]
# template user/login.html
{% extends 'user/user_frame.html' %}
{% load static %}
<!-- Styles -->
{% block styles %}
<link href="{% static 'css/user_frame.css' %}" rel="stylesheet" type="text/css">
{% endblock styles %}
{% block form %}
<div class="logo-container"><img src="{% static 'images/logo_negative_text.svg' %}" class="logo-image"></div>
<div class="form-container">
<!-- form headline -->
<h1 class="form-headline">Login to your Farena Account</h1>
<!-- form -->
<form class="form" method="post" action=".">
{% csrf_token %}
<div class="error-wrapper">
<div class="errors">{{ form.non_field_errors }}</div>
</div>
<div class="email-wrapper field-wrapper">
<div class="tag name-tag">{{ form.username.label }}*</div>
<div class="input">{{ form.username }}</div>
</div>
<div class="password-wrapper field-wrapper">
<div class="tag">{{ form.password.label }}*</div>
<div class="input">{{ form.password }}</div>
<div class="forgot-password">Forgot Password?</div>
</div>
<!-- submit button -->
<button class="login-button" type="submit">Log In</button>
</form>
</div>
<div class="account-info">No account yet? Sign Up!</div>
{% endblock form %}
The issue is with your template for the login view - you're missing the next form field that tells Django where to redirect the user after they have logged in. See the documentation for sample template code for this view.
Specifically, you need to add this inside your form:
<input type="hidden" name="next" value="{{ next }}">
That's missing right now which means Django will always just default to LOGIN_REDIRECT_URL.

Django form not visible after redirect

I'm trying to make django form to appear after user is logged in and authenticated but the form just does not appear on the page here is my code. I'm stuck on this for few days now and any help would be huge help
Views.py form code
def prasymas(request):
context = initialize_context(request)
user = context['user']
form = Prasymas(request.POST or None)
if form.is_valid():
form.save()
context ={
'form':form
}
return HttpResponseRedirect(reverse('home'))
urls.py code
from django.urls import path
from . import views
urlpatterns = [
# /
path('', views.home, name='home'),
# TEMPORARY
path('signin', views.sign_in, name='signin'),
path('signout', views.sign_out, name='signout'),
path('callback', views.callback, name='callback'),
path('prasymas', views.home, name='prasymas'),
]
template.py code
{% extends "loginas/layout.html" %}
{% block content %}
<div class="container">
<h1 class="d-flex justify-content-center"></h1>
<p class="d-flex justify-content-center"></p>
{% if user.is_authenticated %}
<h4>Sveiki {{ user.firstname }} {{user.surname}}
</h4>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-secondary">POST</button>
</form>
{% else %}<div class="d-flex justify-content-center">
Prisijungti
</div>
{% endif %}
</div>
{% endblock %}
From your urls.py it looks like the prasymas function in views.py is not being called.
Try making the following change to your urls.py file to include a call to the prasymas function.
Note: the line path('prasymas', views.prasymas, name='prasymas'), now points to views.prasymas not home. This means the path /prasymas will now render your form.
from django.urls import path
from . import views
urlpatterns = [
# /
path('', views.home, name='home'),
# TEMPORARY
path('signin', views.sign_in, name='signin'),
path('signout', views.sign_out, name='signout'),
path('callback', views.callback, name='callback'),
path('prasymas', views.prasymas, name='prasymas'),
]

Django: objects are not showing at index page

This is my first project with Django and I got a problem. In the backend I created news, but I have an issue displaying the news on the frontpage. Models should be fine since I can create news into the admin panel. But I can't figure out where is my mistake.
I have app 'pages'>views.py
from django.shortcuts import render, redirect, get_object_or_404
from mainnews.models import Mainnews
# Create your views here.
def home_view(request):
main = Mainnews.objects.all()
context = {
'main' : main
}
return render(request, 'index.html', context)
root>urls.py
from pages.views import home_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name = 'home'),
]
and app mainnews>views.py
from django.shortcuts import render, get_object_or_404
from .models import Mainnews
# Create your views here.
def index(request):
main = Mainnews.objects.all()
context = {
'main' : main
}
return render(request, 'index.html', context)
and the template mainnewsandevents.html that extends to index
{% block content %}
<!-- Section 2 News and Events -->
<div id="news-container">
<div class="jumbo-news">
<img id = 'jumboImgUrl' class='jumbo-img' src="{{ main.image.url }}">
<h2 id = 'jumboTitle' class='jumbo-title'>{{ main.title }}</h2>
<h4 id = 'jumboDescription' class='jumbo-parag'>{{ main.description }}</h4>
</div>
{% endblock %}
Fix it like this:
def home_view(request):
main = Mainnews.objects.first()
# or main = Mainnews.objects.last()
# other code
or if you need to show all objects on your template use something like it:
{% block content %}
<!-- Section 2 News and Events -->
<div id="news-container">
<div class="jumbo-news">
{% for article in main %}
<img id = 'jumboImgUrl' class='jumbo-img' src="{{ main.image.url }}">
<h2 id = 'jumboTitle' class='jumbo-title'>{{ main.title }}</h2>
<h4 id = 'jumboDescription' class='jumbo-parag'>{{ main.description }}</h4>
{% endfor %}
</div>
{% endblock %}
Depends on your needs.
Also you shouldn't use not obvious names for variables so you shall use main_news instead of main.
main is an array of objects right so you need a for loop to get every object
{% block content %}
<!-- Section 2 News and Events -->
<div id="news-container">
<div class="jumbo-news">
{% for obj in main %}
<img id = 'jumboImgUrl' class='jumbo-img' src={{ obj.image.url }}>
<h2 id = 'jumboTitle' class='jumbo-title'>{{ obj.title }}</h2>
<h4 id = 'jumboDescription' class='jumbo-parag'>{{ obj.description }}</h4>
{% endfor %}
</div>
{% endblock %}

Django Error After Changing/Reverting Views

I was changing some views earlier related to some geolocation (that failed) and upon restoring the previous views, I'm receiving this error:
TemplateSyntaxError at /report/all/
Caught NoReverseMatch while rendering: Reverse for 'profiles_profile_detail' with arguments '('',)' and keyword arguments '{}' not found.
What's odd is that the views I altered and restored had nothing to do with this view or template. The urls.py file was not touched at all. All other pages in the application are displaying normally. I can't figure out what the problem might be.
Views:
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from myapp.report.models import Story, UserProfile
from myapp.report.forms import ProfileForm, StoryForm
from django.contrib.auth.decorators import login_required
from django.contrib.gis.utils import GeoIP
def all_stories(request):
if not request.user.is_authenticated():
return redirect("django.contrib.auth.views.login")
all_stories = Story.objects.all().order_by("-date")
return render_to_response("report/storyline.html",
{'stories': all_stories},
context_instance=RequestContext(request))
def story_detail(request, story_id):
story = get_object_or_404(Story, id=story_id)
return render_to_response('report/detail.html',
{'story': story},
context_instance=RequestContext(request))
#login_required
def submit_story(request):
if request.method =="POST":
story_form = StoryForm(request.POST, request.FILES)
if story_form.is_valid():
new_story = story_form.save(commit=False)
new_story.author = request.user
new_story.save()
return HttpResponseRedirect("/report/all/")
else: # GET request
story_form = StoryForm()
return render_to_response("report/report.html", {'form': story_form}, context_instance=RequestContext(request))
Forms (changed but restored; appear to be working):
from django import forms
from stentorian.report.models import UserProfile, Story
from django.contrib.gis.utils import GeoIP
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
class StoryForm(forms.ModelForm):
class Meta:
model = Story
exclude = ('author',)
Template:
{% extends 'base.html' %}
{% block page_title %}Stentorian{% endblock %}
{% block headline %}Stentorian Storyline{% endblock %}
{% block content %}
<div class="row">
<div class="span12">
<h2>Welcome {{ user.username }}</h2>
<div class="accordion" id="story_accordion">
{% for story in stories %}
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle story-header" data-toggle="collapse" data-parent="#story_accordion" href="#story_{{ story.id }}">
{{ story.title }} - {{ story.author.username }} - {{ story.date }}
</a>
</div>
<div id="story_{{ story.id }}" class="accordion-body collapse{% if forloop.counter0 == 0 %} in{% endif %}">
<div class="accordion-inner">
<!-- <h2>{{story.title}}</h2>-->
<span>{{story.author}} </span><br>
<span>{{story.topic}}</span><br>
<span>{{story.zip_code}}</span><br>
<span>{{story.date}}</span><br>
<p>{{story.copy}}</p>
</div>
</div>
</div>
<br>
{% endfor %}
</div>
</div>
</div>
{% endblock content %}
The error is coming up on the line:
{% for story in stories %}
If anyone can provide an idea of why this is happening, it would be most appreciated. Again, the url wasn't changed, which seems to be the chief reason for this error.
Seems like u r not getting user.username
Try with this.
<h2>Welcome {{ request.user.username }}</h2>