url routing in django? - html

I am creating website in django from 2 to 3 pages so the problem is in the html part when linking the pages in html there is two pages now ( index " the main home page for the site - about)
so when I run the server it open the index page and when I click on about link the url will be (www.xxxx.com/about/about) and when I click on the index link the url will be( www.xxxx.com/about) not the index page . so the two link direct me to the about page but with different url
here is the url in the main project :
urlpatterns = [
path('',include('pages.urls')),
path('about/',include('pages.urls')),
path('admin/', admin.site.urls),
]
and the urls.py in pages app:
urlpatterns = [
path('',views.index , name='index'),
path('about/',views.about , name='about'),
]
and the views.py in pages app :
def index(reqouest):
return render(reqouest,'pages/index.html')
def about(reqouest):
return render(reqouest ,'pages/about.html')
and the about html page :
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> About</li>
</ol>
</nav>
</div>
</section>
p.s I put the html pages in template/pages folder

Remove path('about/',include('pages.urls')) from your main app urls.
You shouldn't have 2 url prefixes that include the same urls. Only the last include will be used when you're reversing urls by name since you're basically defining the same name twice.
When you do path('about/', include('pages.urls')), you're telling django to build all the urls in pages.urls prefixed by about/, so /about/ becomes the "index" url pattern and /about/about/ the "about" url pattern.
The first include (path('', include('pages.urls'))) means you're creating the urls / and /about/, which will work, but they won't be named urls anymore since you override the names with your second include.
So if you remove your second include for pages.urls, you'll get what you want.

Related

Dynamic URL routing is not working in django web application

A am working on a simple application, where trying to generate Dynamic URl and routing take place as per the ID in the url.
Dynamic value is getting populated in the URL, but it not performing action that needed.
prop_listings.html HTML Page:-
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i> {{ listing.list_date | timesince }}
</div>
</div>
<hr>
More Info
</div>
</div>
</div>
URL.py in App Listings:-
from django.urls import path
from . import views
urlpatterns = [
path('',views.PropListings,name="prop_listings"),
path('<int:listing_id>', views.mlisting, name="morelisting"),
]
Views.py :-
def mlisting(request, listing_id):
# listingDetl = get_object_or_404(Listing, pk=listing_id)
listingDetl = Listing.objects.get(pk=listing_id)
print(listingDetl.username, listingDetl.address,listingDetl.city)
context = {
'listingDetails': listingDetl
}
return render(request,'listings/detail_listing.html', context)
URL.py in MainProject:-
urlpatterns = [
path('', include('static_pages.urls')),
path('user_account/', include('user_account.urls')),
path('listings/', include('listings.urls')),
path('feedback/', include('feedback.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Am trying to redirect the page from prop_listings.html to detail_listing.html, based on the below tag URL generated on listing.id
More Info
It's not working as expected on-click of above tag.
But when i did inspect on the same, URL is getting generated properly and when i click on the url, it will work as expected.
Inspect on the html page, URL populated
I looked into similar issue threads and tried to make changes, but not able to fix it.
Not getting what the issue and how to correct it.

getting unexpected/unwanted url path when clicking on an href link in django

so, here are all the urls i defined:
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("new", views.new.as_view(), name="new"),
path("<int:user>/watchlist", views.watchlist, name="watchlist"),
path("<int:user>/<str:name>", views.name, name="name"),
path("<str:user>/<str:name>/watchlist/remove", views.remove, name="remove-from-watchlist"),
path("<int:user>/<str:name>/watchlist/add", views.add, name="add-to-watchlist"),
path("<str:user>/<str:name>/bid", views.bid, name="bid"),
path("<str:user>/<str:name>/close", views.close, name="close-bid"),
path("<str:user>/<str:name>/comment", views.comment, name="comment"),
path("add-category", views.addC, name="add-Category"),
path("categories", views.categories, name="categories"),
path("<str:cat>/category", views.cat, name="category-page")
From experience, the problem is with all the 'watchlist' related URLs.
For example, when i am on index view, the path to path("<int:user>/watchlist", views.watchlist, name="watchlist"), is <a class="nav-link" href="{{ user.id }}/watchlist">Watchlist</a>
and the url path shows the same -
http://127.0.0.1:8000/2/watchlist
where 2 is the user id. Then when i go to a url <a class="nav-link" href="categories">Categories</a> the url path followed is
http://127.0.0.1:8000/2/categories
the '2' should not be there! I specifically hard coded the path in the anchor tag
I am facing another problem:
when i am at the index view and i click on the anchor tag containing <a href=/{{ user.id }}/{{ item.Title }}
where item.Title is say "Magic Broom", the url path i am getting is
http://127.0.0.1:8000/2/Magic
while it should have been
http://127.0.0.1:8000/2/Magic Broom
Can someone please explain what's going on here...
the correct reverse for the path would be like this:
path("<int:user>/watchlist", views.watchlist, name="watchlist")
some text
In your example you built the url "manually" instead you should always go reverse via path->name definition which is done by the {% url ... %}. Why? if your urls change you only have to update paths in the settings.py

Dynamic HTML Templates with PureCSS

I am building a web app using flask. I found that I am retying the same thing over and over with a minor edit into everyone of my HTML pages so I want to make it into a template. How can I make it a dynamic template? Below is the code that I use for my ABOUTUS page which is just one line different from my CONTACT page.
About Us Page header:
<div id="menu">
<div class="pure-menu">
<a class="pure-menu-heading" href="#">WebAPP</a>
<ul class="pure-menu-list">
<li class="pure-menu-item">Home</li>
<li class="pure-menu-item menu-item-divided pure-menu-selected">About</li>
<li class="pure-menu-item">Membership</li>
<li class="pure-menu-item">Contact</li>
{% if current_user.is_authenticated %}
<li class="pure-menu-item">Log out</li>
{% else %}
<li class="pure-menu-item">Log in</li>
{% endif %}
</ul>
</div>
Contact Page header:
<div id="menu">
<div class="pure-menu">
<a class="pure-menu-heading" href="#">WebAPP</a>
<ul class="pure-menu-list">
<li class="pure-menu-item">Home</li>
<li class="pure-menu-item">About</li>
<li class="pure-menu-item">Membership</li>
<li class="pure-menu-item menu-item-divided pure-menu-selected">Contact</li>
{% if current_user.is_authenticated %}
<li class="pure-menu-item">Log out</li>
{% else %}
<li class="pure-menu-item">Log in</li>
{% endif %}
</ul>
</div>
</div>
The only change is that I move the menu-item-divided pure-menu-selected line from one line to the other based on what template I am loading. I cannot think of a way to do this dynamically so that I can turn this into a template that I can just extend for every file.
You could just use standard jinja template inheritance as mentioned in comment above.
Docs here: Template Inheritance
Method 1:
Import request method in your routes.py file,
Use jinga if condition to check whether page is pointing to
current url endpoint.
<li class="pure-menu-item{% if request.path == '/contact'} menu-item-divided pure-menu-selected{% endif %}"><a href="/contact" class="pure-menu-link">Contact</a</li>
Tip: You can use flask dynamic url difination {{ url_for('contact') }} instead of hard coding urls.
Method 2: (recommended)
This is not related to flask jinja but does the work as intended in front-end but using JavaScript with jQuery library.
Add this script at the end of the template before closing body tag.
jQuery version
<script>
let current_path = "{{ request.path }}"
if (current_path === window.location.pathname) {
$(".pure-menu-item a[href='"+current_path+"']")
.prop("href", "#").closest('li')
.addClass("pure-menu-item menu-item-divided pure-menu-selected");
}
</script>
Vanilla JS (plain js)
<script>
let current_path = "{{ request.path }}"
let current_nav = document.querySelctor("div.pure-menu-item a[href='"+current_path+"']");
if (current_path === window.location.pathname) {
current_nav.setAttribute("href", "#");
current_nav.closest('li').classList.add("pure-menu-item menu-item-divided pure-menu-selected");
}
</script>
What it does?
If the current url matches to the url specfied in navigation above, it adds the menu-item-divided pure-menu-selected class to the div and disables the current url routing by replacing the actual url to #.
Clean and elegant.
Why?
If you use JavaScript you don't have to define hundreds of {% if... %} in back-end, those if statements you defined in back-end will be checked in every pages user loads, additionally you just saved on more ifs and elses to check if loaded page is nav link's page and disable routing by change url to #. Wow you just saved millions of cpu cycles. :-)

how to show external media in template in django

Hi i'm currently new to Django and i'm trying to populate a product page.
I'm having problem with the img to show the image(which uses an image url online instead of a file) for example an img src="media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg"
The url already in my database with the text media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg
But when i tried to render it in template the image doesn't show
I tried to used the but it still not work
Any help would be appreciate!
My template
{% for discount in discounts|slice:":8" %}
<div class="col-md-3 product-men women_two">
<div class="product-googles-info googles">
<div class="men-pro-item">
<div class="men-thumb-item">
<img src="{{STATIC_URL}}{{discount.product_image}}" alt="" />
<div class="men-cart-pro">
<div class="inner-men-cart-pro">
Quick View
</div>
</div>
<span class="product-new-top">New</span>
</div>
<div class="item-info-product">
<div class="info-product-price">
<div class="grid_meta">
<div class="product_price">
<h4>
{{discount.product_name}}
</h4>
<div class="grid-price mt-2">
<span class="money">{{discount.product_old_price}}</span>
</div>
</div>
<div>
<h3>{{discount.product_sit}}</h3>
</div>
<div><h2 style="color: red;">Only {{discount.product_price}}!</h2></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
{% endfor %}
EDIT
Seems like the image src trying to get is "http://127.0.0.1:8000/media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg" which i don't want "http://127.0.0.1:8000/" in the link. Is there a way to remove this when using {{discount.product_image}} tag ?
Main project urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('frontend.urls')),
]
frontend app urls.py:
from django.urls import path
from .import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'frontend'
urlpatterns = [
#index
path('',views.index, name='index')
]
Try using .url like this.
<img src="{{ discount.product_image.url }}" alt=""/>
Also add the MEDIA and STATIC url to your project url patterns.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URL pattern goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
EDIT:
From the discussion in chat, I understood that I had misunderstood your problem first. The images are external and not in your db, you are just storing the URL to the images. And you are using a TextField not ImageField. I assumed ImageField previously. So, all you have to do is to replace {{STATIC_URL}} from in front of the actual URL and put http:// there. The reason behind this is, as the src is missing http:// it's assumed the image to be in the same host domain. So it goes to http://127.0.0.1/your_url.
<img src="http://{{ discount.product_image }}" alt=""/>

django <a href='...'> redirected to account/login by chrome

Can someone explain what is happening? The following href works on firefox but gets redirected inside Chrome. Any my visualization view is not displayed.
BEHAVIOR
I am at the top page of myapp... drawn via mysite.views.page showing templates/myapp/home.html (extends a navigation set of buttons via templates/myapp/base.html).
When I hover over the button it displays
127.0.0.1:8000/vis/myapp/assets.default
When I click on it I get different behavior
Firefox - invokes the view and visualization occurs correctly.
myapp.views.visualization module
On Chrome, it displays the login page... url of page is
http://127.0.0.1:8000/accounts/login/?next=vis/myapp/assets.default
What is ?next=
I have confimed that views.visualization() is not called.
I don't see any GET posting in the logs?
Any help is greatly appreciated. Below is the code... let me know if you need to see other things.
templates/myapp/base.html
{% block app_nav_list %}
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>Assets</li>
<li>...</li>
...
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">My<br>Settings<b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li>...</li>
<li>...</li>
</ul>
</li>
mysite.views.page()
def page(request, hname = 'index'):
pagePath = hname.strip().split('.')
pgName = '/'.join(pagePath)
return render_to_response(pgName+'.html')
myapp/urls.py
from mysite.urls import urlpatterns
urlpatterns += patterns('',
url(r'^vis/myapp/(?P<visualName>.*)', 'myapp.views.visualization'),
url(r'^actions/myapp/(?P<actionName>.*)', 'myapp.views.actions'),
)
mysite/urls.py
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='base.html')),
# Serve pages per each app using views.pages (relative to templates)
# calls views.pages(request, pagename=xx, apptops=x)
url(r'^page/(?P<hname>.*)', 'mysite.views.page'),
)
# Import APP URLS
import myapp.urls
#
# Admin URLS
#
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
admin_urlpatterns = patterns('',
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# login/registration auth urls
url(r'^accounts/login/$', 'mysite.views.login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^accounts/auth/$', 'mysite.views.auth_view'),
url(r'^accounts/loggedin/$', 'mysite.views.loggedin'),
url(r'^accounts/invalid/$', 'mysite.views.invalid_login'),
url(r'^accounts/register/$', 'mysite.views.login_register'),
url(r'^actions/register/$', 'mysite.views.login_register_action'),
url(r'^accounts/register_success/$', 'mysite.views.login_register_success'),
)
urlpatterns += admin_urlpatterns