Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get sheet names from excel file before uploading file to Django python using angular 5?
I am using angular 5 as frontend and Django python as backend.I want sheet names from excel file when file is selected without sending to Django.I want these sheet names should be displayed on UI as list so that user is allowed to select sheet from it. Once user select sheet , I want to send selected sheet name and actual file to Django for further processing(i.e. storing file in database and using sheet name to get data from sheet). Kindly help. -
Suppress line breaks after each templatetag in django
I searched around, but didn't find a nice way to solve this issue so far, so hoping you can help. I am using django template language for all my plaintext emails and it is very inconvenient that each templatetag renders with an additional line break. While it allows me to have nicely formatted templates the rendered text contains multiple newlines which I am not being able to control unless I make my template ugly by removing the new lines after the templatetags. Please note that I am using it for text rendering, and any "spaceless" will not work here. My last resort is to manually read the templates into string, do a regex stripping of new lines before passing it to rendering so I enjoy the both worlds, but I wonder if someone has a better idea. Example: {%load i18n%} {%with name=something.somethingelse.name%} Hello {{name}}, {%endwith%} The output will ne: <line break> <line break> Hello Someone, -
Using django with legacy database with another backand
I have a legacy database working with some backend. My task is to make new one using django. And there are some problems: 1.Django creates some system tables in legacy database, what is not allowed. 2.Django auth is not compatible with current users table structure. Ways I'm thinking to solve this problems: Force django to use separate database to store its system information. Some how using this. There is 2 ways I'm concidering: a) Try to write some User model that will be compatible with database, but there are some problems: AbstractBaseUser has a default attribute password (which is represents as database column password), but legacy database uses column password_hash. b) To store django-apropriate user table in separate database and link one-to-one with legacy user table. It promises a lot of crutches in future and forther more what I'm gonna do with some new users that may be added via other backend? So, I'm stuck. -
Why is SECURE_SSL_REDIRECT always getting set to True?
I currently have a local .env file which contains parameters for my local environment. I have a Django App hosted on Heroku where I assign my config variables. I figured using python-decouple's .env file to set SECURE_SSL_REDIRECT=False and then in my settings.py use SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT') would work. However, no matter the case, if Django sees SECURE_SSL_REDIRECT = True ANYWHERE, it tries to load as HTTPS and my god is it frustrating. -
Django variable handling-why does this work?
I'm pretty new to django and came across something that confuses me in this views.py file I've created. I just played around with it a little and came up with something that works, but I don't get why it does. The class Draft_Order (which I have in another file) requests the NBA stats page, performs some calculations on the backend, and spits out draft lottery odds (for the new draft). The methods initialize, sim draft, and get standings all do things on the backend (which works perfectly). Now, my question is that I don't get why I can create an instance "f" of the class DraftOrder outside all of the functions, but yet still be able to reference it within most of my functions as they are getting called from my urls.py file, so it doesnt seem like they should be working at all. Also, for some reason, the update function can only reference "f" if I don't have an assignment to f in the function-e.g. if I add the line f = temp Then all of a sudden it gives me an "unboundlocalerror", and says that f is referenced before assignment. I'd appreciate any help on this. Thanks. from β¦ -
Best practice when updating Django model fields? Is this what manager classes are for?
I am very new to Django and I am wondering what the best practice is for updating a field. Here is my model: class Website(models.Model): id = models.AutoField(primary_key=True) url = models.TextField() is_awesome = models.BooleanField(default=False) Right now I have a separate helper file, WebsiteHelper.py, with many other functions not related to the database in it, but also this function for updating a specific field in the DB: def __mark_needs_redone(Website): Website.update(is_awesome=True) Is there a cleaner place for functions such as these to live, such as: class WebsiteManager(models.Manager) #Execute function here Is this how managers are supposed to be used? If not, what is the best practice here? -
Errno 10053οΌ An established connection was aborted by the software in your host machine
I use django 1.11.14οΌ python2.7 and win7 I have finished writting a webοΌ when I tried to publish it in the our LAN, other people can not log in to the web I got the error in cmdοΌErrno 10053οΌ An established connection was aborted by the software in your host machine due to other projectsοΌ I can not change to python3οΌ and I have to publish it to our LAN using my own computer as a server. HOW TO FIX THAT? THANKS! -
Using font-awesome in python django application
I'm trying to load a local copy of font awesome icons in my python django app. My template base.html contains: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="{% static " /appointments/css/all.css " %}" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous"> <title>{% block title %}Hello, world!{% endblock %}</title> </head> as adapted from https://docs.djangoproject.com/en/2.0/howto/static-files/ The directory structure of my app is: joel@hp:~/myappointments$ tree . βββ appointments β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ static β β βββ appointments β β βββ css β β β βββ all.css β β βββ webfonts β βββ templates β β βββ appointments β β βββ base.html β β βββ createappointment.html β β βββ doctor.html β β βββ doctors.html β β βββ home.html β β βββ index.html β β βββ navbar.html β β βββ patient.html β β βββ patients.html β βββ tests.py β βββ urls.py β βββ using shell.txt β βββ views.py βββ appointments.ipynb βββ db.sqlite3 βββ manage.py βββ myappointments β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py However these icons are not being β¦ -
search function works but doesn't display data
I am trying to have search function in my page. i followed the django document and coding codingentrepreneurs site for that and followed that guide given in that. But my search function doesn't display any data. I am using django 1.11 and python 2.7.10. Could some one help me fixing it! Thanks in advance. common urls.py from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.contrib.auth.views import LoginView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^login/$', LoginView.as_view(), name='login'), url(r'^u/', include('profiles.urls', namespace='profiles')), url(r'^items/', include('menus.urls', namespace='menus')), url(r'^restaurants/', include('restaurants.urls', namespace='restaurants')), url(r'^about/$', TemplateView.as_view(template_name='about.html'), name='about'), url(r'^contact/$', TemplateView.as_view(template_name='contact.html'), name='contact'), ] RESTAURANTS APP model.py from django.conf import settings from django.db import models from django.db.models import Q from django.db.models.signals import pre_save, post_save from django.core.urlresolvers import reverse from .utils import unique_slug_generator from .validators import validate_category User = settings.AUTH_USER_MODEL class RestaurantLocationQuerySet(models.query.QuerySet): def search(self, query): if query: query = query.strip() return self.filter( Q(name__icontains=query)| Q(location__icontains=query)| Q(location__iexact=query)| Q(category__icontains=query)| Q(category__iexact=query)| Q(item__name__icontains=query)| Q(item__contents__icontains=query) ).distinct() return self class RestaurantLocationManager(models.Manager): def get_queryset(self): return RestaurantLocationQuerySet(self.model, using=self._db) def search(self, query): #RestaurantLocation.objects.search() return self.get_queryset().search(query) class RestaurantLocation(models.Model): owner = models.ForeignKey(User) name = models.CharField(max_length=200) location = models.CharField(max_length=200) category = models.CharField(max_length=200) slug = models.SlugField(null=True, blank=True) objects = RestaurantLocationManager() def __str__(self): return self.name def get_absolute_url(self): return reverse('restaurants:detail', kwargs={'slug': β¦ -
Django how to set custom properties for a ModelForm
I have a forms.ModelForm 'CreateUserForm'. I want to set a property for each form field to be later used in the template. In this case, I want to set a icon name to specify which icon name should be used for each field. class CreateUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) icon_names = ['person', 'email', 'enhanced_encryption'] class Meta: model = User fields = ['username', 'email', 'password'] I've had trouble iterating over both the field AND the field's property 'icon_names'. I can't really zip() without losing functionality. Currently I've hacked together iteration by using the 'forloop.parentloop.counter' {% for field in form %} <div class="form-group"> <div class="input-field"> <i class="icons"> {% for icon in form.icon_names %} {% if forloop.parentloop.counter == forloop.counter %} {{ icon }} {% endif %} {% endfor %} </i> <input type="text" id="autocomplete-input" class="autocomplete"> <label class="control-label" for="autocomplete-input">{{ field.label_tag }}</label> </div> </div> {% endfor %} Which produces the intended result, but it seems redundant, especially if I wanted to add another field property in the future. What's the proper way to do this? -
Django: Can't figure out how to get each form data out unique
I am building an ordering system in python using django. I have an formset which emails the inserted user input. When I call the {{form data}} in my html template, the variables repeat whatever the last form data is. Have been stuck on this for a couple days and haven't found a way to do this without using database models. This is my code: Views.py def order(request): extra_forms = 1 order_formset = formset_factory(order_form, extra=extra_forms) if request.method == 'POST': if 'additems' in request.POST and request.POST['additems'] == 'true': formset_dictionary_copy = request.POST.copy() formset_dictionary_copy['form-TOTAL_FORMS'] = int(formset_dictionary_copy['form-TOTAL_FORMS']) + extra_forms formset = order_formset(formset_dictionary_copy) else: formset = order_formset(request.POST) if formset.is_valid(): for form in formset: #Clean Form Data cleaned_quanity = form.cleaned_data['quanity'] cleaned_pack = form.cleaned_data['pack'] cleaned_grade = form.cleaned_data['grade'] cleaned_size = form.cleaned_data['size'] cleaned_variety = form.cleaned_data['variety'] cleaned_loading_date = form.cleaned_data['loading_date'] cleaned_notes = form.cleaned_data['notes'] #Convert Cleaned Data to Int int_pack = int(cleaned_pack) int_grade = int(cleaned_grade) int_variety = int(cleaned_variety) #Logic for choice options if int_pack == 1: int_pack = 'Carton' elif int_pack == 2: int_pack = '12/3# Bags' elif int_pack == 3: int_pack = '10/4# Bags' else: int_pack = '6/8# Bags' if int_grade == 1: int_grade = 'Standard' elif int_grade == 2: int_grade = 'Choice' else: int_grade = 'Fancy' if int_variety == 1: int_variety β¦ -
POST http://127.0.0.1:8000/api/checks 403 (Forbidden)
I have an application that uses angular 6 as front framework & Django on backend. When I use get request everything is ok, but whenever I want to use post I face 403 forbidden error. Tried to use headers={'Access-Control-Allow-Origin': '*' on Django but it didn't work any good. Here's my code: Check.service.ts: editCheck(check: Check):Observable<any> { return this.http.post(this.checksUrl, check,httpOptions) } check-edit.component.ts: goBack():void{ this.location.back(); } editCheck(): void { this.checksService.editCheck(this.check) .subscribe(() =>this.goBack()) } editCheck is called at check-edit.component.html: <button mat-button (click)="editCheck()" >Save</button> And here is what the error looks like: polyfills.js:1 POST http://127.0.0.1:8000/api/checks 403 (Forbidden) main.js:1 ERROR e {headers: t, status: 403, statusText: "Forbidden", url: "http://127.0.0.1:8000/api/checks", ok: false, β¦} -
Django - Allauth default email is bad
I am using Allauth to handle the authentication happening on my website. And I am also using Mailgun for sending mail, connecting to it via SMTP. Now, in production, whenever I register a new account an confirmation mail is sent to me (per default via allauth). However, to my dismay the mail I got it from is extremely ugly (see picture below). Is there a way to resolve this? -
Loading multiple forms in a single template while passing instances to each form
I am creating a survey app where users can fill out surveys on other users. As part of this, I want to allow users to fill out surveys for multiple users in one Formset. For this, there are 2 instance variables I want to set that are required for the model, but should not be set by the user for the form. These are reporter and user (the subject of the survey). I am trying to figure out how to do this, but haven't used Formsets enough (i.e. at all) to quite figure this out. I've also found this a bit tricky because I have 2 different models in play here. 1st (Surveys) is where the survey results are stored, 2nd (SurveysQueue) is where the information regarding survey queues are stored (i.e. user with their list of users in a ManyToManyField for the queue). My code is below: forms.py Note that the Surveys model also has the 2 additional hidden fields, user and reporter class SurveyForm(forms.ModelForm): description = forms.CharField( label='Description', required=False,) score = forms.ChoiceField(choices=choices, widget=forms.RadioSelect(attrs={'class': 'radiolist inline'}),) class Meta: model = Surveys fields = ('reason', 'score') views.py class MultiUserSurvey(View): UserSurveyFormSet = modelformset_factory(Surveys, form=SurveyForm) template_name = "surveys/survey.html" def get(self, request, *args, β¦ -
How to deploy Django (via Anaconda) to Heroku with django_heroku
I am trying to deploy my first Django application to Heroku. I'm using anaconda for python, and following Deploying Python from Heroku, and the recommendation is to use django_heroku package. I cannot find this package and get the following message when using: conda install django_heroku. Does anyone know where this package is? Is this necessary, or is there another way? PackagesNotFoundError: The following packages are not available from current channels: - django_heroku Current channels: - https://repo.anaconda.com/pkgs/main/win-64 - https://repo.anaconda.com/pkgs/main/noarch - https://repo.anaconda.com/pkgs/free/win-64 - https://repo.anaconda.com/pkgs/free/noarch - https://repo.anaconda.com/pkgs/r/win-64 - https://repo.anaconda.com/pkgs/r/noarch - https://repo.anaconda.com/pkgs/pro/win-64 - https://repo.anaconda.com/pkgs/pro/noarch - https://repo.anaconda.com/pkgs/msys2/win-64 - https://repo.anaconda.com/pkgs/msys2/noarch - https://conda.anaconda.org/conda-forge/win-64 - https://conda.anaconda.org/conda-forge/noarch To search for alternate channels that may provide the conda package you're looking for, navigate to https://anaconda.org and use the search bar at the top of the page. -
Creating a beginners app using Django/Python: ModuleNotFoundError: No module named 'pages'
I'm new to Django and am trying to create a very simple app off of a tutorial I found online. Working on a mac Django Version 2.0.7 Python 3.7.0 My file structure: helloworld ......venv ..........(other files) ......helloworld_project ..........(other files) ......manage.py ......pages .........._ pycache _ ..............otherfiles ..........admin.py ..........apps.py ..........migrations ..............(other files) ..........models.py ..........tests.py ..........urls.py ..........views.py The problem: when I run my urls.py file, I get the following message: Traceback (most recent call last): File "/Users/Bethany/Desktop/helloworld/pages/urls.py", line 3, in <module> from pages import views ModuleNotFoundError: No module named 'pages' My urls.py file: # pages/urls.py from django.urls import path from pages import views urlpatterns = [ path('', views.homePageView, name='home') ] I've tried replacing "from pages import views" with "from . import views" and get the same message. I've looked through a few similar questions on stack overflow, but haven't had success with finding a solution to fix my issue. does anyone have any suggestions? Thanks! If needed, this is the tutorial I'm following: https://djangoforbeginners.com/hello-world/ -
django how to pass parameter from url to view
I'm trying to append a parameter no_rep at the end of my question url as a signal to show different views. This is the url.py: url( r'^%s(?P<id>\d+)/' % QUESTION_PAGE_BASE_URL.strip('/') + r'(%s)?' % r'(?P<no_rep>\w+)', views.readers.question, name='question' ), I'm trying to show different displays depending on the value of no_rep in my url. This is the view: def question(request, id, no_rep): if no_rep == '1': request.session['no_rep'] = True else: request.session['no_rep'] = False I couldn't find information on what the +,%,? do, which is probably where the problem is. Could someone explain how the regex work with the base url? When I enter the url http://localhost:8000/question6/test-question/no_rep:1, request.session['no_rep'] should be set to true, but it's not. What am I missing? -
Performing operations on Django Querysets
I have very large Querysets with the following general form: ( {id: x} {termVector: [ '.00035 .00052...' ]} ) If I want to convert the termVectors from a string to a list of floats, is there a standard way of doing that? I've been using the .values() method and iterating through the resulting dict, but it seems to be pretty computationally heavy given the size of the querysets. I feel like there must be a better way but I can't seem to find any way of doing it in the documentation. -
Django: unhashable type:'list' error
I am working on Django 2 projects. I have an error that I have not encountered before. HTML Page: <body> <h1>Postlar burada gΓΆrΓΌntΓΌleniyor</h1> <a href="{% url 'postlar:post_olustur' %}">Post OluΕtur</a> {% for post in listelenen_postlar %} <br> <a href="{% url 'postlar:post_detay' post.id %}">{{post.baΕlΔ±k}}</a> <br> {{post.iΓ§erik}} <br> {{post.olusturma_zamanΔ±}}/////////////////{{post.olusturma_zamanΔ±|timesince}} ago <br> {{post.gΓΌncelleme_zamanΔ±}} <br> {% endfor %} Views.py def post_listele(request): listelenen_postlar = Post.objects.all() context ={"listelenen_postlar":listelenen_postlar} return render(request,"postlar/post_listele.html",context) urls.py in my app: urlpatterns = [ url(r'^$',view=post_listele, name="post_listele"), url(r'^post_olustur/$',view=post_olustur, name='post_olustur'), url(r'^post_detay/(?P<id>[0-9]+)$',view=post_detay, name='post_detay'),] TypeError at /postlar/ unhashable type: 'list' Request Method: GET Request URL: http://127.0.0.1:8000/postlar/ Django Version: 2.0.7 Exception Type: TypeError Exception Value: unhashable type: 'list' Exception Location: C:\Users\mete\Desktop\blog_deneme\venv\lib\site-packages\django\db\models\sql\compiler.py in get_order_by, line 290 Python Executable: C:\Users\mete\Desktop\blog_deneme\venv\Scripts\python.exe Python Version: 3.6.4 Python Path: ['C:\Users\mete\Desktop\blog_deneme\blog', 'C:\Users\mete\Desktop\blog_deneme\venv\Scripts\python36.zip', 'C:\Users\mete\Desktop\blog_deneme\venv\DLLs', 'C:\Users\mete\Desktop\blog_deneme\venv\lib', 'C:\Users\mete\Desktop\blog_deneme\venv\Scripts', 'c:\python\Lib', 'c:\python\DLLs', 'C:\Users\mete\Desktop\blog_deneme\venv', 'C:\Users\mete\Desktop\blog_deneme\venv\lib\site-packages'] Server time: Mon, 30 Jul 2018 22:50:33 +0000 Thank you..enter image description here -
Passing specific instances to forms in Formset
I am creating a survey app where users can fill out surveys on other users. As part of this, I want to allow users to fill out surveys for multiple users in one Formset. For this, there are 2 instance variables I want to set that are required for the model, but should not be set by the user for the form. These are reporter and user (the subject of the survey). I am trying to figure out how to do this, but haven't used Formsets enough (i.e. at all) to quite figure this out. My code is below: forms.py # Note that the Surveys model also has the 2 additional hidden fields, user and reporter class SurveyForm(forms.ModelForm): description = forms.CharField( label='Description', required=False,) score = forms.ChoiceField(choices=choices, widget=forms.RadioSelect(attrs={'class': 'radiolist inline'}),) class Meta: model = Surveys fields = ('reason', 'score') views.py def multi_survey(request): user = get_object_or_404(User, user=request.user) queue_exists = UserSurveyQueue.objects.filter(user=user) if not queue_exists: raise Http404 queue = queue_exists.get(user=user).queue.all() # This returns a list of user_ids that should be included in forms within the formset in the user field (1 per form). survey_users = [user['user'] for user in queue.values('user')] UserSurveyFormSet = formset_factory(SurveyForm) # I was planning to use the below list to loop β¦ -
What is the proper way to handle custom exceptions in Python?
According to what I've read EAFP (Easier to Ask for Forgiveness than Permission) is an accepted coding style in Python, actually recommended in many cases. My question is about when that becomes too much with custom exceptions. Imagine we have a web application for a dog hotel with the following structure: - controllers -- dogs.py (Receives REST requests) - services -- dogs.py (Connects to a DB and a third party API to retrieve dog breed information) -- validator.py Now three requests examples: Someone wants to create a new dog, but gives invalid information. So the validator has a is_valid_dog method that returns False. Someone makes a GET request to retrieve information about a certain dog that does not exist. The dogs service hits the database but nothing is found. The user wants dog breed information, the service hits the third party API but it's down (500 status obtained). What is the best way to handle that type of flow? In the first case, should I raise an exception when the is_valid_dog returns a False? or return None/False to the controller so it can map it to the 400 status code? Should I return None so the controller maps the return β¦ -
java script doesn't work in my django project
recently I add a new template to my my django project and the html and css load properly but my java script and jquery doesn't executed at all. this are my codes : //jQuery time var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties which we will animate var animating; //flag to prevent quick multi-click glitches $(".next").click(function(){ if(animating) return false; animating = true; current_fs = $(this).parent(); next_fs = $(this).parent().next(); //activate next step on progressbar using the index of next_fs $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active"); //show the next fieldset next_fs.show(); //hide the current fieldset with style current_fs.animate({opacity: 0}, { step: function(now, mx) { //as the opacity of current_fs reduces to 0 - stored in "now" //1. scale current_fs down to 80% scale = 1 - (1 - now) * 0.2; //2. bring next_fs from the right(50%) left = (now * 50)+"%"; //3. increase opacity of next_fs to 1 as it moves in opacity = 1 - now; current_fs.css({ 'transform': 'scale('+scale+')', 'position': 'absolute' }); next_fs.css({'left': left, 'opacity': opacity}); }, duration: 800, complete: function(){ current_fs.hide(); animating = false; }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); }); $(".previous").click(function(){ if(animating) return false; animating = true; current_fs = $(this).parent(); previous_fs = $(this).parent().prev(); //de-activate β¦ -
How build efficient server app in python to grab data from external API?
What framework and tools choose to build efficient web server app, assump that has to grab data from third party APIs -
Location of files specified within Django url patterns
I have been tasked to upgrade some very old code made in Django 1.0. I am not the admin on the server and my company's IT department is not always helpful when it comes to linux, so I have to fix this myself. The code has the following lines in it: # Service Views linked URLs urlpatterns += patterns('myservicename.views.service', url(r'^apptopleveldirectory/servicesdirectory/(?P<datatype>\w+)_transporter.php$', 'service', name="service")) I have changed the names of the variables, but the file *_transporter.php is not under the /var/www/ directory. I have tried to find it recursively, both as a file and as a symlink. However, if I make a call to it in the browser, e.g. www.myservicename.com/apptopleveldirectory/servicesdirectory/json_transporter.php ... it returns a 200 status message, which should be the case when the file has received the call successfully. I want to understand what's happening here and if there's any other place than the web root where the URL pattern files should be placed. -
Page not found (404) Django. Defining url addresses
I'm doing this tutorial. Unfortunately, it is for a different version of Django (I use the latest version). I found a small problem with error 404, but I have no idea how to solve it. I am asking for help in solving it. Error when I started my page 'http://127.0.0.1:8000/reviews/': Using the URLconf defined in winerama.urls, Django tried these URL patterns, in this order: ^$ [name='review_list'] ^review/(?P<review_id>[0-9]+)/$ [name='review_detail'] ^wine$ [name='wine_list'] ^wine/(?P<wine_id>[0-9]+)/$ [name='wine_detail'] admin/ The current path, reviews/, didn't match any of these. My views.py (app) from django.shortcuts import get_object_or_404, render from .models import Review, Wine def review_list(request): latest_review_list = Review.objects.order_by('-pub_date')[:9] context = {'latest_review_list':latest_review_list} return render(request, 'reviews/review_list.html', context) def review_detail(request, review_id): review = get_object_or_404(Review, pk=review_id) return render(request, 'reviews/review_detail.html', {'review': review}) def wine_list(request): wine_list = Wine.objects.order_by('-name') context = {'wine_list':wine_list} return render(request, 'reviews/wine_list.html', context) def wine_detail(request, wine_id): wine = get_object_or_404(Wine, pk=wine_id) return render(request, 'reviews/wine_detail.html', {'wine': wine}) My urls.py (app) from django.conf.urls import url from . import views app_name = 'reviews' urlpatterns = [ # ex: / url(r'^$', views.review_list, name='review_list'), # ex: /review/5/ url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'), # ex: /wine/ url(r'^wine$', views.wine_list, name='wine_list'), # ex: /wine/5/ url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'), ] My urls.py from django.contrib import admin from django.urls import path, include app_name = 'reviews' urlpatterns β¦