Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have multiple django adminsites with different themes
I have setup a django project to use both the default admin site located at /admin and then I have created a separate adminsite that is located at /special_admin. I did this by subclassing admin.AdminSite and registering models with this other admin and it works exactly as intended. However, I want to use django-jazzmin with this other admin while sticking with the standard admin theme for the default admin site. I do not know how to do this or if it is even possible. And pointers in the right direction is highly appreciated. -
QuerySet in Django
How can I perform this SQL query SELECT * FROM table_name WHERE culumm_name != value in the QuerySet of Django I tried this but isn't correct way.. enter image description here -
How to save CloudinaryField in a folder named by the user
I am trying to upload an image to cloudinary with a CloudinaryField in my models.py. I want the image to be uploaded to a folder in cloudinary named in this format : users/<username>/pictures/profile. so far I leart I can set folder and public_id of the field, but I cannot name it dynamically. for example I can pass a function in upload_to key in ImageField to create the image wherever i want. is there any way to do this with CloudinaryField ?? thanks ahead! -
How can I create a custom user in django without interfering with the default auth_user . I don't want my user table to inherit from AbstractBaseUser
I want to have a user table to add data from django rest framework and use it for all login/ logout and auth related tasks. I don't want to extend the BaseUser or the AbstractBaseUser. Is this possible? How can I do this? -
Django manipulate image Pil before save instance model
I try follow the example of this question. I need manipulate a image with PIL before save. For now i try something like: models.py from PIL import Image """function to custom path and filename""" def user_directory_path(instance, filename): ext = filename.split('.')[-1] filename = instance.product.slug+"_"+str(instance.id)+"."+ext return 'user_{0}/{1}/{2}'.format(instance.product.user.id, instance.product.id, filename) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to=user_directory_path, null=True, blank=True, default='magickhat-profile.jpg' ) def save(self): super().save() self.image_file = Image.open(self.image_file.path) self.image_file.resize((200,300)) self.image_file.save(self.image_file.path) So i take the error: AttributeError at /admin/users/product/12/change/ path -
How to filter on two different fields in on a Django query?
I have the following model in my Django project: class History(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) timestamp = models.BigIntegerField(default=0) price = models.FloatField() And I want to filter on based on the item and the timestamp. The idea is I want to check if a model instance exist or not before I create a new instance. Current I have the following: History.objects.filter(timestamp=timestamp).exists() == False: I filter based on the timestamp but I want to do something like filtering by both the item and the timestamp at the same time. For example if I have item="phone", timestamp = 1640736000 item = "phone" timestamp = 1640736000 History.objects.filter(timestamp=timestamp and item=item).exists() == False: But the above doesn't seem to work. How do i go about this? -
Can I connect to 2 layers of authentification on the same domaine?
I am building an ERP and I decided to deploy it on AWS. I already coded my frontend in REACT and my backend in python Django. They are both Dockerized and I will deploy them with on ECS Fargate and with PostgreSQL on ECR. All of this contained in a VPC. I want to create 1 VPC per client/company with their own pool of users authenticated with either Django or cognito. I'm not sure yet. But I am wondering if I can have a landing page with my domain name where clients would be signing in with a cognito pool, giving them access to their respective VPC in a subdomain. And then signing in as a user in that VPC on a different sub-pool. Won't I have a token conflict being on the same domain? I think having those 2 layers of auth would avoid chances of having clients accessing the wrong database. (example: new user created in the wrong pool) This is my first post, although I use this forum a lot. I hope it is clear. Let me know if you need more details thanks -
How Do I Restore My Django/MySQL Installation?
So Django was giving me an error when trying to access auth-api/ from the DRF application. It said it gave me a 502 or 500 error saying that it couldn't locate my mysqld file. (somewhere I var, IIRC) So I went through a tremendous ordeal of reinstalling what seemed to be a terribly broken mysqlserver installation, just to find out through troubleshooting that Django now uses a local mysql server install instead. So it seemed like everything was working properly but then I tried to access /admin and started getting a 502 error. In further troubleshooting, I tried to makemigrations and then thats when it gave me this error: NameError: name '_mysql' is not defined. Why would that be if I still had the local environment mysqlclient installed? I don't know where to go from here and I sure would appreciate any help. Does anyone have any idea how I can get my server working? -
Django decimal field fails to store floating numbers that should be ok
In a django project I'm trying to store a calculated decimal value, but it fails for some strange reason. My model looks something like: class FancyModel(models.Model): fancy_field = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True) Sometimes, rather often actually, it crashes on save: django.db.utils.IntegrityError: CHECK constraint failed: myapp_fancy_model which I found out after some digging was caused by this validation: django.core.exceptions.ValidationError: {'fancy_field': ['Ensure that there are no more than 2 decimal places.']} I've dumped the values of the actual model, and it seems ok to me: {'fancy_field': 3.26 } I cannot see how this would fail. Sometimes it works fine, other times it crashes. I've tried to use the round-method, like: model_instance.fancy_model = round(floating_value, 2) but it still fails. -
Docker and CloudSQL proxy
I'm having problems connecting my Django server to my Postgres database hosted on Google Cloud through CloudSQL Proxy with Docker. Currently, I have a Docker compose file that looks like this version: '3' services: cloud-sql-proxy: image: gcr.io/cloudsql-docker/gce-proxy command: /cloud_sql_proxy --dir=/cloudsql -instances=gamr-335802:us-central1:gamr=tcp:0.0.0.0:5432 -credential_file=/django_backend/gamr-335802-e8f23fcc176c.json ports: - "5432:5432" volumes: - /cloudsql:/cloudsql - ./gamr-335802-e8f23fcc176c.json:/django_backend/gamr-335802-e8f23fcc176c.json restart: always gamr-backend: build: ./ command: ./runner.sh volumes: - .:/django ports: - "8000:8000" depends_on: - cloud-sql-proxy I think it may be an issue with the volumes of the cloud-sql-proxy but I'm not certain. I get an error that looks like this cloud-sql-proxy_1 | 2021/12/28 22:21:17 current FDs rlimit set to 1048576, wanted limit is 8500. Nothing to do here. cloud-sql-proxy_1 | 2021/12/28 22:21:17 using credential file for authentication; email=serviceacc@gamr-335802.iam.gserviceaccount.com cloud-sql-proxy_1 | 2021/12/28 22:21:18 Listening on 0.0.0.0:5432 for gamr-335802:us-central1:gamr cloud-sql-proxy_1 | 2021/12/28 22:21:18 Ready for new connections cloud-sql-proxy_1 | 2021/12/28 22:21:18 Generated RSA key in 389.763737ms gamr-backend_1 | Performing system checks... gamr-backend_1 | gamr-backend_1 | System check identified no issues (0 silenced). gamr-backend_1 | Traceback (most recent call last): gamr-backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection gamr-backend_1 | self.connect() gamr-backend_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner gamr-backend_1 | return func(*args, **kwargs) gamr-backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 211, in connect … -
Django TypeError: InstagramBot() takes 1 positional argument but 2 were given
I am confused as to why I am getting to 2 positional arguments when I simply just run the code below, it works perfectly fine but when I receive the inputs from Django I have 2 positional arguments. Test.py from InstagramBot import InstagramBot X = InstagramBot("equinox_api", "Blast123!") InstagramBot.get_following_of_user(X) Views.py def InstagramBot(request): if request.method == "POST": form = InstagramForms(request.POST) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = {'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,'response': recaptcha_response} data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) if result['success']: form.save() email = request.POST.get('username', '') password = request.POST.get('password1', '') username = form.cleaned_data.get('username') X = InstagramBot(f"{email}", f"{password}") InstagramBot.get_following_of_user(X) messages.success(request, f'Hi {username}, your account was created successfully') print(f"username: {email}, password: {password} ") return redirect('home') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') else: form = InstagramForms() return render(request, 'users/instagramBot.html', {'form': form}) InstagramBot.py #Some of these imports may not be required from instapy import InstaPy from instapy import smart_run from os.path import join import sys import os import time import traceback class InstagramBot(): def __init__(self, username, password): self.username = username self.password = password def get_following_of_user(self): session = InstaPy(username = self.username, password = self.password, headless_browser = False, multi_logs=True) with smart_run(session): session.grab_following(username=self.username, amount="full", live_match=False, store_locally=True) number_of_following = session.grab_following(username=self.username, amount="full", live_match=False, … -
display only some fields in get api response django serializer
I have an example model which has a fk relation with user model and Blog model. Now I have a get api which only requires certain fields of user to be displayed. My model: class Example(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name="user_examples", ) blog = models.ForeignKey( Blog, on_delete=models.CASCADE, null=True, related_name="blog_examples", ) /................./ Now my view: class ExampleView(viewsets.ModelViewSet): queryset = Example.objects.all() serializer_class = ExampleSerializer def list(self, request, *args, **kwargs): id = self.kwargs.get('pk') queryset = Example.objects.filter(blog=id) serializer = self.serializer_class(queryset,many=True) return Response(serializer.data,status=200) My serializer: class ExampleSerializer(serializers.ModelSerializer): class Meta: model = Example fields = ['user','blog','status'] depth = 1 Now when I call with this get api, I get all example objects that is required but all the unnecessary fields of user like password, group etc . What I want is only user's email and full name. Same goes with blog, I only want certain fields not all of them. Now how to achieve this in a best way?? -
Raw queries in Django - empty response, but shouldn't be?
I wonder if you can help me - I have obviously done something wrong in the below, but I can't figure out quite what it is. In this, the API key gets passed as a URL parameter. I then select all records from the table voxi_skills, where the username is equal to the username in voxi_apikeys (and the key matches that in the request). The key is correct and the user exists in both tables, but it's returning an empty response. The URL path is: path('api/skills_data/<str:api_key>', views.get_skills)] Have I made a mistake in the syntax that would cause this? Thanks! def get_skills(request, api_key): if request.method == 'GET': try: api_key = str(api_key) names = ('id', 'status', 'skill_name', 'creator', 'target_date', 'points') query =''' SELECT category as id, status, skill_name, creator, target_date, points FROM voxi_skills where creator = (select user from voxi_apikeys where key = %s) ''' response = serializers.serialize('json', skills.objects.raw(query, [api_key]), fields=names) except: response = json.dumps([{ 'Error': 'Not a valid API key'}]) return HttpResponse(response, content_type='text/json') -
My edit function creates a new page instead of editing the previous page views.py
I edited my views.py but I am having a bug, each time I edit the previous entry, it creates a new entry with what i edited instead of editing that copy. I've tried to retouch the possible errors. please help VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) def edit_page(request, title): if request.method == "GET": # title = request.GET.get('title') content = util.get_entry(title) form = AddPageForm(initial={"content": title}) return render(request, "encyclopedia/editpage.html", {"form": form}) else: form = AddPageForm(request.POST) if form.is_valid(): # title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) return redirect('encyclopedia:entrypage', title) return render(request, 'encyclopedia/editpage.html', {'form': form}) EDIT PAGE {% block body %} <h1>Edit {{ title }}</h1> <form action="" method="post"> {% csrf_token %} {% form %} <input type="submit" value="Submit" class="btn btn-secondary"> </form> ENTRY PAGE {% block body %} {{ content|safe }} <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Update</a> {% endblock %} URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("search", views.search, name="search"), path("add_page", views.add_page, name="addpage"), path("edit_page/<str:title>", views.edit_page, name="editpage") ] -
Django Admin - change user type (is_staff = T/F) based on group assignment
I have a django app with 3 types of user, super_user, admin, user. From django-admin panel I am assigning a user to Admin group. Admin group is a group with allowed permission. So when I am assigning a user I am changing their is_staff to True in GroupAdminForm. Problem is when I remove a user from the group I can not change those users is_staff to false. Here's my GroupAdminForm Also I see that save_m2m is being called 2 times, but I am calling it once. what is the flow of saving here ? class GroupAdminForm(forms.ModelForm): class Meta: model = Group exclude = [] users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple('users', False) ) def __init__(self, *args, **kwargs): super(GroupAdminForm, self).__init__(*args, **kwargs) old_users = None if self.instance.pk: self.fields['users'].initial = self.instance.user_set.all() old_users = self.instance.user_set.all() def save_m2m(self): print(f'Users = ', self.instance.user_set.all()) print(f'M2M Called - {self.test}') self.instance.user_set.set(self.cleaned_data['users']) def save(self, *args, **kwargs): instance = super(GroupAdminForm, self).save() all_users = self.instance.user_set.all() print('Save Called') self.save_m2m() users = self.cleaned_data['users'] if instance.name == 'Admin': for user in users: user.is_staff = True user.save() return instance -
Unsingning a signed value Django Rest
I am using web3.personal.sign(nonce, web3.eth.coinbase, callback); to sign nonce at front end but I am trying to build backend in Django Rest. Using this to unsign the signed nonce but getting an error- from django.core import signing unsigned_value = signing.loads(signed_value) error- django.core.signing.BadSignature: No ":" found in value Can anyone have any ideas about how to unsign this nonce. Thanks -
how to work with the timer to the quiz fully functionality in django
Hi I am creating a quiz app where user has to complete test within particular time, and i used the following javascript code for the timer window.onload = function begin(){ document.getElementById('timer').innerHTML = 1 + ":" + 00; startTimer(); } function startTimer() { var presentTime = document.getElementById('timer').innerHTML; var timeArray = presentTime.split(/[:]+/); var m = timeArray[0]; var s = checkSecond((timeArray[1] - 1)); if(s==59){m=m-1} if(m<0){ document.getElementById('quiz').submit(); } document.getElementById('timer').innerHTML = m + ":" + s; setTimeout(startTimer, 1000); } function checkSecond(sec) { if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10 if (sec < 0) {sec = "59"}; return sec; } the timer is working count down but i cant handle the quiz even if the time is 00 and when i refresh teh browser the time is reset...any one who have an exprince with this please help me -
Do an INSERT INTO a User table has been "extended" using django.contrib.auth.models import AbstractUser
I've cloned a Django/Angular Application and built it. The data migrations produced an empty database. I'm now attempting to set up a way to login as there is no account setup on the login page. The use of the AbstractUser is supposed to require that an email is required in place of a user name. Trying to find a way to set up the login. The User model is: class User(AbstractUser): email = None first_name = None last_name = None REQUIRED_FIELDS = [] def __str__(self): return self.email class Meta: db_table = 'User' Table Description is: Table "public.User" Column | Type | Collation | Nullable | Default --------------+--------------------------+-----------+----------+------------------------------------ id | integer | | not null | nextval('"User_id_seq"'::regclass) password | character varying(128) | | not null | last_login | timestamp with time zone | | | is_superuser | boolean | | not null | username | character varying(150) | | not null | is_staff | boolean | | not null | is_active | boolean | | not null | date_joined | timestamp with time zone | | not null | Using this description I've attempted to some add data to facilitate being able to log in. select * from "User"; id | … -
problem when I load a page using django, Page not found (404) Request Method: GET
I followed a tutorial from YouTube about django but I face a problem when I create a page and I try to load it. The server seems to run normal but when I load the page which I created I get the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/playground/hello Using the URLconf defined in storefront.urls, Django tried these URL patterns, in this order: admin/ The current path, playground/hello, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. here is the code for settings.py file from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_ko=j(tbb+7&m^e-_ti8upt9d6nt#bxl_4&2*tk-co5s!gph+h' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'storefront.urls' TEMPLATES … -
Code and render dictionary list - each key is element of a set, value is difference between two sets
The example below perfectly articulates my problem. My models are: person id name 1 Alf 2 Beauty fruit id name 1 apple 2 banana 3 cape gooseberry 4 date 5 eggplant diet id person fruit 1 Alf apple 2 Beauty apple 3 Alf banana 4 Beauty cape gooseberry 5 Alf date 6 Beauty eggplant 7 Alf eggplant 8 Alf apple 9 Beauty apple 10 Alf banana 11 Beauty cape gooseberry (Of course, the person and fruit in the Diet model are actually foreign keys in the background.) Required Any of the people did not have the full fruit diet? If so, output = dictionary list, the respective key/values pairs being such person and the missing fruit from his/her diet If not, output = "None" My thinking persons = set(Person.objects.values_list('name', flat=True).order_by('name')) available_fruit = set(Fruit.objects.values_list('name', flat=True).order_by('name')) fruit_in_diet = set(Diet.objects.filter(person_id=1).values_list('fruit_id', flat=True).order_by('fruit_id')) missing_fruit = available_fruit - fruit_in_diet Done Tested my thinking and it works, for both persons respectively - that is, individually. It works only in so far as I get a set consisting of the correct missing_fruits for each person used in the code. My questions How do I get a dictionary list as output? How do I get a single dictionary list … -
How many messages can a django channels send per seconds?
Well, I'm really confused. I have developed a notification application with django and Django channels. Now I'm confused that how much request or messages, django and Django channels can handle per second.. And also guide me how can I scale up my app.. -
How to youtube-dl video download directly to a user side not download file in local system using python Django?
I am trying to youtube videos download directly to the client-side. I don't want to store files in the local system. For that, I used the youtube-dl python library. I also want youtube-dl video download direct to AWS S3. Please help me. -
How to get value from dict in a loop in a django template
I need to get the value of totale in this dictionary dinamically: { "periodo": "2021-12", "corrispettivi": { "10.00": { "totale": -100.0, "imposta": -9.09, "imponibile": -90.91 }, "22.00": { "totale": 10773.81, "imposta": 1942.82, "imponibile": 8830.99 } }, "saldo": { "totale": 10673.81, "imposta": 1933.73, "imponibile": 8740.08 }, "ndc": 782, "ingressi": 782 }, in my template {% for entrata in entrate %} <h3>Periodo: {{ entrata.periodo }}</h3> <table style="width:100%"> <thead> <tr> <th></th> <th style="text-align:right">TOTALE</th> <th style="text-align:right">IMPOSTA</th> <th style="text-align:right">IMPONIBILE</th> </tr> </thead> <tbody> {% for corrispettivo in entrata.corrispettivi %} <tr> <th>IVA {{corrispettivo}} %</th> <td>{{corrispettivo.totale}}</td> <td>{{corrispettivo.imposta}}</td> <td>{{corrispettivo.imponibile}}</td> </tr> {% endfor %} </tbody> </table> {% endfor %} but corrispettivo.totale doesn't work i tried this guide but I don't understand how it works how can I access the value of totale? -
Introduce a ForeignKey filed in my Project Model
I have a system that uses, class MyModel(models.Model) book_classes = (("","Select"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4')) b_class = models.CharField('Form',max_length=4,choices=book_classes,default="n/a") I would like to switch it to use a foreignkey from a Klass model class Klass(models.Model): name = models.CharField(max_length=20) class MyModel(models.Model) b_class = models.ForeignKey(Klass,on_delete=models.CASCADE) The system already has a lot of data that uses class MyModel(models.Model) book_classes = (("","Select"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4')) b_class = models.CharField('Form',max_length=4,choices=book_classes,default="n/a") What effect will the change have on the already existing data? -
django channels WebsocketCommunicator TimeoutError
I am trying to run the following test: tests.py from rest_framework.test import APITestCase from myapp.routing import application from channels.testing import WebsocketCommunicator from account.models import User from rest_framework.authtoken.models import Token class Tests(APITestCase): def setUp(self): self.user = User.objects.create(email='test@test.test', password='a password') self.token, created = Token.objects.get_or_create(user=self.user) async def test_connect(self): communicator = WebsocketCommunicator(application, f"/ws/user/{self.token}/") connected, subprotocol = await communicator.connect() self.assertTrue(connected) await communicator.disconnect() application is a boilerplate instance of channels.routing.ProtocolTypeRouter (like in here: https://channels.readthedocs.io/en/latest/topics/routing.html). Everything works fine in production. The test exits with the following error: Traceback (most recent call last): File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 74, in receive_output return await self.output_queue.get() File "/usr/lib/python3.7/asyncio/queues.py", line 159, in get await getter concurrent.futures._base.CancelledError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/sync.py", line 223, in __call__ return call_result.result() File "/usr/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/usr/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/sync.py", line 292, in main_wrap result = await self.awaitable(*args, **kwargs) File "/home/projects/myapp/myapp-api/app/tests.py", line 35, in test_connect connected, subprotocol = await communicator.connect() File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/channels/testing/websocket.py", line 36, in connect response = await self.receive_output(timeout) File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 85, in receive_output raise e File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 74, in receive_output return await self.output_queue.get() File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/timeout.py", line 66, in __aexit__ self._do_exit(exc_type) File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/timeout.py", line …