Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extend djoser create jwt token view
Intro I am using Django rest as my backend api and djoser to handle my authentication system. the goal I want to extend the djoser create jwt token view, to store the jwt token at HttpOnly cookie. Does anyone have an idea how can I do it? Thanks in advance -
Django Rest Framework - Authentication credentials were not provide even with auth header, rest_framework.authtoken
So best I can tell this happened out of nowehere, I just deployed this API and it was working two days ago now that I've come back to it it's not working. I've regenerated fresh tokens, Tried with Curl vs postman and both fail, set cloudflare to dev mode and double checked their documentation (which states headers are pass thru), Verified TokenAuthentication was specified in my auth classes as well as double-checked my AuthenticatedUser default auth level. deleted and regenerated the database to create a fresh superuser I can get a token I just can't do anything past that. Any advice or guidance would be MUCH appreciated. I've checked through the following SO articles already: DRF Token Authentication: { "detail": "Authentication credentials were not provided." } Token Authentication Not Working on Django Rest Framework Authentication credentials were not provided django-rest-auth -
Django TruncHour + annotate Count not inlcuding hours with zero rows
I have a model EventData class EventData(models.Model): id = models.BigAutoField(primary_key=True) created = models.DateTimeField() session = models.ForeignKey(EventSession, on_delete=models.CASCADE) name = models.ForeignKey(EventName, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) value = models.CharField(max_length=200) and a query event_volume = IngestModels.EventData.objects.filter(product=my_product, created__date=selected_date) .annotate(hour=TruncHour('created')) .annotate(event_count=Count('*')) .values("hour", "event_count") that yields results like hour event_count 2021-11-12 00:00:00 2 2021-11-12 01:00:00 2 2021-11-12 02:00:00 7 2021-11-12 05:00:00 5 2021-11-12 06:00:00 9 2021-11-12 09:00:00 10 2021-11-12 10:00:00 1 2021-11-12 12:00:00 9 You'll notice that there are times when no events occurred, so the hour is omitted from the row. I'd really like each hour to be present and 0 in the event_count column if no events occurred. So something like: hour event_count 2021-11-12 00:00:00 2 2021-11-12 01:00:00 2 2021-11-12 02:00:00 7 2021-11-12 03:00:00 0 2021-11-12 04:00:00 0 2021-11-12 05:00:00 5 2021-11-12 06:00:00 9 2021-11-12 07:00:00 0 2021-11-12 08:00:00 0 2021-11-12 09:00:00 10 2021-11-12 10:00:00 1 2021-11-12 11:00:00 0 2021-11-12 12:00:00 9 Any help would be greatly appreciated! I'm using PostgreSQL as my database. -
Django -how to pass value in dynamic url into queryset
I have a dynamic url that will display the same page but with specific data depending on the value that is in the url. I'm trying to set up a View that will return the filtered data based on the value in the url but i don't know how to pass value in the url into the queryset. Views.py: from rest_framework import permissions from .serializers import ProductSerializer,CategorySerializer from .models import Product,Category from rest_framework.response import Response from rest_framework.views import APIView # Create your views here. class ProductViewSet(viewsets.ModelViewSet): queryset=Product.objects.all() serializer_class= ProductSerializer class CategoryViewSet(viewsets.ModelViewSet): queryset=Category.objects.all() serializer_class= CategorySerializer class ProductbyCategory(viewsets.ModelViewSet): categoryid=1 def __init__(self,request,categoryid): self.categoryid=categoryid queryset=Product.objects.filter(categoryid=categoryid) serializer_class= ProductSerializer Urls.py from .views import ProductViewSet,CategoryViewSet,ProductbyCategory from rest_framework import routers from .serializers import ProductSerializer,CategorySerializer from .models import Product,Category router = routers.DefaultRouter() router.register(r'products', ProductViewSet) router.register(r'category', CategoryViewSet) router.register(r'sort-by-category/<int:categoryid>', ProductbyCategory) urlpatterns = [ path('',include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Any help would be greatly appreciated -
ModelChoiceField returns a number instead of its value
I have a simple model for my csv files: class csvModel(models.Model): csvFileName = models.CharField(max_length=50) csvFile = models.FileField(upload_to='tpData/csv/') My script allows a user to upload a file Then, I use a ModelChoiceField that allows a user to select one of the uploaded file: class convertForm(forms.Form): fileToConvert = forms.ModelChoiceField(queryset=csvModel.objects.all(), label="Choose a CSV file to convert") When calling is_valid() I can access the value of the ModelChoiceField (e.g. if my csv file is named test1 I will get test1) def clean_fileToConvert(self): print(self.cleaned_data.get("fileToConvert")) #I get the name of the field (what I want) But when I try to access this value just below the is_valid() , I obtain a number (e.g. 48 for a file, 49 for the following etc.) form2 = convertForm(request.POST) if form2.is_valid(): print(request.POST.get("fileToConvert")) #I get 48 I even tried to return self.cleaned_data.get("fileToConvert") in the clean function but it does not work, I don't know how to access to the selected file name, url etc. -
How to reset a model field when creating a new instance via "Save As New"
Say I have a model w/ attribute special_id, I have the Save As New option enabled for the model's Admin, but when it creates the new instance I need to set special_id = None. What is the best way to achieve this? -
Django template different items for different groups. User authentication and group segregations
So I am trying to make a classroom like website but it is only for a course someone I know is running. I want different groups to have a different view for the website. For example group "Guest" can't see menu items group "Student" can see. But it is not quite working... Here's a bit of my code for the menu: {% if user.is_authenticated %} {% for group in user.groups.all %} {% ifequal group.name 'Student' %} <div class="menu"> <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button> <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button> <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button> <button onclick="location.href='http://10.0.0.60:8000/lessons';" class="home en">Lessons</button> <button onclick="location.href='http://10.0.0.60:8000/assignments';" class="home en">Assignments</button> </div> {% endifequal %} {%ifequal group.name 'Guest'%} <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button> <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button> <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button> {%endifequal%} {%else%} <div class="menu"> <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button> <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button> <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button> </div> {%endfor%} {%endif%} -
How to refer to all child objects with existing queries in self-referencing foreign key?
I have a model that represents an owner. There is a foreign key on this model to itself to represent a parent entity. There is another model called asset with a foreign key to owner. The purpose of the parent foreign key is to emulate a corporate structure, such that a parent “owns” an Asset whose foreign key is itself or a subsidiary: Class Owner(models.Model): parent = models.ForeignKey( “self”, ) Class Asset(models.Model): owner = models.ForeignKey( Owner, ) Is there a way return all assets owned by a parent and all of its subsidiaries by simply referencing the parent (eg Asset.object.filter(owner=parent))? I know I can create a method to return a queryset of all subsidiaries of a parent, and then filter to all assets in that owner queryset, but I am hoping to avoid a large refactor given the existing code base doesn’t have the concept of a parent owner. My first thought is a custom manager, but I don’t think that will change the behavior of existing queries that are all off the default manager. Can I overload filter on this model? If I need to rethink design that is fine, but I think this approach is cleaner and captures … -
Django REST Framework missing imports with Docker
So, recently I've started creating project using Docker for the first time so my knowledge is not very great. When I'm creating venv using python3 -m venv venv, and installing Rest Framework, everything works fine and I'm not having any problems at all. But in my project with Docker, I have no idea why but PyLance detects missing imports with Django and Django REST. It is really annoying, also when I'm making imports from Django, it makes suggestions: But it won't suggest anything when making imports from REST Does anyone know how to fix this issue? I've tried: Opening VSC in different directories Rebuliding Docker image Everything works fine, my requirements file contains REST Framework therefore it works fine. It is all about theese non-sense missing modules. -
Unable to Deploy Django App to Heroku because of PyWin32
So I have gone through the forums in search for an answer but haven't found one that works for me. I am using Windows machine and my Django application works on Localhost but when I try to deploy the same application to Heroku it gives me this error. INFO: pip is looking at multiple versions of anyio to determine which version is compatible with other requirements. This could take a while. remote: ERROR: Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32) (from versions: none) remote: ERROR: No matching distribution found for pywin32>=223 remote: ! Push rejected, failed to compile Python app. I have removed pywin32 from the requirements.txt file but still when I run the git push heroku master command, I keep getting the same error. I have also tried to copy all my source code into a new folder and deleted the initial git file and re-initialized Git but still nothing seems to be working. Forum Articles I have read that did not help include: Could not find a version that satisfies the requirement pywin32==227 heroku Heroku fails to install pywin32 library Allow me to attach my full error log: Enumerating objects: 268, done. Counting … -
How do I populate my form with the data sent by a user after a GET request in Django?
def index(request): if len(request.GET) == 0: form = FlightSearchForm() else: arr = request.GET.get('arrival_airport') dep = request.GET.get('departure_airport') form = FlightSearchForm({'departure_airport': dep,'arrival_airport': arr}) return render(request, 'app1/index.html', {'form': form}) What I want to do is create a form that would allow users to search for a flight, so I need them to use GET request. The problem is I don't know how to make their search appear in the fields after they go to their specific url (with all the details they searched for). It worked with a POST request in the past, but obviously I can't use it in this case. class FlightSearchForm(forms.Form): def __init__(self, *args, **kwargs): self.departure_airport = kwargs.pop('departure_airport') self.arrival_airport = kwargs.pop('arrival_airport') super.__init__(*args, **kwargs) departure_airport = forms.CharField(max_length=100) arrival_airport = forms.CharField(max_length=100) I tried something like that but it didn't help. Now it shouts that there is a keyerror, which doesn't exist. What can I do about this? -
Django ORM with PostgreSQL return wrong data using icontains
My model is class Seller(models.Model): supplierId = models.IntegerField('Supplier ID', primary_key=True) supplierName = models.CharField('Поставщик', max_length=255, null=True, blank=True) inn = models.CharField('ИНН', max_length=255, null=True, blank=True) ogrn = models.CharField('ОГРН', max_length=255, null=True, blank=True) legalAddress = models.CharField('Юридический адрес', max_length=512, null=True, blank=True) I have 2 records with the same supplierName='Смирнова Ольга Александровна'. sellers = Seller.objects.filter(supplierName__icontains='Смирнова Ольга Александровна') print(sellers.count()) # return 1 sellers = Seller.objects.filter(supplierName__contains='Смирнова Ольга Александровна') print(sellers.count()) # return 2 sellers = Seller.objects.filter(supplierName='Смирнова Ольга Александровна') print(sellers.count()) # return 2 I also try to use supplierName__search, but it returns not normal data too. icontains return wrong data not only in this example. What can i do with it? I need this for correct search on my site. -
Django test for a page that redirects
I am trying to write a test for a View that redirects to the dashboard but I'm not getting something right. A user must be authenticated before he/she can access the (membership) View. In my urls.py, I have something like ... path('membership/', MembershipView.as_view(), name='membership'), ... Then my tests.py contains class TestApp(TestCase): def test_that_membership_resolves(self): client = Client() response = client.post('/membership/', { # I then pass the necessary values in a dictionary ... ... }) self.assertRedirects(response, reverse("src:dashboard")) But the I am getting an error which says self.assertEqual( AssertionError: '/login/?next=%2Fmembership%2F' != '/dashboard' - /login/?next=%2Fmembership%2F + /dashboard : Response redirected to '/login/?next=/membership/', expected '/dashboard'Expected '/login/?next=/membership/' to equal '/dashboard'. I think it's telling me to login first. I already have a test a method that tests for login and the test passes. How can I solve this issue here? -
Heroku Slug Size Exceeded by 800MB For Django Project
This is my first time using Heroku to deploy a Django application and the slug size exceeds by 800MB. Error Log I used to have around 360 jpeg images in my folder but moved it to S3, and it went from 1.5GB to 1.3GB. I'm probably getting something completely wrong, but I can't seem to figure it out. There are a few aspects that I feel like is causing this. First, in one of the Django models, I have a field that serves pickle objects. I needed this because I need it to store the rgb data (numpy) for every image. It is 64*64pixels and it may be taking a lot of space. enter image description here The second is the 360 images that I had and pushed to Github. This is the command to show the files and folders in the current directory, ordered by (uncompressed) size: enter image description here If would be greatly appreciated if anyone could guide me to where I should look. Please tell me if I need to provide anything else. Thank you! -
I want to pluging openedx xblock ckeditor in xblock package please if any one do same thing then help me out
Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock SyntaxError: Unexpected token '>' at eval (<anonymous>) at Function.globalEval (jquery.js:343) at domManip (jquery.js:5291) at jQuery.fn.init.append (jquery.js:5431) at child.loadResource (xblock.js:236) at applyResource (xblock.js:199) at Object.<anonymous> (xblock.js:202) at fire (jquery.js:3187) at Object.add [as done] (jquery.js:3246) at applyResource (xblock.js:201) "SyntaxError: Unexpected token '>'\n at eval (<anonymous>)\n at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)\n at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)\n at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)\n at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)\n at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)\n at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)\n at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)" -
Django - Batch Actions in a ListView - Select Rows and Return a Zip Archive in Response
Ok, first off, I know this is not the best way to handle serving files on a prod server. But this site will be accessed by a small group of users, the request for these files should be minimal, and the static files being served are very small - so I am trying to keep things simple. I have a ListView Table where the user can select rows and then perform batch actions on the objects (eg. Delete, Export CSVs, Send CSV data to another location, etc). I've created a class based view to handle each of these batch actions. The only action that I can't get to work is when the user requests a download of a ZIP archive of the CSV data. When the ZIP export action is selected from the ListView, the selected rows are written as individual CSV files into to a static file location, and then zipped into a single ZIP archive. But the FileResponse never returns the archive to the user as a download. I've tried different ways of handling the response - redirecting to a new URL, reverse to the ListView, different URL patterns, etc. the method shown below that handles the create … -
NoReverseMatch at /course/ Reverse for 'course_detail' not found. 'course_detail' is not a valid view function or pattern name
I am trying to return all courses from the database to my course url and i got this error NoReverseMatch at /course/ Reverse for 'course_detail' not found. 'course_detail' is not a valid view function or pattern name. here is my code `class Courses(models.Model): category = models.ForeignKey(Category, related_name='courses', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100) description = models.TextField() cover = models.ImageField(blank=True, null=True, upload_to="courses_cover/") slug = models.SlugField() # Courses content content_url = models.URLField(blank=True, null=True) content_file = models.FileField(blank=True, null=True) price = models.PositiveIntegerField(default=1) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return reverse('courses:course_detail', args=[self.id, self.slug]) def price_display(self): return "{0:.2f}".format (self.price / 100) code for the views.py def course_list(request, category_slug=None): category = None categories = Category.objects.all() courses = Courses.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) courses = courses.filter(category=category) return render(request,'courses/content/list.html', {'category': category, 'categories': categories, 'courses': courses}) def course_detail(request, id, slug): course = get_object_or_404(Courses, id=id, slug=slug, available=True) return render(request, 'courses/content/detail.html', {'course': course}) ` code for the course urls app_name = "courses" urlpatterns = [ path('', views.course_list, name='course_list'), ] -
Unable to import firebase module inside firebase-messaging-sw.js
Im working on firebase messaging service to send push notification via django web application to web app on Andriod,IOS and website as well, I managed to get token and run sw ,however i can't running sw and get messages due to importing module issue, I tried all import statements and none has worked with me!!, when i run the below lines i got this error "Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js'); and when i run these ones i got this error "Cannot use import statement outside a module": import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"; import { getMessaging } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js"; Note I do not have any error when accessing localhost:/firebase-messaging-sw.js and download window open to download firebase-messaging-sw.js file please findfirebase-messaging-sw.js files for your reference: // import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"; // import { getMessaging } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js"; importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js'); self.importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js'); // import { initializeApp } from "./node_modules/@firebase/app"; // import { getMessaging } from "./node_modules/@firebase/messaging/sw"; // import { getMessaging } from "./firebase/@firebase/messaging/sw"; // Initialize the Firebase app in the service worker by passing in // your app's Firebase config object. // https://firebase.google.com/docs/web/setup#config-object const BikumApp = firebase.initializeApp({ apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx', authDomain: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx', databaseURL: 'xxxxxxxxxxxxxxxxxxxxxxxxxx', projectId: 'xxxxxxxxxxxxxxxxxxxxxx', storageBucket: 'xxxxxxxxxxxxxxxxxxxxxxx', … -
How do I perform a nexted query on django models
so i have these 2 model Profile (have one to one relationship with my default django User model) Item ( also have one to one relationship with my default django User model) from Item model, how do i get access to Profile model using User model please see my code below My Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=200,null=True) ``` My View def home(request): all_item_lists = Item.objects.all() context = { 'all_item_lists':all_item_lists } return render(request, 'findit/home.html', context) My Template {% for list in all_item_lists %} <!-- how want to get the phone number of the user that posted this Item --> <span>{{list.owner.first_name }}</span> {% endfor %}``` -
Importing from views directory
In my project I have an app called api where I keep my viewsets in a directory called views. I keep getting ModuleNotFoundError: No module named 'api.views.book'; 'api.views' is not a package where I import in my api/urls.py api/urls.py from rest_framework import routers from api.views.book import BookViewset router = routers.DefaultRouter() router.register(r'books', BookViewset, 'books') api_urls = router.urls In my main urls.py I'm doing this: urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from api.urls import api_urls urlpatterns = [ path('api', include(api_urls)), path('admin/', admin.site.urls), ] I didn't get an error until I imported api_urls -
Django Serializer from ManyToManyField using through
I'm trying to serialize the User model from Django, including a manyToMany relation I created. Here are my models: class CompanyAccount(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) user_ids = models.ManyToManyField(User, through='CompanyUser') class CompanyUser(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) user_id = models.ForeignKey(User, on_delete=models.CASCADE) company_id = models.ForeignKey(CompanyAccount, on_delete=models.CASCADE) is_company_admin = models.BooleanField(default=False, null=True) Now my goal would be to get the company serialized and returned along with any user. Here are my serializer, but sadly the company is not returned. class CompanyAccountSerializer(serializers.ModelSerializer): address_id = AddressSerializer(many=False) class Meta: model = CompanyAccount fields = '__all__' class UserSerializer(serializers.ModelSerializer): company_id = CompanyAccountSerializer(many=False, read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'first_name', 'last_name', 'company_id'] Any help is welcome :-) -
Django aggregate query with filters
i have two tables.Template and Tracker tables. with one to many relationship. i need to show all the uploaded templates for a particular user. also i need to order by with the download count. i tried the following query. but it's not getting the all downloaded count. Template.objects.filter(tracker__type='upload', user_id=300).annotate( download_count=Count( 'tracker', filter=Q(tracker__type='download') ) ).order_by("-download_count") Template Table id title description 1 AAA AAA 2 AAA AAA 3 AAA AAA Tracker Table id type user_id template_id 1 download 100 1 2 download 200 1 3 upload 300 1 -
How do you avoid SQL Injection attacks in your Django Rest APIs if using native ORM?
They say that by using Django ORM you are already protected against most SQL Injection attacks. However, I wanted to know if there are any additional measures that should or can be used to process user input? Any libraries like bleach? -
Heroku 20-stack django deployment issue (djongo not found)
-----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.6/site-packages/djongo/base.py", line 11, in from . import database as Database File "/app/.heroku/python/lib/python3.6/site-packages/djongo/database.py", line 2, in from pymongo import MongoClient File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/init.py", line 77, in from pymongo.collection import ReturnDocument File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/collection.py", line 20, in from bson.code import Code File "/app/.heroku/python/lib/python3.6/site-packages/bson/code.py", line 18, in from bson.py3compat import abc, string_type, PY3, text_type ImportError: cannot import name 'abc' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", … -
How do I pass a context name into a url call in my template html django
This is the urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('blog/', views.blog, name='blog') ] This is the views.py file def index(request): # Home home = Home.objects.latest('updated') # About about = About.objects.latest('updated') profiles = Profile.objects.filter(about=about) # Skills categories = Category.objects.all() # Portfolio portfolios = Portfolio.objects.all() context = { 'home': home, 'about': about, 'profiles': profiles, 'categories': categories, 'portfolios': portfolios } if request.method == "POST": form_inst = FormFill(name = request.POST['name'], email = request.POST['email'], text = request.POST['text']) form_inst.save() return redirect('/') return render(request, 'index.html', context=context) This is the html file where I am trying to pass each context name to the the navlink <div class="nav__menu" id="nav-menu"> <ul class="nav__list"> <li class="nav__item"><a href="{% url 'blog' %}" class="nav__link active" target="_blank">Blog</a></li> <li class="nav__item"><a href="{% url 'index' {{home}} %}" class="nav__link">Home</a></li> <li class="nav__item"><a href="{% url 'index' {{sbout}} %}" class="nav__link">About</a></li> <li class="nav__item"><a href="{% url 'index' {{profiles}} %}" class="nav__link">Skills</a></li> <li class="nav__item"><a href="{% url 'index' {{categories}} %}" class="nav__link">Portfolio</a></li> <li class="nav__item"><a href="{% url 'index' {{portfolios}} %}" class="nav__link">Contact</a></li> </ul> </div> I would like to pass the context dictionary keys in the url of each nav link in the html file