Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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") -
Create a list view with group by field name and link to details - django admin
So I have the following the following table: class IncomeStatementQuarterly(models.Model): date = models.DateField() statement = models.CharField(max_length=1000, blank=True, null=True) ticker = models.CharField(max_length=1000, blank=True, null=True) security = models.ForeignKey(SecuritiesTable, models.DO_NOTHING) line_item = models.CharField(max_length=1000, blank=True, null=True) amount = models.DecimalField(max_digits=65535, decimal_places=4, blank=True, null=True) class Meta: ordering=('ticker',) verbose_name = "Income statement / Quarterly" verbose_name_plural = "Income statements / Quarterly" managed = False db_table = 'income_statement_quarterly' unique_together = (('date', 'ticker', 'line_item'),) and the following in my admin.py class: @admin.register(IncomeStatementQuarterly) class IncomeStatementQuarterlyAdmin(admin.ModelAdmin): date_hierarchy = 'date' list_filter = ('line_item',) list_display = ("ticker", "date", "statement", "line_item", 'amount') search_fields = ['ticker'] list_display_links = ('ticker',) def has_add_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None) -> bool: return False My goal is to create a view grouped by the 'ticker' and 'date' field. As of right now, my admin view is displaying each rows of my model like so: I want to regroup everything by ticker and date so that I'll have a link that if clicked on, I'll have all the rows based on the given combination of date and ticker. Is this possible? I've been looking everywhere for the past 5 days and I was getting ready to start a new model called statements_list … -
django.db.utils.IntegrityError: UNIQUE constraint failed:
I am making review api with django, but I have a problem. models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify class buildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(unique=True, default=uuid.uuid1) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): self.slug = slugify(self.building_name) return super().save(*args, **kwargs) class reviewData(models.Model): building = models.ForeignKey(buildingData, related_name='reviews', on_delete=models.CASCADE, null=False, blank=False) review_content = models.TextField() star_num = models.FloatField() urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<slug:slug>/', ReviewListAPI.as_view()) ] I am collecting data with crawling, but... django.db.utils.IntegrityError: UNIQUE constraint failed: crawling_data_buildingdata.slug This error occurs. I've tried deleting migrate file and migration again, but still doesn't work. Is there any problem on my code or is there other way to solve this? -
How to handle dynamic byte-struct unpacking and comprehension
During my current project, I have been receiving data from a set of long-range sensors, which are sending data as a series of bytes. Generally, due to having multiple types of sensors, the bytes structures and data contained are different, hence the need to make the functionality more dynamic as to avoid having to hard-code every single setup in the future (which is not practical). The server will be using Django, which I believe is irrelevant to the issue at hand but I have mentioned just in case it might have something that can be used. The bytes data I am receiving looks like this: b'B\x10Vu\x87%\x00x\r\x0f\x04\x01\x00\x00\x00\x00\x1e\x00\x00\x00\x00ad;l' And my current process looks like this: Take the first bytes to get the deviceID (deviceID = val[0:6].hex()) Look up the format to be used in the struct.unpack() (here: >BBHBBhBHhHL after removing the first bytes for the id. Now, the issue is the next step. Many of the datas I have have different forms of pre-processing that needs to be done. F.e. some values need to be ran with a join statement (e.g. ".".join(str(values[2]) ) while others need some simple mathematical changes (-113 + 2 * values[4]) and finally, others needs a simple logic … -
Serve media file on pythonanywhere
I have a web app made with Django. It consists of upload, file processing and download. The download part works with the FileResponse() class, wich takes a binary . I want to run this app on Pythonanywhere. The problem is that, as Django is not meant to serve static/media files, I have to use the Pythonanywhere capabilities, wich provides a Dashboard to serve the files (it maps the file path to a URL). I can see how it is used to serve static files (css or js), wich is the most common case. In their docs they make a very clear example, in wich the URL replaces the file path inside the or tags of the HTML. But in the case of my app, we are talking about a media file wrapped with open() class inside the view function of the view.py file. Do I have to use the URL as the file path passed to open()? Am I scoping this wrong. Please, help me. -
Django total iteration number for nested for loops
Example: django doc cities = [ {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'}, {'name': 'New York', 'population': '20,000,000', 'country': 'USA'}, {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'}, {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'}, {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'}, ] {% regroup cities by country as country_list %} <ul> {% for country, local_cities in country_list %} <li>{{ country }} <ul> {% for city in local_cities %} <li>{{ city.name }}: {{ city.population }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> How do I get the total iteration number of both inner and outer for loop. forloop.counter and forloop.counter0 return only inner index -
Django - remove items from select while maintaining the original query
I'm wondering if Django has the functionality to remove particular items from a select once they've been added. For example, lets say I have a query that looks like: FooBar.objects.annotate( field_1=field_1, field_2=field_1, field_3=field_1 ).filter( some_filter_set ) would produce SQL like so: select field_1, field_2, field_3 from foo_bar where some_filter_set After the initial query has been made, I'd like to keep this query, and create another copy that is the exact same but distilled down to just field_1 in the select. Does Django give the functionality to directly edit the select? The reason for this is that I have a very large dynamically generated query that needs to be used in a subquery. I'd like to take the final version of the query, copy it, change the select, and use that as the subquery. Thanks! -
How to resolve: NOT NULL constraint failed: bloggo_ipaddress.user_id by trying to store user's ip
i'm trying to use the django framework and to practice i tried to create a blog. What I have programmed seems to work quite well. The only thing I'm trying to do and I can't is adding the ip field to the user (which I created with the standard django mode). For now I'm trying to see if by logging (log in works) the ip is saved in the field that I created but it doesn't work (IntegrityError at /login/... NOT NULL constraint failed: bloggo_ipaddress.user_id), then I would like to make sure that if a user enters with a different ip a message is shown. But in the meantime I would like to understand how to correctly store the ip. This is my forms.py with Log in and Registration forms from django import forms from django.forms import ModelForm, TextInput from django.shortcuts import render, redirect from django.contrib.auth import (authenticate, get_user_model, login, logout,) from django.contrib.auth.models import User from bloggo.models import Post from django.contrib.auth.forms import UserCreationForm, AuthenticationForm User = get_user_model() class AuthenticationForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('Wrong username or … -
Pyhton package to convert html to image and pdf
I need python package to convert html to image and pdf without depending on wkhtmltopdf/wkhtmltoimage packages. -
Is a Javascript search less secure than using a search client like Sphinx or Elasticsearch?
I have a concept/security question... Looking at the search options for Django, most recommend search databases or docker apps such as sphinx or elasticsearch. However, in my particular case I was able to create a Javascript real time search that functions just as smoothly as the sphinx one on my site and is simply using my already made django postgres models. My questions are: What are the upsides of using a separate app or database over a javascript search? Are there size limitations to Javascript searches? Are there security risks with either option? Thank you! -
Django on virtualenv but failed to run project and import using git-bash
I already installed django using virtualenv on git bash, but always gives me this error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Already add PYTHONPATH to environment variable as well. I tried to import django on python idle but it seems didn't work too. Any idea what I am missing? -
'max_number' is not defined using annotation with django
I have that code from django.db.models import Max User.objects.annotate(max_number=Max('number')).filter(number=max_number) # Filter all users by the highest number. And when I execute it I got that error : 'max_number' is not defined Could you help me please ? Thank you very much ! -
PostgreSQL not available: instance=None:None, timeout=30s
I am trying to run the old code of Django 1.x in my local machine, some how this project is used as microservice and make many dependencies on other project, But I want to run it locally on my machine. I set up the virtual environment, errors removed when I start the server this comes always (env) C:\Users\mahad\projects\Hermes\app>python manage.py runserver PostgreSQL not available: instance=None:None, timeout=30s here is my code, where I am connecting database: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': environ.get('PGHOST'), 'NAME': environ.get('PGDATABASE', 'app'), 'USER': environ.get('PGUSER'), 'PASSWORD': environ.get('PGPASSWORD'), 'PORT': int(environ.get('PGPORT', 5432)), } What will be the error or what I am missing? Kindly ask if any point you want to know about project settings. -
Querying Multiple foreign key relationships 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