Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django authentication check.password doesn't work
check.password doesn't work and this is the error message : Internal Server Error: /api/login Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python310\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Python310\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Python310\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python310\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Python310\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\test\auth\users\views.py", line 24, in post if not user.check_password(password): File "C:\Python310\lib\site-packages\django\contrib\auth\base_user.py", line 115, in check_password return check_password(raw_password, self.password, setter) File "C:\Python310\lib\site-packages\django\contrib\auth\hashers.py", line 55, in check_password must_update = hasher_changed or preferred.must_update(encoded) File "C:\Python310\lib\site-packages\django\contrib\auth\hashers.py", line 332, in must_update decoded = self.decode(encoded) File "C:\Python310\lib\site-packages\django\contrib\auth\hashers.py", line 308, in decode algorithm, iterations, salt, hash = encoded.split("$", 3) ValueError: not enough values to unpack (expected 4, got 3) [10/May/2022 18:10:48] "POST /api/login HTTP/1.1" 500 101753 this is the views: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from .serializers import UserSerializer from .models import User class RegisterView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): … -
Is there a way to get if the user is on a particular heading, paragraph or a div etc
I was trying to find a way to start an animation only if the user is on it, at first I tried getting screen size, and its works. Once I was googling I found something where we could get ID (by the ID tag) while scrolling, if somehow I could get the ID while scrolling down, I could use a simple JavaScript function to play the animation. is there any way? -
request.COOKIES is empty when Django Rest Framework API hit from React JS but works in Postman
I have implemented JWT Authentication in Django Rest Framework and using React JS as frontend. The issue is, When i test my API in Postman everything works. I send email and password to /login, it returns jwt token and set_cookies with http_only = True, UserView simple fetches that jwt token form cookies and returns the user. See the image of working backend. JWT token returned and COOKIE is set. And userview gives the User back as shown in image... But when i call this API into React JS, The Login Works but UserView doesn't get any Token hence gives error 401. Why this happening? Please see my code -
AWS Beanstalk Django Web App not serving static files when using CLI - Works fine using AWS Console UI
I am trying to use AWS Beanstalk CLI to deploy a Django web application using the command line but I am not able to serve properly the static files. This is my configuration file (.elasticbeanstalk/config.yml): branch-defaults: aws-cli: environment: gather-api-environment group_suffix: null environment-defaults: gather-api-environment: branch: null repository: null global: application_name: gather-api-application branch: null default_ec2_keyname: beanstalk default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: eu-central-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: DataArchitect repository: null sc: git workspace_type: Application option_settings: aws:elasticbeanstalk:container:python: WSGIPath: cdm_api.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /static: /static/ packages: yum: postgresql-devel: [] However, when I load this folder as a zip file using the AWS UI console ("Upload and deploy button"), it works. Here is my .ebextensions/django.config file: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: cdm_api.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /static: /static/ Any suggestions? Let me know if more information is needed. Thanks in advance! -
re-write a function-based view to a class-based view
I am trying to re-write my Django Application, so it is using the Django Rest Framework, but I need a little help to understand how I re-write a post view function to a class-based view. first a have the function-based view I would like to re-write: def make_transfer(request): assert not request.user.is_staff, 'Staff user routing customer view.' if request.method == 'POST': form = TransferForm(request.POST) form.fields['debit_account'].queryset = request.user.customer.accounts if form.is_valid(): amount = form.cleaned_data['amount'] debit_account = Account.objects.get(pk=form.cleaned_data['debit_account'].pk) debit_text = form.cleaned_data['debit_text'] credit_account = Account.objects.get(pk=form.cleaned_data['credit_account']) credit_text = form.cleaned_data['credit_text'] try: transfer = Ledger.transfer(amount, debit_account, debit_text, credit_account, credit_text) return transaction_details(request, transfer) except InsufficientFunds: context = { 'title': 'Transfer Error', 'error': 'Insufficient funds for transfer.' } return render(request, 'BankApp/error.html', context) else: form = TransferForm() form.fields['debit_account'].queryset = request.user.customer.accounts context = { 'form': form, } return render(request, 'BankApp/make_transfer.html', context) The TransferForm look like this: class TransferForm(forms.Form): amount = forms.DecimalField(label='Amount', max_digits=10) debit_account = forms.ModelChoiceField(label='Debit Account', queryset=Customer.objects.none()) debit_text = forms.CharField(label='Debit Account Text', max_length=25) credit_account = forms.IntegerField(label='Credit Account Number') credit_text = forms.CharField(label='Credit Account Text', max_length=25) def clean(self): super().clean() # Ensure credit account exist credit_account = self.cleaned_data.get('credit_account') try: Account.objects.get(pk=credit_account) except ObjectDoesNotExist: self._errors['credit_account'] = self.error_class(['Credit account does not exist.']) # Ensure positive amount if self.cleaned_data.get('amount') < 0: self._errors['amount'] = self.error_class(['Amount must be positive.']) return self.cleaned_data … -
How to use fcm-django?
I'm just new in django-fcm. Can anyone give a step by step how to setup django-fcm package ? I want to push notification to web browser, when user allow notification from my website. Thank You -
How to send list of dictionaries on Httpresponse back to ajax client and unpack the lot received
I want to send a List of dictionaries from Httpresponse in Json back to the ajax and from there unravel the pack so that I can produce a list of tables. I have the code to send for 1 dictionary as well as to unravel one dictionary And to produce One table. Since I need to produce several tables (one for each model, I don't know what the syntax is for unpacking the list of dictionaries received in json format. Once I have them unpacked, I already know how to make a table out of one in Javascript. For 1 dictionary and 1 table I do like this: dictionary = { "key1": "value1", "key2": "value2" } json_dict = json.dumps(dictionary) return HttpResponse(json_dict) and then unpack like this: . ... .... datatype:'json' }).done(function(data) { obj = JSON.parse( data); How can I get obj1, obj2, obj3 etc (corresponding each to a dictionary, a model and will become a table) -
Django didn't create table fields in MySQL
I'm working on a blog project. There is an app called "blog" with one single model. The code of the models.py is below: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Articles(models.Model): title = models.CharField(max_length=200), author = models.ForeignKey(User, on_delete=models.CASCADE), text = models.TextField(), created_date = models.DateTimeField(timezone.now), published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title I added the app to the INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] Still, Django only created the id field (created automatically) and the published_date field. This never happened before. Any idea about what's the problem here? -
Django: Crispy forms on django-filters removes selected on drop-down lists
Why does | crispy remove the selected attribute on drop-down lists of my filters? It does not show the currently applied filter. Given the following filter.py: from .models import Task import django_filters class TaskFilter(django_filters.FilterSet): class Meta: model = Task fields = ["status"] I'm calling the following URL: http://localhost:8000/task/?status=30 With {{ filter.form }} is generated the following output: <select name="status" id="id_status"> <option value="" >---------</option> <option value="10" >Overdue</option> <option value="20" >Due</option> <option value="30" selected>Pending</option> <option value="40" >Inactive</option> </select> ... With {{ filter.form | crispy }} is generated the following output, which is missing the selected value: <select class="bg-white ..." name="status" > <option value="" >---------</option> <option value="10" >Overdue</option> <option value="20" >Due</option> <option value="30" >Pending</option> <option value="40" >Inactive</option> </select> Any idea why the selected is no longer in place and the id="id_status" is gone? -
How to save ProductAttributesvAlues in Django Oscar Commerce
I'm trying to save m2m relation in Product model on Django Oscar Commerce package, the model has an many to many relation through the ProductAttributeValues model. Making Postan POST method query to url 127.0.0.1:8000/api/products/1/update/ serializers.py: class ProductAttributeValueSerializer(OscarModelSerializer): class Meta: model = ProductAttributeValue fields = '__all__' class ProductSerializer(OscarModelSerializer): attributes = ProductAttributeValueSerializer(many=True, read_only=False) class Meta: model = catalogue_models.Product fields = '__all__' The json content: { 'title': 'Producto 4', 'is_public': True, 'description': 'descripción', 'attributes': [ {'value_text': 'contenido', 'attribute': 1, 'product': 1}, {'value_text': 'contenido', 'attribute': 2, 'product': 1} ] } Anybody could help me please ? Thanks in advance. -
ArangoDB query find name consisting of two or more parts
i am quite new to arangodb and AQL. What i am trying to do is to find names and surnames with query that have two or more parts that may or may not include spaces (" ") to divide those said parts. As i went through documents, I figured that those fileds should be indexed as full-text indexes and query would be something like FOR u IN FULLTEXT(collection, field, "search") RETURN u Now my question is how to utilize the above query for a Persian/Arabic names such as سید امیر حسین Keep in mind that this name comes from an input of a user and it could be in the following formats such as سید امیر حسین/سید امیرحسین/سیدامیر حسین/سیدامیرحسین Note the various types of names with/without spaces. I tried the follwoing query F FOR u IN FULLTEXT(collection, field, "سید,|امیر,|حسین,|سیدامیرحسین") RETURN u But the problem is this will also result of fetching the name because i reckon the use of OR ( | ) operator. سید محمد which is not my intention. So what am i doing wrong or missing here ? Many thanks in advance and excuse my noobiness PS : arango 3.8.3 -
How to add two foreign keys in message table of same(user) table as foreign keys?
I am trying to design a chatting app using Django rest at the backend My Model class MessageModel(models.Model): message = models.CharField(max_length=200) msg_from = models.ForeignKey(UserModel,on_delete=models.CASCADE) msg_to = models.ForeignKey(UserModel,on_delete=models.CASCADE) but it gives the following error SystemCheckError: System check identified some issues: ERRORS: message_api.MessageModel.msg_from: (fields.E304) Reverse accessor for 'message_api.MessageModel.msg_from' clashes with reverse accessor for 'message_api.MessageModel.msg_to'. HINT: Add or change a related_name argument to the definition for 'message_api.MessageModel.msg_from' or 'message_api.MessageModel.msg_to'. message_api.MessageModel.msg_to: (fields.E304) Reverse accessor for 'message_api.MessageModel.msg_to' clashes with reverse accessor for 'message_api.MessageModel.msg_from'. HINT: Add or change a related_name argument to the definition for 'message_api.MessageModel.msg_to' or 'message_api.MessageModel.msg_from'. How can I design a database table for chatting? I am using MySQL database. -
Can compile Django project to War file as boot spring
Can compile the Django project to War file as boot spring? I would like to deploy the Django project as a compiler library which is a similar WAR file of boot spring framework into the webserver? is there any way to hide or encrypt Django source code in order to deploy it into a web server? -
Return multiple fields from django model
As the title says, I want to return two fields (semester, subject) separately from semSubject model and access them in Sem1Attendance. Code as follows, models.py class semSubject(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=7, primary_key=True) category = models.CharField(max_length=9,default="Theory") sem = models.IntegerField(null=True) class Sem1Attendance(models.Model): reg_no = models.ForeignKey(Sem1Students, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices=STATUS) semester = models.ForeignKey(semSubject,related_name='sem_name', on_delete=models.CASCADE, default=1) subject = models.ForeignKey(semSubject, related_name='sub_name', on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) Is there a way to do this? -
Custom method inside Django admin does not throw its error - Why?
I have an admin view in Django which should call and display the result of a custom method. I would expect the following: if that custom method raises an error, I'll see the error popping up in my Django admin view. However, the admin view displays a dash instead: "my_custom_method: -". There is no error in the logs. I do not want to wrap every of my custom methods in a try/catch block. Is there any other way I can force Django to display that exception and quit showing that admin page? class MyAdmin(admin.ModelAdmin): readonly_fields=['my_custom_method'] def my_custom_method(_): raise AttributeError -
Django how to add static in images
How to add {% load static %} in images. example ( "{% static 'images/pic/1.jpg' %}" ) in the same time . if I have templates in html I have 50+ images how can I add {% static %} in images ? -
Get field value from inside the model class
I have a Folder class, which creates a folder when instanciated, with the parent_folder field being the location in which I want the folder to be created. class Folder(models.Model): folder_name = models.CharField(max_length=200, unique=True) parent_folder = models.FilePathField(path=r'media/', allow_files=False, allow_folders=True, recursive=True) def __init__(self, *args, **kwargs): super(Folder, self).__init__(*args, **kwargs) self.initial_filepath = self.filepath() def save(self, *args, **kwargs): on_creation = self.pk is None if on_creation: os.mkdir(self.filepath()) else: os.rename(self.initial_filepath, self.filepath()) super(Folder, self).save(*args, **kwargs) def filepath(self): return os.path.join(self.parent_folder, self.folder_name) When I go to the Django Admin page, there's no issue while creating a folder, however if I go and try to modify it, among the different choices for parent_folder, there's the folder itself, and if I select it, it causes an error because it tries renaming inside itself. My goal is then to remove the folder from the list of folders in which I can move it. I tried using the match attribute of the FilePathField, but I didn't manage to get the value of folder_name of my instance (to match any folder which doesn't contain the name of the folder I'm moving). So if you could help me get the value of folder_name of my instance that would be really appreciated ! -
End Session When browser is closed in python django and javascript
I have created logout def in python, in that def I am deleting session that I have created after login the user. I wish to end/del session when the user closes the browser using(X) OR using(alt+4). how do I call logout url in javascript when user close the browser. Here is def logout: @login_required def logout(request): username = request.session['username'] ip = settings.IP headers = settings.HEADERS del request.session['username'] Here is urls.py from django.urls import path from . import views urlpatterns = [ path('logout', views.logout, name="logout"), ] -
Django/Docker/Postgresql: app connected to the 'wrong' database
I have develop a project with Django/Docker/Postgresql and use docker-compose to deploy on a linux remote server. I want to deploy 2 apps based on the same code (and same settings file), preprod and demo, with two disctincts PostgreSQL databases (databases are not dockerized): ecrf_covicompare_preprod and ecrf_covicompare_demo, respectively for preprod and demo. Apps tests will be done by differents teams. I have : 2 docker-compose files, docker-compose.preprod.yml and docker-compose.demo.yml, respectively for preprod and demo .env files, .env.preprod and .env.preprod.demo, respectively for preprod and demo Databases parameters of connection are set in these .env files. But my 2 apps connect to the same database (ecrf_covicompare_preprod). docker-compose.preprod.yml version: '3.7' services: web: restart: always container_name: ecrf_covicompare_web build: context: ./app dockerfile: Dockerfile.preprod command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - app_volume:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.preprod entrypoint: [ "/usr/src/app/entrypoint.preprod.sh" ] depends_on: - redis healthcheck: test: [ "CMD", "curl", "-f", "http://localhost:8000/" ] interval: 30s timeout: 10s retries: 50 redis: container_name: ecrf_covicompare_redis image: "redis:alpine" celery: container_name: ecrf_covicompare_celery build: context: ./app dockerfile: Dockerfile.preprod command: celery -A core worker -l info volumes: - app_volume:/usr/src/app env_file: - ./.env.preprod depends_on: - web - redis celery-beat: container_name: ecrf_covicompare_celery-beat build: context: ./app dockerfile: Dockerfile.preprod command: celery -A core … -
django aggregate between 2 different querysets
So I have 2 query sets that are from the same model but different records. I already made the pythonic way of getting the result. but I want to do it with aggregate and annotate to get this done. result = [i for i in self.old_searches if round( abs(same_keys.get(keyword =i.keyword).current_position-i.current_position)) >=1] so both of self.old_searches and same_keys have the same field called current_position and for example I need first recprd of the first query be compared with first record second one. but all i need is the current_position. -
Interactive drawing
I'm an enginner working on a shipyard and i'm trying to create a django based tool that helps me track production progres. Helpfull with that would be interactive drawing, I can use contractual data given by my boss, a couple of drawings of a vessel. For sure it is easy to import it as a typical src saved as png ....no biggie. But i need it to be interactive - in example if i'll get an information that area 'A' is completed then area 'A' will change it's colour to lets say green. I'm a beginner when it comes to programming so any suggestions on how to achieve my goal will be helpfull. -
Loop through objects in template and set each elements background image to object's ImageField value using tailwind css
From the tailwind docs, to set the background image to an 'Arbitrary value': <div class="bg-[url('/img/hero-pattern.svg')]"> <!-- ... --> </div> In my template, I am trying to loop through a list of Artist objects and build cards for each one. Artist objects all have a profile_picture attribute which is an ImageField: {% for artist in artists %} <div class="bg-[url('{{artist.profile_picture.url}}')]"> <a href = "{{artist.profile_picture.url}}">Link to Image</a> <!-- put this here to make sure the url is correct and this does take me to the image --> <h1>Some text</h1> </div> {% endfor %} And this is not applying the background image. I can confirm the url is correct because I have inspected the page: <div class="bg-[url('/media/images/artists/headshot.jpeg')]"> <h1>Some text</h1> </div> and visited http://127.0.0.1:8000/media/images/artists/headshot.jpeg where I do see the image. Does anyone know what's going on here? Thanks for any help. Edit: Using Tailwind version 3.0.24 -
Throttling is also restart as our django server restart
i need help of yours. I want to limit my GET API. firstly i can hit this API only for one time(forever with the same system) then i signup then i can hit this same API for 5 times(forever with the same system) then i have to pay some amount then i can hit infinite times. At this time no throttle is used. Below is my code:- Settings.py 'DEFAULT_THROTTLE_RATES': { 'Auserlimit': '1/infinite', 'userlimit': '5/infinite', } throttling.py:- from rest_framework.throttling import AnonRateThrottle, UserRateThrottle import random class limitAUserThrottle(AnonRateThrottle): scope = 'Auserlimit' def parse_rate(self, rate): """ Given the request rate string, return a two tuple of: <allowed number of requests>, <period of time in seconds> """ if rate is None: return (None, None) num, period = rate.split('/') num_requests = int(num) duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400, 'i': 315360000000}[period[0]] return num_requests, duration class limitUserThrottle(UserRateThrottle): scope = 'userlimit' def allow_request(self, request, view): if not request.GET.get('call_type') == 'seu': self.scope = 'userlimit' self.rate = '5/infinite' return True return super().allow_request(request, view) def parse_rate(self, rate): """ Given the request rate string, return a two tuple of: <allowed number of requests>, <period of time in seconds> """ if rate is None: return (None, None) num, period = … -
I Face Following below when install Project in pycharm in Django 'A server error occurred. Please contact the administrator.'
please help me what is the main problem face fallowing error throw which I run Django server A server error occurred. Please contact the administrator. Traceback (most recent call last): File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\defaulttags.py", line 1034, in find _library return parser.libraries[name] KeyError: 'staticfiles' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inn er response = get_response(request) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_re sponse response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\Restaurant_Management_System_Project_Django\hotel\views.py", line 113, in index return render(request, 'index.html', {'food':food}) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\loader.py", line 61, in render_to_s tring template = get_template(template_name, using=using) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\loader.py", line 15, in get_templat e return engine.get_template(template_name) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\backends\django.py", line 34, in ge t_template return Template(self.engine.get_template(template_name), self) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\engine.py", line 143, in get_templa te template, origin = self.find_template(template_name) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\engine.py", line 125, in find_templ ate template = loader.get_template(name, skip=skip) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\loaders\base.py", line 30, in get_t emplate contents, origin, origin.template_name, self.engine, File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\defaulttags.py", line 1038, in find _library name, "\n".join(sorted(parser.libraries)), django.template.exceptions.TemplateSyntaxError: 'staticfiles' is not a … -
How to aggregate distinct values of one key then sum the matching values of the other key?
I've made a loop that gives me data in the following format: name_quant = [{'name_id': 'S00004', 'quantity': '1'}, {'name_id': 'S00004', 'quantity': '2'}, {'name_id': 'S00003', 'quantity': '1'}, {'name_id': 'S00003', 'quantity': '2'}, {'name_id': 'S00003', 'quantity': '2'}, {'name_id': 'S00002', 'quantity': '1'}] I used the following loop to get the values above: namesequence = EventSequence.objects.filter(description="names").values("Details") name_quant = [{ 'name_id': e['element'][33:39], 'quantity': e['element'][50:51] } for e in namesequence ] So my question is how can I aggregate the name_ids and sum the quantities of matching name_ids so that i get a result like so: name_sum = [{'name_id': 'S00001', 'quantity': '160'}, {'name_id': 'S00002', 'quantity': '50'}, {'name_id': 'S00003', 'quantity': '40'}, {'name_id': 'S00004', 'quantity': '90'}] I would have used the sum function in Django but I have to subscript and loop though the value first which makes it a bit more complicated :/ Any help is appreciated!