Django: active Home link - django

This is my first project with django, I wanted my static site html/css/js to turn it into a dynamic website. However, in navMenu I want to have 'home' link only if the user is not on the index page.
Here is my attempt:
<style>
#hm{
display:none;
}
.activate{
display:block;
}
</style>
<div id="navMenu" class='py px'>
<ul>
{% url 'home' as home_view %}
<li id = 'hm' {% if request.get_full_path != home_view%} class = 'activate' {% endif%}>Home</li>
<li class='brd'>Alumni</li>
<li class='brd'>Staff</li>
<li class='brd'>Services</li>
<li class='brd'>About</li>
<li><a id='btnSearch' href="#"><i class="fa fa-search searchUpdate"></i></a></li>
</ul>
</div>
the urls:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from pages.views import home_view
from events.views import events
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name = 'home'),
path('events/', events, name = 'events')
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Any help is appreciated!

You could try adding a content block with and adding it only to the templates that you want to have the url on
If you dont know how to do that then it goes like this
<div id="navMenu" class='py px'>
{% block urls %}{% endblock urls %}
</div>
Then, for all of the pages that you want the url to be on, make a new template with:
{% block urls %}
<ul>
{% url 'home' as home_view %}
<li id = 'hm' {% if request.get_full_path != home_view%} class = 'activate' {% endif%}>Home</li>
<li class='brd'>Alumni</li>
<li class='brd'>Staff</li>
<li class='brd'>Services</li>
<li class='brd'>About</li>
<li><a id='btnSearch' href="#"><i class="fa fa-search searchUpdate"></i></a></li>
</ul>
{% endblock urls %}

Related

Why I can not display two listviews in one template?

I am working on a Django project where admin can upload a hero banner to the site and can also upload a notification on the home page of the site.
So I made listviews for listing the two HeroListView and NotificationListView for that.
But the second one is not appearing in the page.
Please tell me how to solve this issue.
This is the models.py file
from django.db import models
class Hero(models.Model):
image = models.ImageField(upload_to="heros/")
class Notification(models.Model):
notification = models.CharField(max_length=200)
This is the views.py file.
from django.views.generic import ListView
from .models import Hero, Notification
class HeroListView(ListView):
model = Hero
template_name = "home.html"
context_object_name = "hero_list"
class NoticficationListView(ListView):
model = Notification
template_name = "home.html"
context_object_name = "notification_list"
this is the app/urls.py file
from django.urls import path
from .views import HeroListView, NoticficationListView
urlpatterns = [
path("", HeroListView.as_view(), name="home"),
path("", NoticficationListView.as_view(), name="home"),
]
this is the project/urls.py file
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("heros.urls")),
path("", include("products.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{% extends '_base.html' %}
{% block title %}Home{% endblock title %}
{% block content %}
{% load static %}
<div class="container mt-4">
<div id="carouselExampleControls" class="carousel carousel-dark slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="{% static 'images/hero2.jpg' %}" class="d-block w-100" alt="..." style="max-height: 400px;">
</div>
{% for hero in hero_list %}
<div class="carousel-item">
<img src="{{ hero.image.url }}" class="d-block w-100" alt="..." style="max-height: 400px;">
</div>
{% endfor %}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="div">
{% for note in notification.list %}
<p>{{ note.notification }}</p>
{% endfor %}
</div>
</div>
{% endblock content %}
please tell me how to solve this issue.
You can do it this way
class HeroListView(ListView):
model = Hero
template_name = "home.html"
def get_context_data(self):
context = super(HeroListView, self).get_context_data()
context['hero_list'] = Hero.objects.all()
context['notification_list'] = Notification.objects.all()
return context
You can't access two or multiple views at the same time, so in your case, you can remove NoticficationListView and use only HeroListView to render both hero_list and notification_list

Page not found (404) Request Method:

please help me. I don't know why can't see the detail of product when i click a product. both first list work good just when i need to see detail of product in second list(filtered list) an 404 error shows.
thanks
here is my code below:
my urls:
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('categories/<category>/', views.ProductListView.as_view(), name='product-list'),
path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
]
views:
from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.views import generic
from .models import Category, Product
class HomeView(generic.ListView):
model = Category
template_name = 'home.html'
class ProductListView(generic.ListView):
template_name = 'product_list.html'
def get_queryset(self):
self.category = get_object_or_404(Category, title=self.kwargs['category'])
return Product.objects.filter(category=self.category)
class ProductDetailView(generic.DetailView):
model = Product
template_name = 'product_detail.html'
product_list.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
Welcome | Global Market
{% endblock %}
{% block content %}
{% for product in product_list %}
<a href="{% url 'shop:product-detail' product.pk %}">
<div class="card bg-light mb-3" style="max-width: 18rem;">
<div class="card-header">{{ product.title }}</div>
<img class="card-img-top" src="{{ product.image.url }}" alt="{{ product.title }}">
<div class="card-body">
<p class="card-text">{{ product.description }}</p>
</div>
</div>
</a>
{% endfor %}
{% endblock %}
product_detail.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
Welcome | Global Market
{% endblock %}
{% block content %}
<h1>thid</h1>
{{ product.name }}
{% endblock %}
Even if the you visit /categories/1, it will use the ProductListView, since the str path converter also accepts a sequence of digits. You can swap the paths, so:
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
path('categories/<category>/', views.ProductListView.as_view(), name='product-list'),
]
Then for /categories/1, it will match with <int:pk> as 1, and thus fire the ProductDetailView.

no reverse matching at / and crawler is not a registered namespace

I am trying to make a codeforces crawler and I am just adding user authentication in the somehow failed to implement. Reverse not match and crawler is not a registered namespace is the error I'm getting. I don't know what files exactly are needed to put here so please ask me I will post them if you need it. I'm just a beginner and I need help.
crawler/urls.py
app_name = 'crawler'
urlpatterns = [
path('',views.index,name='index'),
path('formpage/',views.search_form_view , name='searchform'),
path('formpage/<str:handle>',views.person, name= 'person'),
path('user_login/',views.user_login,name ="user_login"),
path('logout/',views.user_logout,name="logout"),
]
base.html
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="{% url 'crawler:index'%}">Crawler</a>
<!-- Links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'crawler:searchform'%}">Search</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 2</a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{%url 'crawler : logout'%}">Log Out</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{%url 'crawler :user_login'%}">Login</a>
{% endif %}
</li>
</li>
</ul>
</nav>
<br>
{% block body_block %}
{% endblock %}
</body>
views.py
#login_required
def user_logout(request):
logout(request)
return HttpResponse(reverse('index'))
webcrawler/urls.py
app_name = 'crawler'
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('crawler.urls',namespace= "crawler")),
]
A two-part answer here.
No reverse match at /
The point is that, in both your main and app urls.py, you registered both URLs to be '', which means that there will be a match at (empty string) but won't be one at '/'. To fix this, simply add '/' to the main urls.py as it's a better practice.
Crawler is not a registered namespace
As you call an URL, it should be {% url 'crawler:index' %} or {% url 'crawler:searchform' %} or something because crawler is the main namespace but there are multiple URLs under it so you need to pass an additional parameter after your crawler namespace.

Django 3.0.3: NoReverseMatch at / : Reverse for 'post_new' with no arguments not found. 1 pattern(s) tried:

Need Help. I am not passing an argument while using href but still url pattern is looking for an argument.
Master urls.py
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^$',include('portfolio.urls')),
re_path(r'accounts/login/$',LoginView.as_view(),name='login'),
re_path(r'accounts/logout/$',LogoutView,name='logout',kwargs={'next_page':'/'})
]
Portfolio.urls
urlpatterns = [
re_path(r'^$',views.PostListView.as_view(),name='post_list'),
re_path(r'^about/$', views.AboutView.as_view(),name='about'),
path ('post/new/',views.CreatePostView.as_view(),name='post_new'),
re_path (r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),]
<nav class="navbar navbar-dark bg-dark">
<div class ="container">
<ul class= "navbar navbar-dark bg-dark">
<li><a class='navbar-brand' href="{% url 'post_list' %}"> My Blog </a>
<li>Github</li>
<li>Linkedin</li>
</ul>
<ul class='nav nsvbsr-right'>
{% if user.is_authenticated %}
<li>
New Post
Draft
Log Out
</li>
<li>
<a> Welcome : {{ user.username }} </a>
</li>
{% else %}
<li> <a class='nav nsvbsr-right' href="{% url 'login' %}"> Login </a> </li>
{% endif %}
</ul>
</div>
</nav>
I am getting the following error:
In Short: Page throws the error after user logs in (i.e. is_authenticated is true).
Models.py
class CreatePostView(LoginRequiredMixin, CreateView):
login_url="/login/"
redirect_field_name="portfolio/post_detail.html"
form_class = PostForm
model = Post
Remove the dollar from the URL pattern that includes portfolio.urls.
re_path(r'^',include('portfolio.urls')),
Or switch to path:
path('',include('portfolio.urls')),

How To Fix Auto Login In Django?

How To Fix Auto login When I go to this URL like this: 127.0.0.1:8000/profile/1 When I see If Someone go to that URL so Django login him without password and username
ERROR:
How To Fix Auto Login In Django
You Can See The Gif For More Details:
Views.py
def profile_detail(request,pk):
user = get_object_or_404(User, pk=pk)
model = user_register_model()
return render(request,'profile_detail_view.html',{'user':user,'model':model,})
urls.py
from . import views
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index,name='index'),
path('accounts/signup/', views.user_reg,name='register'),
path('profile/<int:pk>',views.profile_detail,name='profile'),
]
Here is my Base.html
<ul class="navbar-nav ml-auto">
{% if not user.is_authenticated %}
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'register' %}"><i class="fa fa-check-square-o"></i> Sign up Free</a>
</li>
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'login' %}"><i class="fa fa-user"></i> Login</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link navaour" href=""><i class="fa fa-user"></i> Profile</a>
</li>
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'logout' %}"><i class="fa fa-power-off"></i> Logout</a>
</li>
{% endif %}
Here is my profile_detail_view.html
<div class="row">
<div class="col-sm-3 col-md-2 col-5">
<label style="font-weight:bold;">Full Name</label>
</div>
<div class="col-md-8 col-6">
{{user.username}}
</div>
</div>
Any Help Appreciated
Thanks!
replace {% if not user.is_authenticated %} with {% if not request.user.is_authenticated %} in your template. You missed request.
you can also use #login_required before the def in views.py and importing library
from django.contrib.auth.decorators import login_required
This will help in blocking those views of url for the users who aren't logged in.