Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin User Permission in database object
I have a models how look like this : class Article(models.Model): # Créé une entrée titre dans la table Article de max 100 caractères titre = models.CharField(max_length=100) # créé une entrée auteur dans la table Article de 50 caractères max auteur = models.CharField(max_length=50) # créé une entrée contenu dans la table Article sans limite de caractères contenu = models.TextField(null=True) # céé une entrée date dans la database en date type field date = models.DateField(default=timezone.now, verbose_name="Date de parution") # créé une entrée image dans la table Article à l'aide du path stocké dans un varchar # L'image est stocké dans la string définie par upload_to. image = models.ImageField(upload_to='image/article', null=True) # céé une entrée preview_text dans la database preview_text = models.CharField(max_length=500, null=True) # créé une entrée slug dans la table Article. Le slug sert à définir l'url de l'article # Il est rempli automatiquement en fonction du titre grâce au prepopulated-field dans admin.py slug = models.SlugField(max_length=100) # Ajout de la clef étrangère catégorie à la table Article. models.PROTECT empèche la supression de la catégorie # si utilisé par un article categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT) # Ajout de la clef étrangère Flag à la table Article. models.PROTECT empèche la suppression du Flag si … -
Python pyminizip package requires password only once
I am using pyminizip to password protect my zip. I am zipping a file using the mentioned package in python. When I try to extract or read, it asks for a password. Till here is fine. However, once I have entered the password and read or extracted the file, then when I again try to read or extract the file, it does not ask for a password. Even when I again compile the code to create a zip, it will run fine but it wont ask for a password again even though the properties of the zip shows that it is password protected. I am on python 3.7.4 Here is my code: import pyminizip compression_level = 5 # 1-9 pyminizip.compress(src, None, dest.zip, "password", compression_level) -
Python is already installed within virtual env
When I created a virtual Environment , in that I am already getting Python 3.7 which is on my local Machine . But I need Python 2 for my Project . How should I install that in my virtualenv And Also why python is already there? -
Django:How to store images in database instead of media file?
I want to store images in database for various users.Its just like famous blog app but instead of blogs i want to store images in database.How can i implement my idea? -
Django runserver throws error during boot
Am trying to run a django server, the server was running fine, but after reverting to old git commit, it started to throw the below error when I do python manage.py runserver Error (venv_prd) D:\projects\rd-portal\rdportal>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\contrib\auth\models.py", line 95, in <module> class Group(models.Model): File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\db\models\base.py", line 156, in __new__ new_class.add_to_class(obj_name, obj) File … -
How can I integrate a function based view into a Class Based View?
In my site I have 2 sections for users. The user posts page and the profile page. The profile page has all their info on it, so username, description, first/last name, etc. And the user posts page has all their posts on it. However, I want to integrate them together somehow. Here is some of the code. Here is the view for the User Posts class UserPostListView(ListView): model = Post template_name = 'mainapp/user_posts.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User,username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-published_date') As you can see, I am returning the specific users posts. And now here is my profile view def view_profile(request,pk=None): if pk: user_profile = User.objects.get(pk=pk) else: user_profile = request.user context = {'user':user_profile} return render(request,'mainapp/profile.html',context) It returns all the user's info. Here is the HTML code for both the profile and user posts page {% block content %} <div class="profile-page-container"> <div class="profile-page-info"> <div class="profile-page-banner"> <div class="profile-page-banner-background"> <!-- <img src="https://cdn.pixabay.com/photo/2017/08/30/01/05/milky-way-2695569_960_720.jpg" alt="{{ user }}'s Background Image" > --> </div> <div class="profile-page-banner-text"> <h2 title="{{ user }}" id="username-profile-page">{{ user|safe|linebreaksbr|truncatechars_html:25 }} {% if user.userprofileinfo.verified %} <span class="image-profile-verified"><img draggable="false" title="Verified User" class="verifed" src="{% static 'images\verified.png' %}" alt="verified" width="25" height="25" srcset=""></span> {% endif %}</h2> <p>{{ user.first_name }} {{ user.last_name }}</p><br> </div> </div> <div class="profile-page-user-desc-box"> <p>{{ … -
Django social-auth-app-django always redirects to LOGIN_ERROE_URL
social-auth-app-django always redirects to LOGIN_ERROR_URL after the google authentication completes. I am using the custom user model I tried with default settinga, changing the pipelines and created my own, but none of them works. MIDDLEWARE = [ .... 'social_django.middleware.SocialAuthExceptionMiddleware', ] SOCIAL_AUTH_PIPELINE = [ 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'accounts.views.fetch_social_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ] def fetch_social_user(backend, user, response, *args, **kwargs): global SOCIAL_USER_EMAIL, SOCIAL_USER_FNAME, SOCIAL_USER_LNAME, SOCIAL_USER_IMAGE SOCIAL_USER_EMAIL = response['email'] SOCIAL_USER_FNAME = response['given_name'] SOCIAL_USER_LNAME = response['family_name'] SOCIAL_USER_IMAGE = response['picture'] I need to redirect it to login_success url -
django auth ldap | Add LDAP user in admin-panel
Maybe, anybody know... I need add LDAP user inside admin panel. My autentithication LDAP in Django works, but I have to add users very strange. First they log in and they are not allowed. Then I go to admin panel and see user is added, but without the Staff status flag. I activate the flag. The user can log in with his LDAP account. Question: Is it possible to first add an LDAP user in the admin panel itself and activate everything that is needed so that the user does not have to log in twice? -
How to partiallly update a model in django rest framework?
I built an api with django and I have a picture model that comprises an imagefield. I'm trying to perform a partial update I already tried setting partial = Trueto the Serializer's definition the serializer is class PictureSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Picture fields = ("id", "name", "picture", "button_1", "button_2", "button_3", "button_4") partial = True the model is class Picture(models.Model): name = models.CharField(max_length=250) picture = models.ImageField(upload_to="pictures/", null=True, blank=True) button_1 = models.BooleanField(default=False) button_2 = models.BooleanField(default=False) button_3 = models.BooleanField(default=False) button_4 = models.BooleanField(default=False) printed = models.IntegerField(default=0) the view is class PictureViewSet(viewsets.ModelViewSet): queryset = Picture.objects.all() serializer_class = PictureSerializer -
How to save the data from the post request in django?
I was trying to implement a comment in a blog using a POST method. I want to save get the data by POST method of name, email, text and save it to the database. Also, the date field should get the date.now() and blog field should get the Blog or id of the Blog. The code looks like this - models.py : from django.db import models class Blog...... class Comment(models.Model): id = models.AutoField(primary_key=True, default=0) blog = models.ForiegnKey(Blog_tables, on_delete=models.CASCADE) name = models.CharField(max_length=200) email = models.EmailField() Text = models.TextField() date = models.DateField() def __str__(self): return self.Text views.py from .models import Blog, Comment from django.shortcuts import render, get_object_or_404, redirect from django.template import loader, RequestContext from django.http import HttpResponse, HttpResponseRedirect def blog_detail(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'home/detail.html', {'blog': blog}) def post_comment(request, blog_id): # Here's a post code to be implemented. Please read the commented text # 'blog' field of models will get the id of the blog # 'name' field will get the POST method value of input name="name" # 'email' field will get the POST method value of input name="email" # 'text' field will get the POST method value of input name="text" # 'date' will get the current Date # … -
Include foreign keys to modelform
I have two models: class A(models.Model): name = models.CharField() class B(models.Model): a_object = models.ForeignKey(A) value = models.PositiveIntegerField() I have a ModelForm for object A and I'm trying to create a select field for that relation: class AForm(ModelForm): b_types = ModelChoiceField(queryset=B.objects.all()) but I keep getting the error AttributeError: type object 'B' has no attribute 'all' What am I doing wrong here? -
When running djangos dbshell command, error you appear not to have the sqlcmd program installed or on your path
When I first started the project, I had access to the dbshell command, but now I don't because apparently I don't have the sqlcmd program installed or on my path. I must have somehow accidentally deleted it from the path or unistalled it. Do you know where it would be located, and/or where I could download an older version? (I am using sql server 2014, so the new one doesn't work) -
Django How to gather HTML for {% include %} and assign to JS variable
I am using JSPDF to convert HTML to a PDF. This is extremely simple if I have a rendered page and then clicking a button just exports the appropriate PDF, however, I am attempting to create a receipt via JSPDF and rendering the page prior to providing the PDF is not a good option. With this, I am using Django and basically what I want to do is use a template's html to render the receipt I need: For example: <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.min.js"></script> let doc = new jsPDF(); $('#click').click(function () { let a = {% include 'receipt_template.html' with data=payment_data %}; doc.fromHTML(a, 0, 0, { 'width': 170 }); doc.save('receipt.pdf'); }); But this is not working as I am not gathering the template's HTML, I am literally rendering it on the page. Is what I am trying to do possible? -
How to do Delete Confirmation in Django
I am working on a project in django. I'm trying to do delete Confirmation alert before deleting data. How to do. Any advice would be much appreciated. views.py def del_data(request, obj_id): del_data = Order_data.objects.filter(order_no=obj_id) if len(del_data) > 0: del_data.delete() return redirect('/home/') return render(request, 'delete_conf.html', {}) urls.py urlpatterns = [ path('delete/<int:obj_id>/',views.del_data,name="del_data") ] delete_conf.html <table id="order_view_table"> <tr> <th>Name</th> <th>Email</th> <th>ACTION </th> {% for i in result %} <tr id="get_data"> <td id="name">{{ i.name }} </td> <td>{{ i.email}} </td> <td><a href="{% url 'app:edit_data' i.order_no %}" > <i class='fas fa-edit' ></i></a><a href="{% url 'app:del_data' i.order_no %}"><i class='fas fa-trash-alt' ></i></a> </tr> {% endfor %} </table> -
AWS Upgrading site Django site from Python 2.7 to 3.6
I've a Django project running on AWS with Django1.11 and Python 2.7. I am upgrading it to Django 2.2 and Python 3.6 I have it running locally and all tests pass. I am not trying to load it onto an AWS elasticbeanstalk instance. When I do eb deploy, I am getting the following error in the eb activity log Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/__init__.py", line 5, in <module> import distutils.core File "/opt/python/run/venv/lib64/python3.6/distutils/__init__.py", line 4, in <module> import imp File "/opt/python/run/venv/lib64/python3.6/imp.py", line 27, in <module> import tokenize File "/opt/python/run/venv/lib64/python3.6/tokenize.py", line 33, in <module> import re File "/opt/python/run/venv/lib64/python3.6/re.py", line 142, in <module> class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' The Python2.7 version was using enum34 (in requirements.txt) which I've deleted/uninstalled so I don't believe that is the issue. Can anyone help? -
How to fix "Project with ID "some id" doesn't exist" Django FileField model error
I have a model which I can edit from admin page. I want to upload the file, let the server do some changes to it, then download the file back. In models: class Project(models.Model): project_title = models.CharField(max_length=200) project_content = models.TextField() project_published = models.DateTimeField("date published", default=datetime.now()) project_file = models.FileField(default="Null",upload_to='Files') def __str__(self): return self.project_title In admin: class ProjectAdmin(admin.ModelAdmin): #fields = ["project_title", # "project_published", # "project_content", # "project_funded",] fieldsets = [ ("Title/date", {"fields": ["project_title", "project_published"]}), ("URL", {"fields":["project_slug"]}) ("Content", {"fields":["project_content", "project_file"]}), ] FileField generates 2 sub-fields: an upload button, and a "current" field with the link to the current file if one exists. File upload works just fine, and the file is stored in "Files" directory, but when I click the link I get redirected to homepage and get the "Project with ID "1/change/Files/somefilename" doesn't exist. Perhaps it was deleted?" error. I have tried adding to admin: def file_link(self, Project): if Project.project_file: return "<a href='%s' download>Download</a>" % (Project.project_file.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' but it just prints the href as plain text, containing the "Files/somefilename" url. -
Django: How to use more than 2 Class Based Generic Views in one template
I was trying to create a web app in which a user can see other posts while updating a post. So, for that, I want to use both ListView And UpdateView together in the same template. My Views.py: from django.shortcuts import render from .models import Entry from django.views.generic import ListView from django.views.generic.edit import UpdateView from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin class index(LoginRequiredMixin, ListView): template_name = 'diary/index.html' context_object_name = 'entries' def get_queryset(self): # def get_queryset(self, request): return Entry.objects.filter(author=self.request.user) class EntryUpdate(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Entry fields = ['title', 'content'] template_name = 'diary/update.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False I don't know if I should create another view, or that there is an inbuilt functionality for this, so, it would be really helpful if you guys can help me out. Any Help Would Be Appreciated! -
Making HTTP GET request that target a collection of instances in DjangoRESTFUL
I started with checking if the serializer works as i expected but it didn't show any output after running the code. from datetime import datetime from django.utils import timezone from django.utils.six import BytesIO from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from toys.models import Toy from toys.serializers import ToySerializer toy_release_date = timezone.make_aware(datetime.now(), timezone.get_current_timezone()) toy1 = Toy(name='Snoopy talking action figure', description='Snoopy spearks five languages') toy1,save() toy2 = Toy(name='Hawaiian Barbie', description= 'Barbie loves Hawaii', release_date="") toy2.save() print(toy1.pk) print(toy1.name) print(toy1.created) print(toy1.was_inclded_in_home) print(toy2.pk) print(toy2.name) print(toy2.created) print(toy2.was_included_in_home) serializer_for_toy1 = ToySerializer(toy1) print(serializer_for_toy1.data) serializer_for_toy2 = ToySerializer(toy2) print(serializer_for_toy2.data) json_renderer = JSONRenderer() toy1_rendered_into_json = jason_renderer.render(serializer_for_toy1.data) toy2_rendered_into_json = json_renderer.render(serializer_for_toy2.data) print(toy1_rendered_into_json) print(toy2_rendered_into_json) json_string_for_new_toy = '{"name":"Clash Royale play set","descriptions":"6 figures from Clash Royele"}' json_bytes_for_new_toy = bytes(json_string_for_new_toy, encoding="UTF-8") stream_for_new_toy = BytesOI(json_bytes_for_new_toy) parser = JSONParser() parsed_new_toy =parser.parse(stream_for_new_toy) print(parsed_new_toy) new_toy_serializer = ToySerializer(data=parsed_new_toy) if new_toy_serializer.is_valid(): toy3 = new_toy_serializer.save() print(toy3.name) but then i had started with creating my Django views combined with serializer classes. from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from rest_framework import status from toys.models import Toy from toys.serializers import ToySerializer class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] ='application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def toy_list(request): if request.method == 'GET': … -
How to fix 'User has no attribute usergroup' eventhough it's added?
I have to develop a register form, I'm using crispy forms for this. (It was not my idea...), So I wrote a RegisterForm class (see code), and added some nice fields to work with, they all do work, unless usergroup = forms.ChoiceField(choices=GROUPS). Django shows me an Attribute error: User' object has no attribute 'usergroup'. Eventhough I can call all the other things such as fullname and email. I've already tried setting it to CharField and enter it manually but this gives me an error too. GROUPS = ( ('None', 'Choose...'), ('xyit', 'xy IT'), ('xyhr', 'xy HR'), ('xysales', 'xy Sales'), ('cn', 'admin'), ) class RegisterForm(UserCreationForm): fullname = forms.CharField() usergroup = forms.ChoiceField(choices=GROUPS) email = forms.EmailField() class Meta: model = User fields = ["fullname","usergroup", "username", "email", "password1", "password2"] And this is where I want to call it: def contacts(request): username = None if request.user.is_authenticated: username = request.user.username fullname = request.user.fullname email = request.user.email usergroup = request.user.usergroup print(email, fullname, usergroup) numberDevices = len(DeviceInformation.objects.all()) numberDevicesUser = len(request.user.deviceinformation.all()) return render(request, contact_req, {'username':username, "numberDevices": numberDevices, "numberDevicesUser": numberDevicesUser,}) else: return render(request, unauthorized_req, status=401) {% block register %} <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy}} <button type="submit" class="btn btn-dark">Register</button> </form> {% endblock %} Django==2.2.4 Python==3.6.8 AttributeError by Django … -
How to show specific fields only to the user profile owner in graphene-django?
I have the following schema in my graphene-django application: import graphene from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType class UserType(DjangoObjectType): class Meta: model = get_user_model() fields = ("id", "username", "email") class Query(object): user = graphene.Field(UserType, user_id=graphene.Int()) def resolve_user(self, info, user_id): user = get_user_model().objects.get(pk=user_id) if info.context.user.id != user_id: # Return User object without the `email` field else: # Return User object with all fields I want to be able to query the schema in the following way: # Logged in as user 1 => no errors query { user (userId: 1) { id username email } } # Not logged in as user 1 => no errors query { user (userId: 1) { id username } } # Not logged in as user 1 => return error because accessing email query { user (userId: 1) { id username email } } How can I make it so that only a logged in user can see the email field of their own profile and no one else can see the emails of others? -
How to download content from my Django webpage?
I have a table on one of my Django webpage. I want to give the user the ability to download the content of the table in xl format. What would be an efficient and good way of doing this? I was thinking of creating an xlsx file using the xldr library. Writing the data on the file. making the file available for download and then deleting the file at the end, so that my drive stays clean. but it doesn't feel like a very efficient way. I'm new in web development, so open to all kind of ideas. Thanks -
Many-To-Many reverse field lookup with ids in Django
I try to figure out how to produce the correct queryset to retrieve url and value fields (Attr_1 and Attr_2 model) from querying the Object1 models 'reverse set' Many-to-Many Relation. Here is my Example: models.py: class Text(models.Model): string = models.TextField() #Entity class Element(models.Model): pageline = models.IntegerField() class Object1(Element): text = models.ManyToManyField(Text) class Object2(Element): another_var = models.ManyToManyField(Text) yet_another = models.CharField(max_length=1) #Entity class Attribute(models.Model): belongsTo = models.ManyToManyField(Element) class Attr_1(Attribute): url = models.URLField() class Attr_2(Attribute): value = models.CharField(max_length=255) date = models.URLField() If I use: >> models.Object1.objects.get(pk=1).attribute_set.all() <QuerySet [<Attribute: Attribute object (1)>, <Attribute: Attribute object (2)>]> >> models.Object1.objects.get(pk=1).attribute_set.values() <QuerySet [{'id': 1}, {'id': 2}]> I guess now I have to query Attr_1 for pk=1 and Attr_2 for pk=2? Does the Attribute model has a relation to know if id=1 is in Attr_1 or Attr_2 model? Any help is appreciated. Thank you! -
Not getting varaiable from django template
i am working on a function to send emails to users, from django admin area. I created a form in forms.py class SendEmailForm(forms.Form): subject = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Subject'})) message = forms.CharField(widget=forms.Textarea) users = forms.ModelMultipleChoiceField(label="To", queryset=User.objects.all(), widget=forms.SelectMultiple()) And an admin action in admin.py: def send_emails(self, request, queryset): emails = "" for qr in queryset: emails += qr.email + ", " form = SendEmailForm(initial={'users': queryset}) context = {'form': form} return render(request, 'admin/send_email.html', context) send_emails.short_description = u"Send email" class CustomUserAdmin(UserAdmin): actions = [send_emails] And from views.py i am trying to extract the user emails, but i can only extract the message and the subject, when i extract the variable users i get the number of users. def send_emails(request): if request.method == 'POST': form = SendEmailForm(request.POST) print("STEP1") if form.is_valid(): users = request.POST['users'] print(users) and the template code is {% extends "admin/base_site.html" %} {% load i18n admin_urls static %} {% block content %} <p>{% blocktrans %}Write your message here{% endblocktrans %}</p> <form method="POST" action="{% url 'email' %}">{% csrf_token %} <div> <div> <p>{{ form.users.errors }}</p> <p>{{ form.users.label_tag }}</p> <p> {% for user in form.users.initial %} {{ user.email }}{% if not forloop.last %},&nbsp;{% endif %} {% endfor %} </p> <select name="users" multiple style="display: none"> {% for user … -
How to display list of lists in different divs in django
I have list of lists, which I'm sending to html: views.py: data = (('13:20','Dave','Stivenson'),('14:15','John','Scaletta'),('11:00','Dave','Johnston')) return render(request, 'test.html', {'rows': data}) test.html: {% for r in rows %} <div class="col-md-3"> <span style="color:white;font-size:14px">{{ r }}</span> </div> {% endfor %} It displays list in div, but how can I display not list, but list strings in div? Like: 13:20 Dave Stivenson -
Django: transfering two primary keys to new detail view
I'm trying to create a detail view where I use employee and subject name to show the evaluations created in the specific subject. I currently have this detail where, where I'm looping through the subject names and displaying all the evaluations for the subject for the employee. The view is using employee as the primary key. So when I press on the subject name from the loop below, I wish to go to a new view where I show the evaluations for the subject by the specific employee. Employee template {% for subject in subject_list %} {{ subject.subjectname }} {% for evaluation in subject.evaluation_set.all %} {{ evaluation.instructor }} {{ evaluation.ma }} {% endfor %} {% endfor %} I can't figure out what the best way to do this is. I believe using the employee primary key for the new view is correct, but how do I "transfer" the subject id from the loop to the next view? Alternatively I can use the subject id for the view but then I don't understand how to "transfer" the employee over. Employee view with subjects class EmployeeEvalDetailView(DetailView): template_name = 'evalsys/evalueringer/se_alle_evalueringer.html' model = Employee def get_context_data(self, **kwargs): context = super(EmployeeEvalDetailView, self).get_context_data(**kwargs) context['fagene'] = Subject.objects.all().prefetch_related(Prefetch('evaluation_set', …