Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: do_something_on_deactivation() missing 1 required positional argument: 'instance_id' in django
Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\OneDrive\Desktop\GFG\gfgvenv\lib\site-packages\activatable_model\models.py", line 109, in save model_activations_changed.send(self.__class__, instance_ids=[self.id], is_active=current_activable_value) File "C:\Users\OneDrive\Desktop\GFG\gfgvenv\lib\site-packages\django\dispatch\dispatcher.py", line 182, in send for receiver in self._live_receivers(sender) File "C:\Users\OneDrive\Desktop\GFG\gfgvenv\lib\site-packages\django\dispatch\dispatcher.py", line 182, in <listcomp> for receiver in self._live_receivers(sender) TypeError: do_something_on_deactivation() missing 1 required positional argument: 'instance_id' I am getting this error when I am saving my Django custom model object. This is my Model.py file from django.db import models # Create your models here. class MyModel(models.Model): username = models.CharField(max_length=15) pass1 = models.CharField(max_length=50) is_active = models.BooleanField(default=False) In the python manage.py shell I ran >>>from authentication.models import MyModel >>>obj = MyModel.objects.all()[0] >>>obj.is_active = True >>>obj.save() Not sure where I am wrong, even though it throughs an error, the changes are being made -
DJango + nginx + gunicorn: how to start caching and which way is more standard?
I deployed my Django project using Gunicorn, but now can't use Nginx caching. How to start caching on a project that use Gunicorn and which caching method is standard for Django. -
Django. Annotate queryset to get amount of relations with other model
I have models Question, Answer, Form and FormAnswer. models were simplified to shorten reading time class Question(models.Model): text = models.CharField(max_length=255) class Answer(models.Model): question = models.ForeignKey(Question, models.CASCADE) text = models.CharField(max_length=255) class Form(models.Model): user = models.ForeignKey(CustomUser, models.CASCADE) class FormAnswer(models.Model): form = models.ForeignKey(Form, models.CASCADE) question = models.ForeignKey(Question, models.CASCADE) answer = models.ForeignKey(Answer, models.CASCADE) I'd like to be able to annotate stats like this: Form.stats -> { 1: { # Question.pk 2: 5 # Answer.pk: how much times this question # was answered with this answer via FormAnswer model 3: 11, 4: 1, }, 2: { 5: 1, 6: 2, 7: 9, }, } SQL alternatives would also be helpful -
How to write the mark_safe fun for this class based view
I wanted to return mark_safe for the below API so how can i do that class AboutUsViewSet(viewsets.ModelViewSet): queryset = AboutUs.objects.all() serializer_class = AboutUsSerializer def get_permissions(self): if self.request.method == 'GET': self.permission_classes = [AllowAny, ] else: self.permission_classes = [IsAuthenticated, ] return super(AboutUsViewSet, self).get_permissions() -
is there any 'safe' keyword of django template filter in python or javascript?
I'm using ckeditor for description field which allow user to format text this is what saving in my description field: <div class="ql-editor" data-gramm="false" data-placeholder="Compose an epic..." contenteditable="true"> <p><strong>Lösungen, die mit Ihrem Unternehmen wachsen. Gern berate ich Sie zu allen Steuerfragen. Vereinbaren Sie ein individuelles Informationsgespräch. Annette Wolff Ι Steuerberaterin</strong></p> </div> <div class="ql-clipboard" tabindex="-1" contenteditable="true"> </div> <div class="ql-tooltip ql-hidden"> <a class="ql-preview" target="_blank" href="about:blank"></a><input type="text" data-formula="e=mc^2" data-link="https://quilljs.com" data-video="Embed URL"><a class="ql-action"></a><a class="ql-remove"></a> </div> to show it in a proper format i'm using description|safe filter in django template which shows the descripltion like this: Lösungen, die mit Ihrem Unternehmen wachsen. Gern berate ich Sie zu allen Steuerfragen. Vereinbaren Sie ein individuelles Informationsgespräch. Annette Wolff Ι Steuerberaterin but how can i handle it with ajax call as i cannot use django template safe filter keyword. Is there any way to handle it in javascript, jquery or in python file. -
I having 5 fields but i need to search by "username" in "search field". how we can do it in DJango Application
In my application there are fields like phone, username, Address, id. but i need only details of "username" field when i search it in search box. how we can do this . can anyone help me with DJango code -
How to fix incompatible architecture for gdal while running Django server in MacOs
while running Django server by using python manage.py runserver, I'm getting following error. Could anyone please help me to fix this issue. self._handle = _dlopen(self._name, mode) OSError: dlopen(/usr/local/homebrew/opt/gdal/lib/libgdal.dylib, 0x0006): tried: '/usr/local/homebrew/opt/gdal/lib/libgdal.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/usr/local/lib/libgdal.dylib' (no such file), '/usr/lib/libgdal.dylib' (no such file), '/usr/local/homebrew/Cellar/gdal/3.3.3_1/lib/libgdal.29.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/usr/local/lib/libgdal.29.dylib' (no such file), '/usr/lib/libgdal.29.dylib' (no such file) I am having M1 Chip MacBook Pro and I have installed the gdal in /usr/local/homebrew/opt/gdal/. -
TemplateDoesNotExist at /fund_me issue
I have went through the answers to similar question on this site but nothing seems to work as i receive the same error message each time. Help would be greatly appreciated. ERROR MESSAGE ON THE BOTTOM directory tree: directory tree urls.py in fund_proj: from django.contrib import admin from django.urls import include, path from fund_me import views urlpatterns = [ path("admin/", admin.site.urls), path("fund_me", include("fund_me.urls")), ] urls.py in fund_me: from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [path("", views.say_hello)] views.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): context = {"name": "joe"} return render(request, "fund_me/templates/hello_page.html", context) settings.py (relevant code) TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "templates"), "./fund_me/templates/"], "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", ], }, }, ] error message and traceback error msg and traceback -
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