Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django Admin FilteredSelectMultiple form widget with the Add button
I'm trying to use the Django admin FilteredSelectMultiple within a user form, but I also want to include the add button and cannot work out how. This is my form field definition search_areas = forms.ModelMultipleChoiceField( queryset = SearchArea.objects.all(), widget= FilteredSelectMultiple("Postcodes", is_stacked=False), required=True ) And the model: class SearchArea (models.Model): """ This is a Search Area """ post_code = models.CharField( max_length=51, unique=True, ) lat = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True, help_text='This will be populated using the postcode entered on save' ) lng = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True, help_text='This will be populated using the postcode entered on save' ) This provides me with the horizontal filter/select widget, but not the add button. How can I include that? -
Генератор тем на Django [closed]
коллеги! есть задача - написать генератор тем в админке django, то есть - заходим в админку, выбираем (условно) красный цвет, сохраняем и после этого ui сайта меняется на красный. причем не только цвет, а шрифты и т.д. существуют ли какие-нибудь готовые решения для данной задачи? спасибо! -
Problem querying a specific django object correctly
In my (basic) fantasy football app I'm building, I have each player/position represented by an individual model object. Like so. Here's one such model/position. class Quarterback(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=20, blank=True) I also have a "Team" model which has information on team name, user, and players in the team. The main purpose of this object is because I want to display a list of all users and their teams and their team's total score so that each user can see how everyone else is scoring. class Team(models.Model): team_name = models.CharField(max_length=255, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) quarter_back = models.ForeignKey(Quarterback, on_delete=models.CASCADE, null=True) running_back = models.ForeignKey(Runningback, on_delete=models.CASCADE, null=True) wide_receiver = models.ForeignKey(Widereceiver, on_delete=models.CASCADE, null=True) tight_end = models.ForeignKey(Tightend, on_delete=models.CASCADE, null=True) kicker = models.ForeignKey(Kicker, on_delete=models.CASCADE, null=True) The problem I'm having though is assigning a total score. What I'm trying to do is compare the players'names in Team to a list of players and scores that I've pulled from an api. Let's call it "player_data." If the player in the Team object is in the player_data object, I can then assign the player's score to a variable called "totalscore", tally it, render it to my template, etc. But, I'm having trouble with … -
Django REST AttributeError 'dict' object has no attribute 'pk'
Im trying to do django rest api with Django Rest Framework. The issue Im experiencing is 'dict' object has no attribute 'pk' when I try to display agregated data. I can see in the trace serializer.data displayed as it should be, the format is as follows: [{'maint_window':'W1-12:00-CET', 'total':'10'}, {'maint_window':'W2-12:00-CET', 'total':'5',} {'maint_window':'W3-12:00-CET', 'total':'22'}] But it seems that I`m not returning the correct format in the view, or in the serializer. models.py: from django.db import models class Server(models.Model): name = models.CharField(max_length=60) fqdn = models.CharField(max_length=60) maint_window = models.CharField(max_length=60) def __str__(self): return self.name serializer.py: class ServerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Server fielsds='__all__' views.py: class OpsCalendarViewSet(viewsets.ModelViewSet): """ API endpoint that shows ops calendar """ queryset = Server.objects \ .filter(~Q(maint_window__contains='MW') & \ ~Q(maint_window__contains='Change') & \ ~Q(maint_window__contains='Individual')) \ .values('maint_window') \ .annotate(total=Count('name'))\ .order_by('maint_window') serializer_class = ServerSerializer permission_classes = [permissions.AllowAny] And the error itself: lookup_value = getattr(obj, self.lookup_field) AttributeError: 'dict' object has no attribute 'pk' -
Company internal User creation in django without a signup url
I am trying to create an authentication system for a Company and the Company would want to have its admin create users from his endpoint and then the users can receive an email, where they can click a link, a link shall just have a password one field and password two field and the moment they click the save button they would be able to avtivate their account and be redirected to the dashboard based on the category they belong to. Below is my code. class UserManager(BaseUserManager): USER_TYPE_CHOICES = [ ('supervisor', 'SUPERVISOR'), ('operator', 'OPERATOR'), ('hofosm', 'HEAD OFFICE ORDINARY STAFF MEMBER'), ('hofom', 'HEAD OFFICE MANAGEMENT'), ('hofis', 'HEAD OFFICE IT STAFF'), ] def create_user( self, email, is_superuser=False, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Enter Valid Email") user_obj = self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_superuser(self, email, password=None, **extra_fields): user=self.create_user( email, password = password, is_staff = True, is_admin =True, is_superuser=True, **extra_fields ) return user class User(AbstractBaseUser, PermissionsMixin): title = models.CharField(max_length=341, choices = USER_TITLE_CHOICES) category = models.CharField(max_length=341, choices = USER_TYPE_CHOICES, default='operator') first_name = models.CharField(max_length =32, blank=True, null=True) middle_name = models.CharField(max_length =32, blank=True, null=True) company_branch= models.ForeignKey( 'company_setup.CompanyBranch', related_name='employees', on_delete=models.SET_NULL, null=True, blank=True ) … -
Django templates - how to strictly check for equality of a string
I struggling to solve the following: I am customizing django tabular inline template which contains several fields. I have a condition {% if field.field.name == 'productid' %} ... {% endif %} However there are two fields that have the ... condition applied which is "productid" and "distributionid price productid" - both contain the productid word. However, I want only the former to have it. How can I make this condition more strict? Any help will be much appreciated. -
How to make Django send request itself
I need to make GET request, that executes himself once per 3 day, I found things about celery and Redis, but I don't understand how to send request. I mean, if I use celery, I need to wrap function with @app.task, so it can't be method GET of a class, right? And so I can't use method of a class outside of class, cause I don't have self (instance of a class). So how do I make Django send request to itself? -
Checkbox to select multiple images and download (Django)
I am stuck with implementing a multiple image download using Django. As seen in the photo, I want to download the images that are checked. How am I able to go about doing this using Django and Jquery? I am able to download individual images using html tag but this is not what I need. Any help would be greatly appreciated! Using Jquery, on click of the download button at the bottom of my webapp, I would check for the checkboxes that are ticked and then grab the url of those images and append them to an array. I am stuck from this step onwards. Link to webapp image -
How to return a multiple values of one method in template in django
How to return a multiple values of one method in template in django class Invoice(models.Model): client = models.ForeignKey(Client, on_delete=models.PROTECT) price = models.DecimalField(default=0, max_digits=20, decimal_places=2) quantity = models.DecimalField(default=0, max_digits=20, decimal_places=2) def total(self): x = self.price y = self.quantity return x, y How to implement it in Html ? {{ invoice }} -
Django DetailView not displaying the content from the database
I am trying to develop a job portal where people can post jobs. I created a Listview and a DetailView for the application. The list view is working but the content isn't appearing on the details page. views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Application_create # Create your views here. class AllApps(ListView): model = Application_create template_name = 'fundamentals/allapps.html' ordering = ['-id'] class ApplicationInDetail(DetailView): model = Application_create template_name = 'fundamentals/application_detail.html' urls.py: from django.urls import path from .views import AllApps, ApplicationInDetail urlpatterns = [ path('allappslist', AllApps.as_view(), name='applist'), path('app_in_detail/<int:pk>', ApplicationInDetail.as_view(), name='application_detail') ] models.py: from django.db import models from django.urls import reverse_lazy # Create your models here. class Application_create(models.Model): application_title = models.CharField(max_length=500, default='') application_opening = models.DateTimeField(auto_now=True) application_closing = models.DateField() application_description = models.TextField(default='') company_name = models.CharField(max_length=500, default='') skills_req = models.CharField(max_length=2000, default='') job_pay = models.IntegerField(default=10000) freelancing_pay = models.IntegerField(default=10000) job_type = models.CharField(max_length=500) def __str__(self): return self.application_title + self.company_name def get_absolute_url(self): return reverse('application_detail', args = [str(self.id)]) base.html: <html> <head> {% load static %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <link rel="stylesheet" href="{% static 'css/allappslist.css' %}"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light navbar_custom"> <a class="navbar-brand" … -
django `django.contrib.auth.urls` to generic view set for get auto documentation using redoc?
I used a redoc for auto-documentation my API this is my route router = DefaultRouter() router.register('user', GenericsUserViewSet, basename='user') router.register('userProfile', GenericsUserProfileViewSet, basename='userProfile') urlpatterns = [ .... path('api/v1/doc/redoc/', schema_view.with_ui('redoc', cache_timeout=0)), .... path('api/v1/accounts/', include('django.contrib.auth.urls')), # THIS WHAT I WANNA REG INTO ROUTER ] my question is, how to transform django.contrib.auth.urls into generic view set, so i can register that into router for auto documentation? -
Plotly margin is not working in update_layout - Django
I'm using Plotly to draw gauge charts in my Django project. In views.py, I tried to update layout by setting margin for the graph like the following: gauge_toc = go.Figure(go.Indicator( mode = "gauge+number", value = 5, domain = {'x': [0, 1], 'y': [0, 1]}, title = {'text': "TOC [mg/L]"}, gauge = {'axis': {'range': [0, 50]}, # 'steps' : [ # {'range': [0, 250], 'color': "lightgray"}, # {'range': [250, 400], 'color': "gray"}], # 'threshold' : {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': 490} } ) ) gauge_toc.update_layout(font = {'color': "black", 'family': "Arial"}, margin = dict(t=0, b=0, l=5, r=5,)) config = { 'scrollZoom': False, 'displayModeBar': False, 'editable': False, 'showLink':False, 'displaylogo': False } div_toc = opy.plot(gauge_toc, auto_open=False, config=config, output_type='div') Although the left and right margins seem to work, the vertical margins won't disappear! this isthe template: <div class="row"> <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3"> {% if graph_temperature %} <div > {{ graph_temperature|safe }} </div> {% endif %} </div> <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3"> {% if graph_ph %} <div > {{ graph_ph|safe }} </div> {% endif %} </div> </div> any suggestions? -
AttributeError: 'NoneType' object has no attribute 'secret'
I am working on a django tenants app. I want to store stripe api keys to db. Here is my code class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True) The model has been migrated and I have added a single set of data to db. But when I print out to terminal from view it shows empty and if I print out and instance it throws the above error. api_key = ExternalKeys.objects.order_by('pk').first().secret print(api_key) I can see the data in django admin -
Create a backup of every posts
I've developed my personal blog to learn Django, I would like to make a backup of every post on a second model. Below there is an example of my aim: from django.db import models class mainModel(models.Model): text = models.CharField(max_length=250) class copyModel(models.Model): main = models.ForeignKey(mainModel, on_delete=models.CASCADE) text = models.CharField(max_length=250) def save(self, *args, **kwargs): self.text = mainModel.text super(copyModel, self).save(*args, **kwargs) When I create or modify a post into mainModel must be create a copy of it into copyModel. With the code above I can create a "post" but the save method from copyModel doesen't work. Is this the right way? -
Django decorators to handle admin users redirection
I want normal users to be redirected to <address>/panel and need admins to be redirected to <adress>/admin. So what I did in views.py is something like: from django.contrib.auth.decorators import login_required @unauthenticated_user def registration_view(request): ... @unauthenticated_user def login_view(request): ... @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def admin_home_view(request): context = {} return render(request, 'account/admin/home-page.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['user']) def user_home_view(request): context = {} return render(request, 'account/user/home-page.html', context) And in decorators.py I have: from django.http import HttpResponse from django.shortcuts import redirect from groups_manager.models import Group, GroupMemberRole, Member def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('panel') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): allowed_role = allowed_roles[0] username = request.user.username member = Member.objects.get(username=username) roles = GroupMemberRole.objects.filter(groupmember__member=member) label = roles.get(label=allowed_role).label if label == allowed_role: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not allowed!') return wrapper_func return decorator I want to know how I can redirect admin users to <address>/admin url. My urls.py is: urlpatterns = [ path('admin', views.admin_home_view, name='admin'), path('panel', views.user_home_view, name='panel'), path('panel/register', views.registration_view, name='register'), path('panel/logout', views.logout_view, name='logout'), path('panel/login', views.login_view, name='login'), ] -
How to restart a django project without refresh session data stored in process/thread space?
In my django project, I store an instance of a complex class in the thread space. This instance is hard to be serialized so it cannot be stored in the database and resumed from database. When a request coming, the instance is used to response. When I refresh the code, I wanna to reload the project without refresh the instance. As the instance keep a lot of information which takes a very long time to construct again. Is there any way to keep the instance(object that cannot be serialized) when reload django project? Or is there any way to keep the instance and resume it which cannot be stored in database? -
RelatedObjectDoesNotExist in Django
i am working on ecommerce site and i get this error "Exception Type: RelatedObjectDoesNotExist Exception Value: User has no customer." models.py class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) views.py def cart(request): customer=request.user.customer order,created=Order.objects.get_or_create(customer=customer,complete=False) items=order.orderitem_set.all() context={ 'items':items } thanks beforehand. -
how can i itter on each file of folder in django project?
i am trying to read each file in folder with this code: for filename in os.listdir('spectrum_order/zip_file'): if filename.endswith(".xlsx") or filename.endswith(".xls"): read = pd.read_excel(filename) labels = read['x'].tolist() but it raise this error: No such file or directory: '1.xlsx' it Shows the names of the files in the folder. But it says there is no file. my folder: image of folder when i remove 1.xldx it raise: No such file or directory: '2.xlsx' -
Char is UTF But I Still See Encrypted Letters
When some Korean texts went through the Django server, I printed the 'data' variable just to see if this encryption issue was caused by Python. Fortunately, Korean letters show well: However, when the letters go through the Django templates, it shows like this: Notice the words like \uc57c,\ud734,\ud734,\uc57c,\uc57c \ud734,\uc57c,\uc57c,\ud734,\ud734 Below is the source code of the templates: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Group Share</title> </head> <body> <p>{{ user.first_name }} opened {{ room_name }} group schedule</p> <h3>Group Members</h3> <ul> {% for member in group_members %} <li>{{ member.first_name }}</li> {% endfor %} </ul> <div id="group-schedule" class="flex"> </div> <textarea id="chat-log" cols="100" rows="20"></textarea><br> {{ room_name|json_script:"room-name" }} <script charset="UTF-8"> const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/groupshare/channel/' + roomName ); chatSocket.onopen = function(e) { const data = JSON.parse(e.data); document.querySelector('#chat-log').value += (data.message + '\n'); document.querySelector('#chat-log').value = (data.new_schedule + '\n'); console.log(data.new_schedule) }; ... ... ... Settings are all set for UTF-8. Everyone tells that UTF-8 setting will solve the problem but it hasn't worked out yet. -
I want to change status and show customer the tran id
I want to show status and successfull message after a successful payment. Here I tried SSLCOMMERZ Here I apply payment integration process: def post(self, request, *args, **kwargs): settings = { 'store_id': 'gngbdlive', 'store_pass': '5F22684A3D96651198', 'issandbox': False } customer = Customer.objects.get(id=request.session['customer']['id']) order = Order.objects.get(pk=kwargs['id']) total = order.total name = order.fname phone = order.phone address = order.address quantity = order.quantity transaction_id = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) Order.objects.filter(pk=kwargs['id']).update(transaction_id=transaction_id) sslcommez = SSLCOMMERZ(settings) post_body = {} post_body['total_amount'] = total post_body['currency'] = "BDT" # post_body['tran_id'] = "123sdf5xxxxx234asf2321" post_body['tran_id'] = transaction_id post_body['success_url'] = "https://gngbd.com/Successurl/" post_body['fail_url'] = "https://gngbd.com/user_dashboard/" post_body['cancel_url'] = "https://gngbd.com/orders" post_body['emi_option'] = 0 post_body['cus_name'] = name post_body['cus_email'] = customer.email post_body['cus_phone'] = phone post_body['cus_add1'] = address post_body['cus_city'] = "Dhaka" post_body['cus_country'] = "Bangladesh" post_body['shipping_method'] = "NO" post_body['multi_card_name'] = "" post_body['num_of_item'] = quantity post_body['product_name'] = order.product.name post_body['product_category'] = order.product.category post_body['product_profile'] = "general" response = sslcommez.createSession(post_body) return redirect(response['GatewayPageURL']) after successful payment users will redirect to success.html Here is my success.html: Your Order have Been Placed! Thank You For ordering from GNGBD.COM Your TRXID: {{tran_id}} After successful payment the status will update to PAID Here is my Order Model class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address … -
I have created the django but it is not loading my home page
I am learning django app and I am stuck. I don't know the error because the compiler is working fine but the url is not loading. Here is my code. views.py>> ''' from django.shortcuts import render def home(request): # prams={'name':'Abhinav', 'place':'Earth'} return render(request, "index.html") ''' index.html>> ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Template Home</title> </head> <body> Welcome to template: <h1>Text Analyzer : Enter your text below : </h1> <form action='/analyze' method='get'> <textarea name='text' style='margin: 0px; width: 1498px; height: 166px;'></textarea><br> <input type='checkbox' name='removepunc'>Remove Punctuations<br> <input type='checkbox' name='spaceremove'>Remove Space<br> <input type='checkbox' name='capfirst'>Capitalize First<br> <input type='checkbox' name='newlineremove'>Remove New Line <br> <button type="submit">Analyzer</button> </form> </body> </html> ''' Urls.py>> ''' from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('analyze/', views.analyze, name='analyze'),] ''' There is no error but the url is not connecting, it should show the index.html file but it is showing install app successfully , the default page of django app . Please Help I have mention my code above. -
Why does `HyperlinkedRelatedField` in Django rest framework needs its view to return `request` paramater as context?
I'm new to DRF. While defining a HyperlinkedRelatedField in serializer class, request paramater has to be returned from the related view. But i dont understand why. Someone please help me understand. -
pre-commit hook to check django migrations
I'm trying to write a pre-commit hook to my Django project that checks for missing migrations. That is, it ensures all changes are reflected in a migrations file. One way to implement this is to PASS the pre-commit hook if the makemigrations command returns no changes. $ ./manage.py makemigrations --dry-run No changes detected And to FAIL the pre-commit hook if it returns something: $ ./manage.py makemigrations --dry-run Migrations for 'myapp': myapp/migrations/0003_auto_20201213_2233.py - Alter field type on event How can I write this pre-commit hook? Is there a better approach than using makemigrations? This is what I have so far but it always passes (I think I need to parse the response): repos: - repo: local hooks: - id: pre-commit-django-migrations name: Check django migrations entry: ./manage.py makemigrations --dry-run language: system types: [python] pass_filenames: false -
Carousel Item exceeding height..or height not adjusting to carousel item
https://topqna.herokuapp.com/ The text is missing in each carousel item, each time i have to manually adjust the carousel height and add < br> to get it to work but every day's text length might be different. Is there an automatic way so that the the entire text is visible while also the gap between navbar and item is fixed. Here's the html (albeit as a django template) {% load staticfiles %} {% load static %} {% load index %} <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <nav> <div class="container nav-wrapper"> <div class="flex-container"> <h class="brand-logo center"><b>Today's Q/A</b></h> <ul id="nav-mobile" class="Center"> <li><a href="/"></a></li> </ul> </div> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script> $(document).ready(function(){ $('.carousel').carousel(); }); autoplay() function autoplay() { $('.carousel').carousel('next'); setTimeout(autoplay, 4500); } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> {#<section class="black">#} <style> html, body{ background-color: #FEDCC8; } .flex-container { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: space-evenly; } </style> <div class="flex-container"> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/kiddinglol">Cute Cat Pic <3 <i class="large material-icons left">sentiment_neutral</i> <i class="large material-icons right">sentiment_very_satisfied</i> </a> </div> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/iamonceagainsaying_your_net_sucks_sry"> C O Z Y <i class="large material-icons left">favorite</i> <i class="large material-icons right">favorite</i> … -
filter user records based on their names
I simply have a django medical website where users have their medical records and can view when logged in. I have achieved the filtering based on user that is logged in, what i want is another user(doctor) to see this records based on user(patient he selects). currently the doctor can see if the record is one(using get_object_or_404, but i want loop over many records. The models.py class Medrecs(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="meds") title = models.CharField(max_length=60, null=True) doctor = models.ForeignKey('Doctors.Doctor', null=True, on_delete=models.PROTECT) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True, null=True) meds = models.TextField() def __str__(self): return self.title Views.py def detail(request, pat_id): patient = get_object_or_404(Patient, pk=pat_id) medrecs = Medrecs.objects.all().filter(user=request.user) return render(request, 'MyDoc/detail_pat.html', {'patient': patient}, {'medrecs': medrecs}) In the view above i can see the patient records which are single records, but the medrecs(Medical records am unable to filter them based on the user(patient), it just gives me the page with the code(the template page unexecuted ). Medrecs.objects.filter(user=request.user) same case, .get will bring the number of rows and an error multipleobjects returned. As a side note i was able to filter this records in the user's(profile page) with the view: def my_profile(request): if request.user.is_authenticated: meds = Medrecs.objects.all().filter(user=request.user) return render(request, 'MyDoc/my_profile.html', {'meds': …