How to change URLs based on a column data from the Database - python

I tried a lot but I am just not able to reach the exact solution.
I want to change the URLs of the list which is being generated by a for loop in HTML.
Here is my code for that view in views.py file:
class DashboardHomeViewClass(View):
def get(self, request, *args, **kwargs):
device_objects = device_user_data.objects.filter(User_Name = request.user.username)
device_list = []
for device in device_objects:
device_list.append(device.Device_Alias_Data)
context_logged = {'device_list': device_list}
return render(request, "dashboardhometemplate.html", context_logged)
Here is the code where this context is being used in the HTML template:
{%for item in device_list%}
<li> <i class="fa fa-bar-chart"></i><span class="hide-menu">{{item}}</span>
{% endfor %}
Now what I need exactly is: Different links should open on clicking different list view items based on device_Alias_Data.
eg : http://127.0.0.1:8000/dashboard/{{Device_Alias_Data}}
where Device_Alias_Data is character varying field in a table named device_user_data in my database.
Here is my urls.py file :
from django.conf.urls import url
from django.contrib import admin
from dashboardhome.views import DashboardHomeViewClass
from dashboardhome.views import login_view
from django.contrib.auth.views import login
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', login ,{'template_name': 'login_template.html'}),
url(r'^dashboard/$', DashboardHomeViewClass.as_view()),
]

First you should make some tweaks to your urls.py file for this to work:
app_name = "dashboardhome"
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', login ,{'template_name': 'login_template.html'}),
url(r'^dashboard/$', DashboardHomeViewClass.as_view(), name="dashboard"),
]
Here we added app_name and name attribute of the url method, this way we can make use of Django Reverse Resolution of urls
After that you can use template builtin url tag, like this:
{%for item in device_list%}
<li> <i class="fa fa-bar-chart"></i><span class="hide-menu">{{item}}</span>
{% endfor %}
And this gonna result in a url like this:
http://127.0.0.1:8000/dashboard/{{item}}
Make sure to check out the links for more info.
I hope this will help.

can use def get_absolute_url() method in model.py by importing django.url.reverse
and using url name.

Related

Django fails to process get request properly with a misconfiguration in the project’s main urls.py

I’ve got a website I’m writing using Django which is a very basic, rudimentary CMS. For now the feature I am trying to implement involves when a web user enters their fake 12-digit chuckee cheese membership card number, Django should redact the first 8 digits and present it back to the user. All of this takes place on the main landing page with blog post text content.
Here is the urlspatterns variable declared inside my project’s parent urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('redactors.urls')),
path('', include('posts.urls')),
path('', include('counters.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
With that exact urlspatterns, the result is this.
As you can see in that image, when the web user enters their membership card number, on the webpage to the right, the card number (below the green heading elements) renders and is processed as intended (which is at this web address location, http://127.0.0.1:8000/?ccEntry=111111111111. The problem is the landing page (as depicted on the left at http://127.0.0.1:8000/), renders the template with the blog post content missing.
One solution would be to swap the order in which path('', include('redactors.urls')), and path('', include('posts.urls')), as they appear inside urlpatterns list. With that change, the result is this. As you can see in this second image, the blog post content renders with and without the card number entered but then below the green heading element doesn’t process in the webpage to the right, it’s just blank. I’m expecting to see: ‘xxxx xxxx 1111’.
My question is: How do I get the ccEntry get request to process so that the blog post content text is rendered when the user lands on the home page and when the web user enters their 12-digit card number?
It's also worth noting that I'm not getting a trace back and my server is not crashing so I don't have many leads in terms of searching on Google for other developers resolving similar or related issues.
Here are the views, the template and the urls.py in play.
Main project urls.py:
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('redactors.urls')),
path('', include('posts.urls')),
path('', include('counters.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Take note of the positioning of path('', include('redactors.urls')), and path('', include('posts.urls')), When I the two positions, I get a different result but still does not achieve my goal (as described above).
redactors.views:
from django.shortcuts import render
from posts.models import Posts
def home(request):
if 'ccEntry' in request.GET:
number = request.GET['ccEntry']
redacted_num = 'xxxx xxxx {}'.format(number[-4:])
posts = Posts.objects.all().order_by('-pub_date')
# context = {'posts':posts}
return render(request, 'alls/landings.html', {'number':number, 'redacted_num':redacted_num, 'posts':posts, })
else:
return render(request, 'alls/landings.html')
posts.views:
from django.shortcuts import redirect, render, get_object_or_404
from posts.models import Posts
def posts(request):
posts = Posts.objects.all().order_by('-pub_date')
context = {'posts':posts}
return render(request, 'alls/landings.html', context)
templates/alls.html:
<div class="card-processor">
<h3>Enter your fake Chuckee Cheese Neptune membership card number!</h3>
<form action="{% url 'home' %}" method="get">
<div>
<label for="password">Enter Card Number:</label>
<input type="text" id="password" name="ccEntry" pattern="[0-9]{12}" maxlength="12"/>
<div class="requirements">Must be a 12 digit number and no letters. </div>
<input type="submit" value="Redact!" class="button"/>
</div>
</form>
<h1>Here is your fake Chuckee Cheese Neptune membership card number!</h1>
<h3 style="color:lime">This was the original number that you entered:</h3>
<div class="field">{{ number }}</div>
<h3 style="color:lime">Here it is redacted:</h3>
<div class="field">{{ redacted_num }}</div>
<div class="field"><strong>Again? Click here!</strong></div>
</div> <!--- END card-processor -->
<div class="post-content">
{% for post in posts %}
<h1> Blog post title: <em>{{ post.title }}</strong></em>
<h4>Publication Date: {{ post.pub_date_preference }}</h4>
<img src="{{ post.image.url }}" class="authors-pic" />
<!-- Body text should go here : -->
<p>{{ post.body|safe }}</p>
{% endfor %}
The above three files I think is where my problem is. But in case you people need to explore some of my other project files, here is a static snapshot (tagged as v0.9.0) of the full source code repo on my GitHub.
Strange: Moments ago I merged my redactors branch into master. There were two minor merge conflicts.
My urlpatterns list variable inside my redactor app's urls.py used to look like this:
urlpatterns = [
path('', views.home, name='home'),
]
Basically, when I passed in 'home'` to the first path argument like this:
urlpatterns = [
path('home', views.home, name='home'),
]
...everything seems to run as intended. The blog post content is present with or without form input and the POST request processes as expected. Hooray!

how to format a a url to return something like this "product/4/improved-led-lamp" in the template

I'm trying to return a formatted url that will look like this "edit-book/4/improved-led-lamp" using the {% url %} tag
I've tried {% url 'dashboard:editbook' 4 slug %}
here is the root url.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('home.urls')),
path('dashboard/', include('dashboard.urls')),
path('admin/', admin.site.urls),
]
here is my dashboard app's urls,py
from django.urls import path
from . import views
app_name = 'dashboard'
urlpatterns = [
path('edit-book/<int:id>/<slug:title>', views.BookView.as_view(), name='editbook'),
]
if I visit "edit-book/4/improved-led-lamp" in my browser, it resolves, but when I try to reproduce this in the view using {% url %} tag, it throws noReverseMatch error
this is the error
screenshot of error
Your syntax looks correct and if slug variable consists of slug ([-a-zA-Z0-9_]+) it should be working.
Look into contents of slug. Error screenshot shows that it's an empty string.

Reverse {% url %}: Reverse for '"' not found. '' is not a valid view function or pattern name

I've been stuck on this for a while, can't seem to fix the error. I do not use reverse() anywhere in the view.
urls.py
urlpatterns = [
url(r"^book/", include("bookings.urls")),
]
bookings.urls.py
from django.conf.urls import url
from . import views
app_name = 'bookings'
urlpatterns = [
url(r'^charge/$', views.charge, name='charge'),
url(r'^booking/$', views.booking, name='booking'),
]
views.py
def booking(request):
# some code
render(request, 'bookings/template.html', {'listing': listing,})
def charge(request):
# some code
template.html
<form action="{% url 'bookings:charge' %}" method="post">
I tried all different alterations and namespaces, e.g. trying to use just charge, different namespaces in urls.py etc.
When I render the book/booking/, I get the following error:
Reverse for 'charge' not found. 'charge' is not a valid view function
or pattern name.
If you want to use URL tag on that way, you need a namespace in your urls.py.
url(r"^book/", include("bookings.urls", namespace="bookings")),
Then you can have {% url 'bookings:charge' %} in your template.

Getting NoReverseMatch Error

I have an app that is going to display some information about people in my group. I'm getting a NoReverseMatch error when trying to use the url tag in my index.html. If I do not use the url tag, but specify the root, I do not receive the error.
The error says:
NoReverseMatch at /
Reverse for 'specialist' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$(?P[0-9]+)/']
Here is are the urls.py files.
From the main wi_tech urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('person.urls')),
url(r'^tech/', include('person.urls')),
url(r'^admin/', admin.site.urls),
]
From the 'person' app urls.py:
from django.conf.urls import url
from . import views
app_name = 'person'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='specialist'),
]
My views.py file looks like this:
from django.views import generic
from .models import Specialist
class IndexView(generic.ListView):
template_name = 'person/index.html'
context_object_name = 'person_list'
def get_queryset(self):
"""Return all specialists"""
return Specialist.objects.order_by('id')
class DetailView(generic.DetailView):
model = Specialist
template_name = 'person/detail.html'
And my index.html page looks like this:
{% if person_list %}
<ul>
{% for specialist in person_list %}
<li> {{ specialist }}</li>
{% endfor %}
</ul>
{% else %}
<p>No specialists are available.</p>
{% endif %}
If I change my tag in index.html to this, it works:
<li> {{ specialist }}</li>
Obviously this isn't an ideal situation in case the web root ever changes. I've reviewed a lot of SO questions on this, and nothing seems to match. I think the issue is the "$" in the beginning of the regex, but I don't see where that's coming from.
Specifically, I used this link as a really good reference point, but came up empty looking through my code.
what is NoReverseMatch and how do i fix it
Clearly there's something I'm missing.
Could it be the additional / at the end of the URL?
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='specialist')
The one after your primary key modifier. When you click the URL (with the (% url ':' model.name %)) what URL comes up in your browser?
I ended up scrapping this implementation, and going with a flatter structure whereby all models, views and templates are in the same application. I have not had this problem in the new design.

python Django repeat url many times

I'm a starter of Django1.10. I just started play around with it. I am trying to show an image on website.
This is myproject/settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and myproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^poster/', include('poster.urls')),
url(r'^admin/', admin.site.urls ),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
myproject/app/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Info
# give a set of summary of items
def index(request):
latest_item_list = Info.objects.all()
context = {'latest_item_list': latest_item_list}
return render(request, 'poster/index.html', context)
def detail(request, item_id):
return HttpResponse("This function will return detail info for items %s" % item_id)
myproject/app/models.py
from django.db import models
class Info(models.Model):
def __str__(self):
return self.info_text
info_text = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
info_image = models.ImageField(upload_to='images/%Y%m/%d')
myproject/app/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# ex:/poster
url(r'^$', views.index, name='index'),
# ex: /poster/5
url(r'^(?P<item_id>[0-9]+)/$', views.detail, name = 'detail'),
]
myproject/app/templates/app/index.html
{% if latest_item_list %}
<ul>
{% for item in latest_item_list %}
{{forloop.counter}}.{{ item.info_text }}
{% endfor %}
</ul>
{% else %}
<p>No poster are available.</p>
{% endif %}
If I run python manage.py runserver, and go http://127.0.0.1:8000/poster/. I can see one object I created before, when I click it, the url it points to get repeated many times
I believe there is something wrong in the url.py, but I am not sure. Can someone help?
First of all I think you are missing a forwardshals in your models.py on line :
info_image = models.ImageField(upload_to='images/%Y%m/%d')
Unless it's your intention, I think it should be like this:
info_image = models.ImageField(upload_to='images/%Y/%m/%d')
^
Next thing is that you are not providing the right url for href attribute in the <a> tag of your index.html template.
{{forloop.counter}}.{{ item.info_text }}
This line will point to the image itself. So you can use it example in the <image src="{{ item.info_image.url }}" /> but not in a link tag. So I guess this is what you were looking for.
To point to your detail view of specific image you would want to ideally create get_absolute_url method on your Info model class.
Model.get_absolute_url()
Define a get_absolute_url() method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP.
For example:
# models.py
class Info(models.Model):
...
info_image = models.ImageField(upload_to='images/%Y%m/%d')
def get_absolute_url(self):
return reverse('detail',
args=[self.id])
Then you could use that in your template like this:
{{forloop.counter}}.{{ item.info_text }}
and display your image, wherever you want, using:
<image src="{{ item.info_image.url }}" />
Have you checked how the URL looks in the generated HTML code? E.g. does the URL look correct when the HTML is loaded, and when you click it, it starts repeating it?

Categories