Dynamic URL routing is not working in django web application - html

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.

Related

url routing in django?

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.

Getting Django CSRF error with raw html form

I'm trying to set up a raw html form where a user can make a suggestion and then save it on a database with a POST method, but I keep getting a Forbidden (403) CSRF verification failed. Request aborted. even after following the steps in the Help section.
I have found that I don't get the error if I add csrf_exempt on top of my view like this:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def suggest_ptags(request):
context = {}
print("Form is submitted.")
return render(request, "partials/search_form.html", context)
But I was made aware that It removes completly the CSRF protection and I don't want that.
So what should I do?
Here's my search_form.html form in a partials folder in templates:
<!-- Suggestion Form in popup -->
<div class="prop-modal">
<div class="prop-content">
<a class="btn-close-prop">×</a>
<img src="{% static 'images/pyramids.svg' %}">
<form action="/suggest_ptags/" class="feedback-form" method="POST" enctype="text/plain">
{% csrf_token %}
<h5 class="title-prop">Suggestion</h5>
<input class="input-prop" name="suggest" rows="3" cols="37" placeholder="suggest something..."></input>
<input class="button-prop" type="submit" value="Envoyez"></input>
</form>
</div>
</div>
My current Views.py:
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
def suggest_ptags(request):
context = {}
print("Form is submitted.")
return render(request, "partials/search_form.html", context)
And in my Urls:
from django.conf.urls import url
from django.contrib import admin
from search.views import HomeView, ProductView, FacetedSearchView, autocomplete, suggest_ptags
from .settings import MEDIA_ROOT, MEDIA_URL
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', HomeView.as_view(), name='home'),
url(r'^admin/', admin.site.urls),
url(r'^suggest_ptags/$', suggest_ptags, name='suggest_ptags'), #Suggestions
url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'),
url(r'^search/autocomplete/$', autocomplete),
url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),
] + static(MEDIA_URL, document_root=MEDIA_ROOT)
Any solutions?
You shouldn't use enctype="text/plain". You can remove it (which is the same as enctype="multipart/form-data"), or use enctype="multipart/form-data" if you are uploading files.

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 : HTML form action directing to view (or url?) with 2 arguments

Started learning django about a week ago and ran into a wall. Would really appreciate any enlightenment...
models.py
class data(models.Model):
course = models.CharField(max_length = 250)
def __str__(self):
return self.course
html
Converted the objects in models.course to schlist
<link rel="stylesheet" type="text/css" href="{% static '/chosen/chosen.css' %}" />
<form action={% views.process %} method="GET">
<div>
<h4 style="font-family:verdana;">First Course: </h4>
<select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
<option value=""></option>
{% for item in schlist %}
<option> {{ item }} </option>
{% endfor %}
</select>
</div>
</br>
<div>
<h4 style="font-family:verdana;">Second Course:</h4>
<select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
<option value=""></option>
{% for item in schlist %}
<option> {{ item }} </option>
{% endfor %}
</select>
</div>
</br>
<input type="submit" value="Compare!" />
</form>
urls.py (having my doubts if this works..)
urlpatterns = [
url(r'^(\d+)/(\d+)$',views.process, name = 'process'),
]
view.py
def process(request,q1 ,q2):
obj1= get_object_or_404(Schdata, course = q1)
obj2= get_object_or_404(Schdata, course = q2)
........
Was wondering if it is possible for the form action to direct the action to
(1) view.py or (2) url.py (and eventually to a view.py) with 2 arguments selected?
If so how should the form action be? {{view ?}} or {{url ?}}. Am I missing out the definition of my arguments in my HTML?
Directing to views.py:
User input is CharField, could use get_object_or_404 to get the model pk. However when defining my urls.py I would get a Noreverse error as my url arguments is the primary key.
Directing to urls.py:
Url arguments is primary key. From the way I see it, I need to magically convert my User input Charfield to a pk before passing it to urls.py
Is there a (or) function for get() in django? E.g get_object_or_404(pk = q1 or course = q1)?
Would really appreciate any advice. Been staring at this for hours.
You are trying to use the reverse resolution of urls in Django.
In your html file correct form action url to the following and method should be POST:
<form action={% url 'process' %} method="POST">
In case you are trying to pass parameters along then use this:
<form action={% url 'process' request.user.id 4 %} method="POST">
Reference:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Yes i'm late but it can help others for better understanding how Django processes the request.
Django 3.0 pattern
How Django processes the request
Basic :
First Django check the matching URL.
If URL is matched then calling the defined view to process the request. (Success)
If URL not matched/found the Django invokes error Page Not Found
In detail reading :
Official Django Documentations How Django processes a request
These are your URL patterns :
urlpatterns = [ path('profile/edit/<int:pk>/',views.editprofile, name='editprofile'),]
Third argument in urlpatterns is for if you want to change the url pattern from current to this :
urlpatterns = [ url('profile/edit/user/id/<int:pk>',views.editprofile, name = 'editprofile'),]
You don't need to redefine url pattern in all Templates where you using url name.
For Example :
This is my template profile.html where i used the url name instead of hard coded url.
<a class="item" href="{% url 'editprofile' user.id %}" >Edit profile </a>
Solution of your problem :
.html
Only use url name instead of hard coded url in your templates and pass arguments.
<form action={% process no_of_arguments %} method="POST">
views.py
Here you can process your request
def process(request,no_of_arguments):
Become good django developer
You can also use Django ModelForms for your model.
Using model forms or simple form you can do multiple things
Modular approach
Write server side validation in related form instead of doing in views.py
Readable code - Clean code

Django URL mapping for different apps

Im trying to link a button in HTML to another html in my project folder for my django project. Lets say its
MyApp
-Polls
-templates
-index
-Votes
-templates
-main
-truths
-rigged
I have a a button on main that uses rigged and truths so in main it has this button
<form action="{% url 'Votes:rigged' %}">
<input type="submit" value="rigged votes" />
</form>
now i want to add another button that would link polls->index into it. Is there a way to do that without copying everything from Polls into the folder Votes?
UPDATE*
main.html
<form action="{% url 'Polls:Index' %}">
<input type="submit" value="Index" />
</form>
Polls.url
urlpatterns=[
url(r'^Index/', Index.as_view(), name="Index"),
]
Index.views
class IndexView(TemplateView):
# template location
template_name = "Polls/Index.html"
# post logic must be defined
def post(self, request, *args, **kwargs):
return redirect(reverse_lazy("Polls:Index"))
Please refer to https://docs.djangoproject.com/en/1.10/topics/http/urls/#url-namespaces
Please understand how the namespaces and named urls work. You should have a urls.py file in your 'MyApp' folder where other files like 'settings.py' and 'wigs.py' are there.
For referring to an url by namespaces you need to first register the namespace associated with url.py of your Polls app. Example from the documentation:
from django.conf.urls import include, url
urlpatterns = [
url(r'^polls/', include('polls.urls', namespace='Polls')),
]
Furthermore you must also name your url in 'polls.urls' like
url(r'^index/$', Whatever_view,name='index'),
then you can call the url as "Polls:index"