Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to read a file from storage and save as a model.FileField object?
I have a model.FileField: class MyModel(models.Model): myfile = models.FileField() I have a default file on my storage that I want to set as a default post instance creation, so I am attempting to do this with a post_save signal: @receiver(post_save, sender=MyModel) def post_save_mymodel_setup(sender, instance, created, **kwargs): if instance and created: with open('/path/to/default_file.pdf', 'r') as f: fileobj = File(f, name='default_confidential_information_memo.pdf') obj = MyModel(myfile=fileobj) obj.save() However, this results in I/O operation on closed file.. Where am I going wrong? -
How get input value to text area
Hi i wanna get input value to text in same page without submit button. Example i wanna to do: enter image description here html; <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-default" style="font-weight: 500;">Aktivite:</span> </div> <input type="text" class="form-control" name="daktivite" id="daktivite" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> -
An error occurred while packaging. Using pyinstaller
I'm trying to build a python file into a exe file. I don't get it since it builds on some days and gives errors on others. The python script works normally when I run it in CMD or Visual Code. I have tried : Reinstalling Django Reinstalling Python Reinstalling auto-py-to-exe Installing GDAL Error that comes up when trying to build the exe : Running auto-py-to-exe v2.10.1 Building directory: C:\Users\white\AppData\Local\Temp\tmphwzenqcz Provided command: pyinstaller --noconfirm --onefile --console "C:/Users/white/Desktop/Security/password.py" Recursion Limit is set to 5000 Executing: pyinstaller --noconfirm --onefile --console C:/Users/white/Desktop/Security/password.py --distpath C:\Users\white\AppData\Local\Temp\tmphwzenqcz\application --workpath C:\Users\white\AppData\Local\Temp\tmphwzenqcz\build --specpath C:\Users\white\AppData\Local\Temp\tmphwzenqcz 4527 INFO: PyInstaller: 4.5.1 4542 INFO: Python: 3.9.7 4563 INFO: Platform: Windows-10-10.0.22000-SP0 4573 INFO: wrote C:\Users\white\AppData\Local\Temp\tmphwzenqcz\password.spec 4576 INFO: UPX is not available. 4590 INFO: Extending PYTHONPATH with paths ['C:\\Users\\white\\Desktop\\Security', 'C:\\Users\\white\\AppData\\Local\\Temp\\tmphwzenqcz'] 4794 INFO: checking Analysis 4796 INFO: Building Analysis because Analysis-00.toc is non existent 4812 INFO: Initializing module dependency graph... 4830 INFO: Caching module graph hooks... 4853 INFO: Analyzing base_library.zip ... 6467 INFO: Processing pre-find module path hook distutils from 'C:\\Users\\white\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\PyInstaller\\hooks\\pre_find_module_path\\hook-distutils.py'. 6475 INFO: distutils: retargeting to non-venv dir 'C:\\Users\\white\\AppData\\Local\\Programs\\Python\\Python39\\lib' 8715 INFO: Caching module dependency graph... 8863 INFO: running Analysis Analysis-00.toc 8876 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by C:\Users\white\AppData\Local\Programs\Python\Python39\python.exe 8926 WARNING: lib not … -
Django Makemigrations and migrate successful. Dev server runs as expected. "Relation "auth_user" does not exist " when serving on Nginx
My app does everything it's supposed to (log in and associated functionality) whilst running on the dev server, being accessed over port 8000. As soon as I switch over to Nginx and try to log or access the admin dash: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... I'm on DigitalOcean running Ubuntu 20.4, Postgres and Nginx. I've tried: making migrations and migrating making migrations and migrating using the name of the specific app dropping the table and re-making migrations comparing the databases on my local machine and the server for differences My user manager and model in app.models.py: class UserManager(BaseUserManager): def create_user(self, email, password = None, active = True, staff = False, superuser = False): if not email: raise ValueError('Users must have an email') if not password: raise ValueError('Users must have a password') user = self.model(email = self.normalize_email(email)) user.set_password(password) user.staff = staff user.superuser = superuser user.active = active user.save(using=self._db) return user def create_staffuser(self, email, password = None): user = self.create_user(email, password = password, staff = True) return user def create_superuser(self, email, password = None): user = self.create_user(email, password = password, staff = True, superuser = True) return user class User(AbstractBaseUser): user_id = models.AutoField(primary_key=True) email = models.EmailField(max_length … -
How to create in django an annotate or agregate option to identify if a request.user is already in m2m relations
I have 2 days looking for a way to have a way to identify if a logged user is following or not any post. bellow my models: class User(AbstractUser): pass class Post(models.Model): user = models.ForeignKey( "User", on_delete=models.CASCADE, related_name="posts") owner = models.ForeignKey( "User", on_delete=models.PROTECT, related_name="post_posted") followers = models.ManyToManyField( "User", default=None, blank=True, related_name="posts_followers") likes = models.ManyToManyField( "User", default=None, blank=True, related_name="posts_likes") unlikes = models.ManyToManyField( "User", default=None, blank=True, related_name="posts_unlikes") content = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) The main idea is when the page is rendered by django put a buton Follow or unfollow depending if the user exist or not into the followers m2m relation. Now in the view I have a query set that I use to identify likes and unlikes numbers, this work fine but I need now the following and unfollow boton as a aditional task I need to add another boton for likes and unlikes too. # Get all post from the DB allposts = Post.objects.all().annotate(num_likes=Count( 'likes'), num_unlikes=Count('unlikes')).order_by("-timestamp") If some one can help me, I really apreciate it. ? Thanks in advance. -
Virtualenv issues,django packages
While working in django project in pycharm ,I got an error it said "install django pacakage" but I already installed django in my virtualenv.If I install global django package in pycharm will it affect my virtualenv ? -
Django and Postgres problems with dockerizing
Hello I can not dockerize my django app because I got an error - listen tcp4 0.0.0.0:5433: bind: address already in use From the other hand, when I "kill" 5433 port in ubuntu terminal I get this error Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5433? What can I do to solve this problem and dockerize successfully my app? Dockerfile FROM python:3 RUN adduser --system --no-create-home django ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . ENV PYTHONPATH /code EXPOSE 8000 USER django CMD ["./main.py"] docker-compose version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=fitshop - POSTGRES_USER=fituser - POSTGRES_PASSWORD=fitpass ports: - "5433:5433" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code restart: always ports: - "8000:8000" depends_on: - db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fitshop', 'USER': 'fituser', 'PASSWORD': 'fitpass', 'HOST': 'localhost', 'PORT': '5433', } } -
I have this following simple view . Then why is this ValueError is coming
This is my views.py enter image description here This error is coming enter image description here -
gitlab run ci tests with django and postgres
I have managed to build image and compile and able to push the images to gitlab container registry. My next step is to use these images to run a test When I try to run the djgando app in docker it seems to fail with The SECRET_KEY setting must not be empty. but I can see it exists when I run export before docker run. see comments in the code below unittests: stage: test before_script: - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - export WEB_IMAGE=$IMAGE/django - export DB_IMAGE=$IMAGE/postgres image: docker script: - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY - docker pull registry.gitlab.com/domain/reach-hf/postgres:latest - ls -al - ./setup_env.sh # this will copy envvars to .env - export # I can see all the required envvars are set - docker run --env-file .env registry.gitlab.com/domain/reach-hf/django:latest bash -e SECRET_KEY=1 # this is failing to run with the error mentioned - docker ps - docker images - docker exec django robot tests only: refs: - merge_requests variables: - $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "qa" -
What's the difference between a top level module and a sub-module in Django when using - "python manage.py startapp polls"
I followed the polls tutorial for Django and am beginning my own hobby project today. When creating an app, the following really confused me - Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite. So my question is - What is the difference between a top-level module vs a submodule for my project? And how do I decide which one to choose? Any help will be greatly appreciated as I am a noob coder working on my first hobby project lol. -
User logout after the first access token expires in django
The user is logout after the first access token expires. How do I automatically create and set a new access token after it has expired? -
Object of type InMemoryUploadedFile is not JSON serializable : Django
Here I am trying to update data in the bookmark model, But there is an error, related to image fields, models.py class Bookmark(BaseModel, SoftDelete): sort_order = models.PositiveSmallIntegerField(null=False, blank=False) mobile_thumbnail_image = models.ImageField(upload_to='video_bookmark_mobile_thumbnail', height_field=None, width_field=None, null=True, blank=True) web_thumbnail_image = models.ImageField(upload_to='video_bookmark_web_thumbnail', height_field=None, width_field=None, null=True, blank=True) serializer.py class BookmarkSerializer(serializers.ModelSerializer): class Meta: model = Bookmark fields = "__all__" views.py class BookmarkViewSet(ResponseViewMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer def post(self, request, *args, **kwargs): try: ..... def put(self, request, pk): try: details = get_object_or_404(Bookmark, pk=pk) serializer = BookmarkSerializer(details, data=request.data) if serializer.is_valid(): serializer.save() return Response('Ok') except Exception as e: .... post(), list() ,delete() are working properly, but in the case of put() makes "Object of type InMemoryUploadedFile is not JSON serializable", please give me a suggestion to fix it -
how to sort a queryset using django and htmx?
i'm using django-filter to apply filters, and on the new queryset i want to make an htmx request sort that depend on select tag change the new queryset sorting, here is my view: views.py def sorted_htmx_products(request): context = {} qs= request.GET['order_by'] print('request', qs['order_by']) if qs == "name_a": querySet = Product.objects.all().order_by('name') elif qs == "name_z": querySet = Product.objects.all().order_by('-name') elif qs == "price": querySet = Product.objects.all().order_by('price') elif qs == "brand": querySet = Product.objects.all().order_by('brand') else: querySet = Product.objects.all() products = ProductFilter(request.GET, queryset=querySet ) print('sorted products', products.qs) context['products'] = products.qs return render(request, 'snippets/htmx_products.html', context) and here is my html snippet where i made the htmx request <div class="product-select-box"> <div class="product-short" > <form hx-get="{% url 'core:sorted-products' %}" hx-target="#removed-products" hx-swap="outerHTML" hx-trigger="change"> <p>Trier par:</p> <select name="order_by" class="nice-select" > <option value="default">Default</option> <option value="name_a">Nom (A - Z)</option> <<option value="price">Prix</option> <option value="brand">Marque</option> </select> </form> </div> </div> why this doesn't work at all ? how to make a simple htmx form call on select option change ? -
Django not able to update field with serialzier
Hi I've my serializer like this class PredefinedHabitSerializer(serializers.ModelSerializer): image= serializers.SerializerMethodField() class Meta: model = models.PredefinedHabit fields = [ "id", "habit", "category", "why", "how", "dos", "donts", "info", "alternative", "image" ] def get_image(self, obj): if obj.image.startswith("https"): return obj.image else: return aws_get(obj,"s3-debug") My serializer get_image method is used to get the presigned URL of the image key stored in the model field image And a view to edit this model def edit_predefined_habit(request): predefined_habit = PredefinedHabit.objects.get(id=request.data.get("id")) data = { "category": request.data.get("category"), "habit": request.data.get("habit"), "why": request.data.get("why"), "how": request.data.get("how"), "dos": request.data.get("dos"), "donts": request.data.get("donts"), "info": request.data.get("info"), "alternative": request.data.get("alternative"), "image": request.data.get("illustration"), } data = Functions.clean(data) serializer = PredefinedHabitSerializer(predefined_habit, data=data) if serializer.is_valid(): serializer.save() return Response(data={"status": "success"}) View to get all objects def viewPredefinedHabits(request): model = PredefinedHabit.objects.all() serializer = PredefinedHabitSerializer(model, many=True) return Response(serializer.data) I am not able to update my image field with edit API, with my understanding it is because I've specified image to be a serializer method field. How do I overcome this? I've tried write_only doesn't work Other way I can think of manually saving into object and .save without passing to serializer. -
Error: Django settings "The SECRET_KEY setting must not be empty."
I am having a problem that has been asked before but I think this case is special. The problem comes because it does not find the "SECRET_KEY" but as I will show you below, it is set. To better understand my settings configuration, they are divided in the following files: settings/base.py, settings/dev.py and settings/prod.py. From the base.py file is where the other settings import their configurations. Next I will leave you all the configurations. base.py """ Django settings for portfolio project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os 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/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'blablabla' # Application definition INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'weatherapi', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'core', 'blog', 'weather', 'bootstrap4', 'bootstrap_datepicker_plus', 'django_bootstrap_icons', 'chartjs', 'ckeditor', ] 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 = 'portfolio.urls' TEMPLATES = [ … -
Add a field to DRF generic list view
I need to create a DRF list view that shows each course along with a boolean field signifying whether the user requesting the view is subscribed to the course. Course subscriptions are stored in the following model: class Subscription(models.Model): user = models.ForeignKey( CustomUser, related_name='subscriptions', null=False, on_delete=CASCADE) course = models.ForeignKey( Course, related_name='subscriptions', null=False, on_delete=CASCADE) class Meta: ordering = ['course', 'user'] unique_together = [['user', 'course']] This is the view I am writing: class CourseListView(generics.ListAPIView): permission_classes = [IsAuthenticated, ] queryset = Course.objects.all() serializer_class = CourseSerializer def isSubscribed(self, request, course): sub = Subscription.objects.filter( user=request.user, course=course).first() return [True if sub else False] def list(self, request, format=None): queryset = Course.objects.all() serializer = CourseSerializer(queryset, many=True) return Response(serializer.data) I am looking for a way to modify he list method, so as to add to the response the information about whether request.user is subscribed to each of the courses. The best solution I have for now is to construct serializer manually, which would look (at the level of pseudo-code) something like this: serializer = [] for course in querySet: course['sub'] = self.isSubscribed(request, course) serializer.append(CourseSerializer(course)) I suspect there should be a better (standard, idiomatic, less convoluted) way for adding a custom field in a list view, but could not find … -
Placeholder content turns red below certain breakpoint - Django CMS
I have what seems like a bug in a Django CMS website -- below a certain breakpoint (±730) all text content inside placeholder tags turns red. I have commented out all custom CSS stylesheets, removed links to external style sheets and all inline styling to try and pinpoint what is causing it by process of elimination, but no luck. I've stripped the website down to its bare bones but the text is still red. Is there maybe a specific way to style placeholders that I'm not familiar with?? -
How add condition "IF NOT EXISTS" to AddIndexConcurrently in Django Migrations?
I want to add index on model field concurrently using AddIndexConcurrently. How can I add condition "IF NOT EXISTS"? Now my query run like CREATE INDEX CONCURRENTLY "chat_chatmessage_type_idx" ON "chats_chatmessage" ("type"); But I need to transform it to CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_chatmessage_type_idx" ON "chats_chatmessage" ("type"); database_operations=[ AddIndexConcurrently( model_name='chatmessage', index=models.Index( fields=["type"], name="chat_chatmessage_type_idx", condition=??something like this - Q("IF NOT EXISTS")?? ) )] -
Django - Group by, split by date range
I have a model: class MyModel(models.Model): store_id = models.TextField() day_dt = models.DateField() param1 = models.IntegerField() param2 = models.IntegerField() Some data example: store_id | day_dt | param1 | param2 ---------------------------------------- STORE1 | 2021-09-30 | 10 | 30 STORE2 | 2021-09-31 | 20 | 40 .... STORE1 | 2021-10-01 | 4 | 5 STORE1 | 2021-10-02 | 6 | 10 STORE1 | 2021-10-03 | 2 | 5 STORE2 | 2021-10-02 | 3 | 7 STORE2 | 2021-10-03 | 1 | 19 .... I need to split data into groups by store_id and interval (day_dt shoould be between 2021-10-01 and 2021-10-04): STORE1 | 2021-10-01 STORE1 | 2021-10-02 STORE1 | 2021-10-03 and STORE2 | 2021-10-02 STORE2 | 2021-10-03 and then apply to each (of two) groups aggregation: Avg('param1') and Avg('param2'). The expected output for data example: store_id | param1_avg | param2_avg ---------------------------------- STORE1 | 6 | 10 STORE2 | 2 | 13 How could I do this aggregation with ORM? -
how to add table list to my Django admin?
imagine every user has some roles! so I would like to add something like a table of the roles which displays the roles of a member...something like django group and every time the user get new roles i want them to be added there. I tried to use group but that didn't look satisfying and here is an image of my example: image of example -
Multiple Foreign keys in DRF
I am completely new to django and python kindly help me with below query: I have 3 models , with multiple foreign key relations with given sample data now I need 3 outputs via django ORM or Serializers 1.for a given student id ,display the Student details and marks in each subjects 2.list all the students with their total marks (sum of three subjects in this case) 3.Average marks scored by all the students for each subject for ex as per the given sample marks in English are 65 , 95 and average is 80 { Subject :"English", average : " 80" } class Student(models.Model): student_id = ShortUUIDField(primary_key=True, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Subjects(models.Model): subject_code = ShortUUIDField(primary_key=True, editable=False) subject_name = models.CharField(max_length=100) class Reports(models.Model): student = models.ForeignKey(Student,on_delete=models.CASCADE,related_name='student_report') subject = models.ForeignKey(Subjects,on_delete=models.CASCADE,related_name='subject',default=None) marks = models.IntegerField(max_length='3') class Meta: unique_together = ("student", "subject") sample data Student data student_id first_name last_name 1 abc x 2 def y Subjects data subject_code subject_name 1 English 2 Science 3 Math Reports data student_id subject_id marks 1 1 65 1 2 75 1 3 92 2 1 95 2 2 85 2 3 62 -
Unable to run Django unit tests for Selenium
I am trying to follow This tutorial but I am having issues with part 4: Automated testing. I have: Installed Chrome Put chromedriver on path Installed Selenium As the tutorial instructs, But when I run python manage.py test chat, I get this error DevTools listening on ws://127.0.0.1:52672/devtools/browser/ecdde935-9116-45d2-b2c3-7d2e36ad5583 EETraceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\spawn.py", line 109, in spawn_main fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY) OSError: [Errno 9] Bad file descriptor Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\spawn.py", line 107, in spawn_main new_handle = reduction.duplicate(pipe_handle, File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\reduction.py", line 79, in duplicate return _winapi.DuplicateHandle( OSError: [WinError 6] The handle is invalid I haven't been able to find anything relating to this problem. All of the solutions I've seen have said to use driver.quit() instead of driver.close() but I already am, and have have no other ideas on what to do. My code is identical to that found in the tutorial linked above -
unique=True give Already exist! Even if interchanging values of 2 objects
To display objects(members) in perticular order i have made field order order = models.IntegerField(unique=True,null=True,blank=True) so that i can .order_by('order') to have it in required order In Django Admin, table have only 2 objects with order 0,1. If i want to interchange it by 1,0 gives error About us with this Order already exists. For ease of using Django admin, is there any better method to achieve above -
'NoneType' object is not subscriptable in django rest framework
Im trying to receive data in json format in django restframework and utilize the data immediately but i realize i get error that 'NoneType' object is not subscriptable' and i feel that i need to use cleaned_data but i dont know how to use cleaned_data in rest framework...here is my code: @api_view(['GET', "POST"]) def home(request): if request.method == 'POST': name = request.data.get('name') email = request.data.get("email") amount = request.data.get("amount") phone = request.data.get("phone") return redirect(str(process_payment(name, email, amount, phone))) else: responseData = { "Homepage": "Payment" } return Response(responseData)``` [That is the image of the error im getting below][1] [1]: https://i.stack.imgur.com/wkOwa.png -
Django: E-commerce Address Checkout Form not Printing Request.POST Data in Terminal
I created a ModelForm with a print(request.POST) statement in the view. When I click the submit button on the form I see no data in the terminal or saved data in the admin. Also I get redirected to the login page weather logged-in on not. Can someone explain what I'm doing wrong; and how should I be thinking about this kinda of error going forward? thanks in advance SO community form.py class AddressForm(forms.ModelForm): class Meta: model = Address fields = [ #'billing_profile', #'address_type', 'address_line_1', 'address_line_2', 'city', 'state', 'country', 'postal_code' ] views.py from django.shortcuts import redirect from django.utils.http import is_safe_url from .forms import AddressForm def checkout_address_create_view(request): form = AddressForm(request.POST or None) context = { "form": form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): print(request.POST) if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("cart:checkout") return redirect("cart:checkout")