Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-mathfilters: How to calculate totals with mathfilters
I need to calculate and display a sum total of maintenance and sinking funds listed on a page. My template is as follows: {% extends "base.html" %} {% load mathfilters %} <div class="container"> <div class="col-md-10 offset-md-1 mt-5"> <div class="jumbotron"> <h1 class="display-4">Unit List</h1> <hr class="my-4"> {% block content %} <form class="d-flex" role="search" action="{% url 'billing-list' %}"> <input class="form-control me-2" type="search" placeholder="Search for OWNER, PROPERTY, BLK or UNIT NUMBER" aria-label="Search" name="search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> <table class="table table-borderless"> <thead class="border-bottom font-weight-bold"> <tr> <td>Property Name</td> <td>Block</td> <td>Floor Number</td> <td>Unit Number</td> <td>Owner</td> <td>Share Value</td> <td>Ownership Start Date</td> <td>Monthly Maintenance Fee Payable</td> <td>Monthly Sinking Fund Payable</td> <td> <a href="{% url 'pdf-list' %}" class="btn btn-outline-success"> <i class="fa-thin fa-file-pdf"></i> PDF </a> <a href="{% url 'email' %}" class="btn text-secondary px-0"> <i class="fa-solid fa-envelope"></i> Email </a> </td> </tr> </thead> <tbody> {% for unit in unit_list %} <tr> <td>{{unit.property}}</td> <td>{{unit.block}}</td> <td>{{unit.floor}}</td> <td>{{unit.unit_number}}</td> <td>{{unit.owner}}</td> <td>{{unit.share_value}}</td> <td>{{unit.ownership_start_date}}</td> {% with unit.maintenance_fee_monthly as maint %} {% with unit.share_value as share %} <td>{{maint|mul:share|div:100}}</td> {% endwith %} {% endwith %} {% with unit.sinking_fund_monthly as sink %} {% with unit.share_value as share %} <td>{{sink|mul:share|div:100}}</td> {% endwith %} {% endwith %} </tr> {% endfor %} </tbody> </table> {% endblock content %} </div> </div> </div> Line items were … -
Use Django ORM in locust
I'm using locust to load test my Django application. I'm currently hardcoding certain values in my locustfile.py: GROUP_UUID = "6790f1e6-64f9-4707-aa82-d4edd64c9cc7" @task def get_single_group(self): self.client.get(f"/api/groups/{GROUP_UUID}/") This obviously fails if GROUP_UUID is not in the database, which occurs whenever I reseed my database so I'm constantly having to change these hardcoded values. It would be much better if I could dynamically fetch a group at runtime: from myapp.models import Group @task def get_single_group(self): group = Group.objects.first() self.client.get(f"/api/groups/{group.id}/") However, I'm getting the following error, which makes sense because locust doesn't know anything about Django: ModuleNotFoundError: No module named 'myapp' Is there anyway to use the Django ORM in locustfile.py or do I need to continue hardcoding data all over the place? -
Apache error "Truncated or oversized response headers received from daemon process" when using Django
We have a Django application using mod_wsgi working fine on our Ubuntu 16 instance. When we spun up a new Ubuntu 18 instance, and attempt to log into our application, we get: [Tue Jan 10 22:12:00.930300 2023] [wsgi:error] [pid 11481:tid 140103479047936] [client 10.61.23.144:61958] Truncated or oversized response headers received from daemon process 'server': /home/.../wsgi.py, referer: https://application/login/?next=/application/ [Tue Jan 10 22:12:00.931998 2023] [core:notice] [pid 6523:tid 140103626501056] AH00052: child pid 11479 exit signal Segmentation fault (11) In searching for answers, we've seen several posts suggesting that we add this line to our apache2.conf file, which we did: WSGIApplicationGroup %{GLOBAL} However, this did not address the problem. Also tried the suggestions noted on https://serverfault.com/questions/844761/wsgi-truncated-or-oversized-response-headers-received-from-daemon-process, but this also did not solve the problem. We increased Apache logging to info but aside from the "Truncated or oversized response headers" and "Segmentation fault" no other information was logged. Hoping we may have missed a trick or two. -
Django: ProfileSerializer() takes no arguments
I am trying to get the logged in user profile using django restframework api_view, i have written a simple logic to do that but it keeps showing this error that says TypeError at /api/my-profile/2/ ProfileSerializer() takes no arguments, i cannot really tell what is wrong with the code that i have written. This is the code here class MyProfileView(APIView): # queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = [permissions.IsAuthenticated] def get_object(self, pk): try: return Profile.objects.get(pk=pk) except Profile.DoesNotExist: raise Http404 def get(self, request, pk ,format=None): profile = self.get_object(pk) serializer = ProfileSerializer(profile) return Response(serializer.data) urls.py path("my-profile/<int:pk>/", MyProfileView.as_view(), name="my-profile"), -
Can't import value from .env file / Django
I got a file .env with 4 values to hide sensitive data: DATABASE_PASSWD=Password1 SECRET_KEY=Password2 VAR3=Password3 VAR4=Password4 All of above values are properly imported in Django code except the DATABASE_PASSWORD. When the DATABASES configuration is as follows: # settings.py from decouple import config # ... DB_PASSWORD=config('DATABASE_PASSWD') SECRET_KEY=config('SECRET_KEY') VAR3=config('VAR3') VAR4=config('VAR4') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': "database_name", 'USER': "database_test_admin", 'PASSWORD': DB_PASSWORD, 'HOST': "localhost", 'PORT': "5432", } } The django outputs: raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: DATABASE_PASSWD not found. Declare it as envvar or define a default value. If I hardcode password that is just the same in .env the problem is gone - the password is correct since it's my private project. Other variables works well with the same config('VAR#') function in views for example. I have no clue what could be wrong here. -
Django Template changes not reflecting
I am trying to make changes in template. everything was going fine from 1 month but now the changes are not reflecting. I have multiple apps in my project and this is just happening for one app only. Please help. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I am trying to make changes in template. everything was going fine from 1 month but now the changes are not reflecting. I have multiple apps in my project and this is just happening for one app only. Please help. -
Django AWS S3 Storages: SignatureDoesNotMatch
My settings: AWS_ACCESS_KEY_ID = 'xxx' AWS_SECRET_ACCESS_KEY = 'xxx' AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_REGION_NAME = 'eu-west-2' AWS_S3_ADDRESSING_STYLE = "virtual" AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' What I get: <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> I've tried changing access keys multiple times to no avail. Why am I getting this error? -
I got ValueError: Related model 'useraccount.user' cannot be resolved in my django app when I tried to migrate AbstractUser?
This error occurred when I try to migrate. └─$ python3 manage.py migrate 130 ⨯ Operations to perform: Apply all migrations: admin, auth, blogapp, contenttypes, forumapp, sessions, token_blacklist, useraccount Running migrations: Applying useraccount.0001_initial...Traceback (most recent call last): File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 22, in <module> main() File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards schema_editor.create_model(model) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 442, in create_model sql, params = self.table_sql(model) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 216, in table_sql definition, extra_params = self.column_sql(model, field) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 346, in column_sql field_db_params = field.db_parameters(connection=self.connection) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1183, in db_parameters target_db_parameters = self.target_field.db_parameters(connection) File … -
Django M2M Form
i try to do checkboxes in form for M2M field, but have this error, have no idea how to fix it. Google didn't help me, i tried. When i render objects as list, i can select few objects and save it, so problem is not in views.py ,but it doesn't work with checkboxes. error: “on” is not a valid value My code: forms.py class CheckoutForm(forms.ModelForm): class Meta: model = Checkout fields = ('dishes', 'user') def __init__(self, *args, **kwargs): super(CheckoutForm, self).__init__(*args, **kwargs) self.fields["dishes"].widget = CheckboxSelectMultiple() self.fields["dishes"].queryset = Dish.objects.all() -
Serialize Multiple Lists Django
I am very new to Django and I am unable to understand via documentation and online research the following problem on how to Serialize the data to the database. I have a complex JSON (trimmed) [ { "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2021-09-25" }, "value": "35929000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2020-09-26" }, "value": "39789000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2019-09-28" }, "value": "50224000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2022-09-24" }, "value": "24977000000" } ], "NetIncomeLoss": [ { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2021-09-26", "endDate": "2022-09-24" }, "value": "99803000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2020-09-27", "endDate": "2021-09-25" }, "value": "94680000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2019-09-29", "endDate": "2020-09-26" }, "value": "57411000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2021-09-26", "endDate": "2022-09-24" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "99803000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2020-09-27", "endDate": "2021-09-25" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "94680000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2019-09-29", "endDate": "2020-09-26" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": … -
Do I need to clear the prefetch cache after each Django prefetch_related?
Django mentions that this is the way to clear the prefetch cache: non_prefetched = qs.prefetch_related(None) Which you should do since now the values are loaded into memory. One problem I'm finding is that this is even persisting across requests, meaning that the data is still cached even after returning in a separate session. Is this expected behavior, or am I misunderstanding? If this is the expected behavior, does this also mean I have to clear the cache at the end of every view with the call above? -
Tox.ini does not recognize python folder?
I ran into weird issue which I have trouble solving. I have following tox.ini file: [vars] PROJECT = django_project TASKS = tasks --exclude tasks/migrations PAGES = pages -exclude pages/migrations [tox] envlist = py310, flake8, black, mypy [testenv] deps = -rrequirements.txt -rrequirements-dev.txt commands = python manage.py test [testenv:flake8] basepython=python3 deps = -rrequirements-dev.txt commands= python -m flake8 --max-line-length=100 {[vars]PROJECT} {[vars]TASKS} {[vars]PAGES} whitelist_externals = /usr/bin/python3 [testenv:black] deps = -rrequirements-dev.txt commands = black --check --diff {[vars]PROJECT} {[vars]TASKS} {[vars]PAGES} [testenv:mypy] deps = -rrequirements-dev.txt commands = mypy --install-types --non-interactive \ --ignore-missing-imports \ --disallow-untyped-defs \ --disallow-incomplete-defs \ --disallow-untyped-decorators {[vars]PROJECT} {[vars]TASKS} {[vars]PAGES} The black commands works as expected for PAGES, but the commands flake8 and mypy are returning following error: error: unrecognized arguments: pages -exclude pages/migrations Does anyone have any idea what could be causing this? -
Could not parse the remainder: '{%get(gender='F')%}.fullname' from 'x.parent.{%get(gender='F')%}.fullname'
I have a problem with getting a data in template. I am writing code in python file its working. students = Student.objects.all() for x in students: print(x.parent.get(gender='M').fullname) It gets me Parent Fullname, but when i write it in template like: {% for x in students %} <td class="small d-none d-xl-table-cell text-center">{{ x.parent.{%get(gender='F')%}.fullname }}</td> {% endfor %} it gets me Could not parse the remainder: '{%get(gender='F')%}.fullname' from 'x.parent.{%get(gender='F')%}.fullname' error. I tried write it like {{ x.parent.get(gender='F').fullname }} but i get same error Same code working in python file but not working in template. -
videojs player seek buttons works in other browsers but not in chrome. The video starts again on clicking the progress bar
I'm fetching a video from s3 bucket using django(backend) and then playing the video in react (frontend) but the seek controls work in other browsers but not in chrome. The video starts again on clicking the progress bar or clicking the arrow keys. I don't understand what seems to be the problem. here is my django code for fetching video class GenericFileOperation(APIView): def get(self, request, material_type=None, course_id=None, format=None): key = request.GET.get('key') download = request.GET.get('download') if key is not None: s3_obj = download_assessment_file(key) splited_path = key.split("/") file_name = splited_path[len(splited_path)-1] contents = s3_obj['Body'].read() temp = tempfile.TemporaryFile() temp.write(contents) temp.seek(0) mime_type, _ = mimetypes.guess_type(key) response = HttpResponse(temp, content_type=mime_type) if download is not None: response['Content-Disposition'] = "attachment; filename=%s" % ( file_name) response['X-Frame-Options'] = "*" return response here is my code for videojs in react import React, { useEffect, useRef } from 'react' import VideoJs from 'video.js' import 'video.js/dist/video-js.css'; import "videojs-hotkeys"; import 'videojs-seek-buttons' const videoJsOptions = { controls: true, autoplay: false, fluid: true, loop: false, playbackRates: [0.5, 1, 1.5, 2], aspectRatio: '12:5', plugins: { seekButtons: { forward: 30, back: 10 }, hotkeys: {} } } const VideoPlayer = ({ url, fileType }) => { const videoContainer = useRef() useEffect(() => { videoContainer.current.innerHTML = ` <div data-vjs-player> … -
How do I make ManyToManyField limit_choices_to equal to request.user (Django)?
I should limit choices of manytomanyfield to logged in admin user profile, in django admin. class News(models.Model): title=models.CharField(max_length=200) users=models.ManyToManyField(User, blank=True, limit_choices_to={"profile__school": "request.user.profile.school"}) I have tried to implement it in admin.ModelAdmin, where I can access request.user, but couldn't find a way to do it. -
How to color value in list with django?
I am using the django framework. And I have a list with values. And the values from that list are displayed on a template. So this is the list: self.list_school_values = [ "12bg00", "Basisschool Vroonestein", "Lohengrinhof 1517, 3438RA NIEUWEGEIN Utrecht", "Lohengrinhof 1517, 3438RA NIEUWEGEIN Utrecht", "mevr. W.M. van den Brink", "030-6037291", "info@vroonestein.nl", "196", "Verdi import B.V.", "dhr. Kees Kooijman", "Koopliedenweg 38 , 2991 LN BARENDRECHT", "verdi@qualitycontrolsystems.nl", ] and the template looks: <div class="form-outline"> <div class="form-group"> <div class="wishlist"> <table> <tr> <th>Gegevens school </th> <th>waardes school contract</th> </tr> {% for value0, value1 in content %} <tr> <td> {{value0}} </td> <td class="{% if value1 == '12bg00' %}red {% endif %}"> {{value1}} </td> </tr> {% endfor %} </table> </div> </div> </div> and css: .red { color: red; } But the value is not colored red. Question: how to color the value from the list red? -
Why is django not showing multiple error messages?
When my form has multiple error messages it only show the first one. Forms.py code: class LoginForm(AuthenticationForm): error_messages = { "invalid_login": _("Incorrect login details. Try again"), "inactive": _("This account is inactive."), } I'm just using the normal Auth form but overwriting the already existing error messages so the message says something different. Template code: <form method="POST"> {% csrf_token %} {{ form }} <button type="submit">Log in</button> </form> When a inactive user tries to login the form returns this: {'invalid_login': 'Incorrect login details. Try again', 'inactive': 'This account is inactive.'} While the user did fill in the right details. And this is the only error that gets shown: <ul class="errorlist nonfield"><li>Incorrect login details. Try again</li></ul> I want it to show either both or the inactive error message since I find that more important to know. -
I am new to django and react integrating both using webpack 5
I am following this tutorial https://medium.com/codex/how-to-integrate-react-and-django-framework-in-a-simple-way-c8b90f3ce945 using webpack to integrate react and django getting this error in when runnning python server Performing system checks... System check identified no issues (0 silenced). January 11, 2023 - 01:00:29 Django version 4.0.3, using settings 'music_controller.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [11/Jan/2023 01:00:30] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:30] "GET /%7B%20%%20static HTTP/1.1" 404 2376 [11/Jan/2023 01:00:36] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:36] "GET /%7B%20%%20static HTTP/1.1" 404 2376 [11/Jan/2023 01:00:37] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:37] "GET /%7B%20%%20static HTTP/1.1" 404 2376 [11/Jan/2023 01:00:37] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:37] "GET /%7B%20%%20static HTTP/1.1" 404 2376 [11/Jan/2023 01:00:37] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:38] "GET /%7B%20%%20static HTTP/1.1" 404 2376 build using webpack PS C:\Users\harshit\Desktop\tutorial\React-Django\music_controller\frontend> npm run dev frontend@1.0.0 dev webpack --mode development --watch asset main.js 1.12 MiB [compared for emit] (name: main) asset runtime.js 7.19 KiB [compared for emit] (name: runtime) Entrypoint main 1.12 MiB = runtime.js 7.19 KiB main.js 1.12 MiB runtime modules 3.42 KiB 7 modules cacheable modules 1.08 MiB … -
why is when i do put request using django rest framework i got 200 but when i try to see one of fields it shows null using get request not the put one
i was trying to do put request on postman and its scussec but when i try the get method to get same result one of the fields which's car_ year shows null i was trying to do put request on postman and its scussec but when i try the get method to get same result one of the fields which's car_ year shows null from django.shortcuts import render from django.http import HttpResponse,JsonResponse from rest_framework.parsers import JSONParser from .models import Driver from .serializers import DriverSerializer from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from rest_framework import generics from rest_framework import mixins from rest_framework.views import APIView # Create your views here. class GenericAPIView(generics.GenericAPIView,mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,mixins.RetrieveModelMixin,mixins.DestroyModelMixin): serializer_class = DriverSerializer queryset = Driver.objects.all() lookup_field = 'id' def get(self,request,id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self,request): return self.create(request) def put(self,request,id=None): return self.update(request,id) from django.db import models # Create your models here. class Driver(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=100) phone_number=models.IntegerField(max_length=None) car_model=models.CharField(max_length=100) car_year=models.IntegerField(max_length=None) def __str__(self): return self.name from rest_framework import serializers from .models import Driver class DriverSerializer(serializers.ModelSerializer): class Meta: model=Driver fields=['id','name','email','phone_number','car_model','car_year'] ``` -
There seems to be a problem with Django Urls?
When ever I run python manage.py runserver, I get a message in the terminal "Not Found: /base/". I do not have this in my urls to start off with anyways so why am I seeing this? Below is what shows up when I run the server. And my url server is default to "http://127.0.0.1:8000/base/" instead of "http://127.0.0.1:8000". Using the URLconf defined in cric_manager.urls, Django tried these URL patterns, in this order: admin/ manager/ The current path, base/, didn’t match any of these. I tried to restart the termnial, VSCODE, and the webpage, but nothing seems to be working. Its getting a little bit annoying. -
How to display name of table from queryset in django
Trying to get the table name in django, I need it to display the detailview correctly via if statemnet. I have such a view to display class Home(ListView): template_name = 'home.html' def get_queryset(self): qs1 = Book.objects.all() qs2 = CD.objects.all() qs3 = Film.objects.all() queryset = sorted(list(chain(qs1, qs2, qs3)), key=operator.attrgetter('title')) return queryset and it returns to me this [<CD: Music1>, <CD: Music2>, <Book: Some books>] How can I get "CD" or "Book" in this template {% block content %} <div class="row"> {% for object in object_list %} <div class="col-md-3"> <div class="card card-product-grid"> <img src="{{ object.image.url }}"> <a href="{% url 'DetailBook' object.pk %}" class="title">{{ object.title }}</a> </div> </div> {% endfor %} </div> {% endblock content %} At the same time, if it's a bad idea to display detailview and listview and it's done differently, I'd appreciate it if you'd let me know I tried different ways of displaying object.key in a loop but it didn't work very well. And other queryset queries. -
'QuerySet' object is not callable
I have this function that must get the class code, and then look for this class in the database, then fill in the participant field of this class with the user who is authenticated. `def participar(request): cc = nameUser(request) if request.method == 'POST': busca = request.POST.get('busca') turma = Turma.objects.filter(codigo=busca) obj = turma(participantes=request.user) obj.save() else: return render(request, 'turmas/participar.html', cc) return render(request, 'turmas/participar.html', cc)` but when trying to add the following error occurs on the line turma(participantes=request.user) 'QuerySet' object is not callable what was expected is that after searching for the desired class by its code, the authenticated user would be added to the participant field of that class -
Django password reset PasswordResetConfirmView
View: def f_forget_password(request): ctx = dict() if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): to_email = password_reset_form.cleaned_data['email'] to_email=to_email.lower() associated_users = User.objects.filter(Q(email=to_email)) if associated_users.exists(): if len(associated_users)!=1: return HttpResponse('Email Is Invalid.') current_site = get_current_site(request) for user in associated_users: mail_subject = "Password Reset Requested" email_template_name = "password/password_reset_email.txt" uid=urlsafe_base64_encode(force_bytes(user.pk)) c = { "email":user.email, 'domain':current_site.domain, 'site_name': 'mysit', "uid": uid, "user": user, 'token': account_activation_token.make_token(user), } try: message = loader.render_to_string(email_template_name, c) email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() except Exception as e: return HttpResponse('Invalid header found.<br/>') return redirect ("/password_reset/done/") else: return HttpResponse('Email not found.') template = loader.get_template('password/forget_password.html') response = HttpResponse(template.render(ctx, request),content_type='text/html') return response url: path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='password/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'), token.py: class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() view PasswordResetConfirmView dont work and my password dont change. when i clicked on passwordresetlink i have an Error: Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. -
Using delphi API from django based website
So, I am a beginner in Django I have a Desktop application Api (Delphi based app) in DLL format And I am trying to build a webpage that interact with this desktop App is there any way to do that?? if the answer in a No way, how can I use DLL API To Interact with this app using Kivy or PyQT5 or any python framework PS: I don't have any knowledge of Delphi I didn't try anything I'm just wondering if my idea is doable -
How to get the currently logged in user in django restframework?
I am trying to get the currently logged in user using django restframework and i have written a simple APIView to do this, but when i access the api_view it shows {"detail": "Authentication credentials were not provided."}, how do i provide the authentication credentials? because i have tried loggin in use the login API i created and it show the current access token but when i access the my-profile view it shows that i need to login? How do i provide the authentication details, login and see the user information maybe (username and email) class MyProfileView(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request): user = User.objects.get(request.user) return Response(user.data)