Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django foreign key specify field values - group by groups
Is it possible to make a foreign key value from specific values in the field from the table? For EXA: HR and POC have foreign key via the employee table, but HR can bring only "HR" values from "name" field - group by group_name field. Also POC table: all values grouped by "POC" TNX alot -
match o file but incompatible architecture
OSError: dlopen(/opt/homebrew/Cellar/gdal/3.5.1_3/lib/libgdal.dylib, 0x0006): tried: '/opt/homebrew/Cellar/gdal/3.5.1_3/lib/libgdal.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/opt/homebrew/Cellar/gdal/3.5.1_3/lib/libgdal.31.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')) There is some previous project and I have to do fixes but this project is not running locally and giving me gdal error I tried to install gdal on mac and even in project but now its saying wrong architecture. Can anyone tell me how to fix this issue? -
How can I add new rows and columns to the table with Django?
The client wants something very different from me. He wants to have the ability to create a table from the admin panel and to give commands to this feature from the front. These are the commands: Clicking the ROW button will create a new line. When the CELL button is clicked, a new column will be created. I can do this with JavaScript. But I don't know how to save them in database with django. So how should the column be stored in the database when it is created? I have no idea. If you have any code sample or idea about it, please share with me. Thank you. -
What it the difference related_name and related_query_name in django?
I know the related_name is used for reverse relationships but when I use related_qauery_name?. I don't find any good answers that convince me. -
Trouble hooking up postgres to django
Following the documentation from Django Postgres DocumentationI added to my settings.py in settings I set DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'service': 'my_service', 'passfile': '.my_pgpass', }, } } Adjacent to settings.py I created pg_service.conf with [my_service] host=localhost user=USER dbname=NAME port=5432 and adjacent to that I created mypg_pass localhost:5432:PostgreSQL 14:postgres:LetMeIn I am pretty sure I followed the documentation but on python manage.py check I got the following error. connection = Database.connect(**conn_params) File "C:\Users\oliver\base\correlator2v2\correlator2home\venv\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync)django.db.utils.OperationalError: definition of service "my_service" not found -
Django/MySQl how to fix Database returned an invalid datetime value. Are time zone definitions for your database installed?
What Happened After moving my Django app - which was working as expected - from a VPS to shared hosting with Cpanel I changed Database from PostgresSQL to MySQL, whenever I open an object that has created_at field which is a Datetime Field I Get this error. Error Database returned an invalid datetime value. Are time zone definitions for your database installed? What I've tried After some searching, I've found out that it can be fixed by running this command in terminal mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql That command should populate the Timezone tables in my database. The Problem I can't run the comment mentioned above as am using Cpanel shared hosting and am very limited on my choices and commands that I can run using terminal. so I tried to run it I got this error What I need I think the solution now is to find a way to populate the timezone tables on the Mysql database using only PhpMyAdmin and not using the terminal -
I want to enter marks of students Grade Model i want my drop down to have only subjects selected by students
class Person(models.Model): lastname=models.CharField(max_length=10,null=True,blank=True) firstname=models.CharField(max_length=10,null=True,blank=True) courses=models.ManyToManyField("Course",blank=True) class Meta: verbose_name_plural="People" def __str__(self): return self.firstname + " " + self.lastname class Course(models.Model): name=models.TextField() year=models.IntegerField() class Meta: unique_together=("name","year") def __str__(self): return f"{self.name},{self.year}" class Grade(models.Model): person=models.ForeignKey(Person,on_delete=models.CASCADE) grade=models.PositiveSmallIntegerField(validators=[MinValueValidator(0),MaxValueValidator(100)]) course=models.ForeignKey(Course,on_delete=models.CASCADE,related_name='Grades') def __str__(self): return f"{self.person},{self.grade},{self.course}" Due to many to many relationship it display all the courses data but i need only the data which students enrolled -
Could not change transaction status (0) (SQLSetConnectAttr)
We have a Django app connected to a remote SQL database. I get an error when i try to do an update request on a database table : [HY000] [FreeTDS][SQL Server]Could not change transaction status (0) (SQLSetConnectAttr). I conclude that a similar request is still in progress and it blocks all my requests. The "autocommit" parameter is True. I tested : connection.rollback() This did not resolve the problem. Does someone have an idea ? -
Unrecognized Content Security Policy directive 'worker-src' in Safari Browser
I have a django app that is embedded in Shopify. It is working fine in all other browsers except in Safari Browser. In safari there is the above mentioned issue in the log and getting internal server error for all other functionalities of the app.This is a part of my settings.py for the CSP settings: CSP_FRAME_ANCESTORS = ("'self'", 'https://*.myshopify.com') # default source as self CSP_DEFAULT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'", "https://fonts.gstatic.com") # style from our domain and bootstrapcdn CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", "https://fonts.googleapis.com") # scripts from our domain and other domains CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'") # images from our domain and other domains CSP_IMG_SRC = ("'self'", "https://*.s3.amazonaws.com", "data:", "https://cdn.shopify.com") SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'PUT'] CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') CSRF_TRUSTED_ORIGINS = [config('CSRF_TRUSTED_ORIGINS')] Can anyone tell me what's the issue here? -
Django-Rest: how to access data if JSON or URL-encoded inside view?
I need to access some nested information inside request.data inside a post definition. The data sent is in the following form: { ... "licence": { "tenant_name": "tenant1", ... } } Since I'm using Django Rest with the default parsers installed (JSONParser and FormParser) I could receive JSON or HTML form content inside the request. I'd like to keep both and don't change the default parser_classes of the view. The request.data has different types and representations based on the content: HTML-encoded: <QueryDict: {..., 'licence.tenant_name': ['tenant1']}> JSON: {..., 'licence': {'tenant_name': 'tenant1'}} To handle this I currently check on the type. Is there a better way as a general use case? class SubscribeView(views.APIView): serializer_class = SubscriptionSerializer permission_classes = (AllowAny, ) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) tenant_name = request.data['licence']['tenant_name'] if type(request.data) is dict else request.data['licence.tenant_name'] # perform actions on tenant_name serializer.save() status_code = status.HTTP_201_CREATED response = { 'success': True, 'status_code': status_code, 'message': 'New subscription successfully created', 'subscription': serializer.data } return Response(response, status=status_code) -
Django rest framework self nesteg query
I'm using DRF. How can I get hierarchical JSON by django ORM? what the query should look like? CategoryModel.objects.filter(active=True).select_related() or prefetch_related()? I have model that looks like this: class Category(models.Model): parent = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=100) slug = models.SlugField(unique=True, default='', blank=True) active = models.BooleanField(default=True) serializers: class ParentCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class CategoryListSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['name', 'slug', 'parent'] parent = ParentCategorySerializer(many=True) I want to get something like this: { "name": "First category", "slug": "first-category", "subcategories": [ { "name": "First subcategory one", "slug": "first-subcategory-one", "subcategories": null }, { "name": "First subcategory two", "slug": "first-subcategory-two", "subcategories": null }, ] }, { "name": "Second category", "slug": "second-category", "subcategories": [] } -
Will I run into a CORS error if I am using my API to return an image url, from on another site, which I set to an <img> tag with the src attribute? [closed]
I have an API written in Django which has a model with links to movie posters, which are hosted on the site: m.media-amazon.com, for example: https://m.media-amazon.com/images/M/MV5BNjM0NTc0NzItM2FlYS00YzEwLWE0YmUtNTA2ZWIzODc2OTgxXkEyXkFqcGdeQXVyNTgwNzIyNzg@._V1_SX300.jpg With my current development server, I have a JavaScript file that makes a request to an endpoint which returns that url, which I then set in an img tag with the src attribute. It displays in my browser, but will I run into issues in production? is this a sustainable approach? this is my js code: async function getMovieUrl() { try { const response = await fetch('/posterurl/', { method: 'GET' }); const urldata = await response.json() var url = document.getElementById("posterurl") url.src = urldata['url'] } catch(error) { console.error(error) } } this is my API code: @api_view(['GET']) def poster_url(request): context = {'url': url from above} return Response(context) and currently I am able to see the image in my browser upon clicking: <button onclick="getMovieUrl()">Movie URL</button> -
404 PAGE NOT FOUND DJANGO project
I have created one app in that urls are working properly with /app_name/urlname but when I am visiting other page in loop it is giving 404 error below is the my code code of urls.py of app when I am visiting first/buttons or first/addrecord separately it is dispalying page but if I will go to addrecord from buttons it is giving 404 error Please help...I got stuck at this error -
getting error to save post data in database with django API
I have two tables Emp and Service,here in Emp table person_id column is foreign key with service tables id.but at time of data saving in databse i want to save data with super_id which is only simple field from Service table. { "name":"joen", "person_id":1 } but i want to pass super_id instead of person_id and save data in emp table in databse. { "name":"joen", "super_id":"asap123" } how we will write api for saving data in databse in django f = Emp.objects.filter(person_id__super_id=(user_data['super_id'])) it is return object of emp table. form={ "name":str(user_data["user_id"]), "person_id":str(user_data["super_id"]), } d = EmpSerializer(data=form, many=True) if d.is_valid(): d.save() data = {"status": 1, "errorMsg": ""} else: data = {"status": 0, "errorMsg": "form could not saved"} getting form could not saved... -
How to schedule an email using twilio sendgrid in django?
I'm currently building an app which contains email sending to multiple users which i'm able to do but i want to add a functionality which schedule's an email, for instance I'm using sent_at method as you can see below:- extra_headers = {'X-SMTPAPI': json.dumps({'send_at': FinalScheduleTime})} I've also tried SendAt but it's not working either. -
Python Django REST Infinite Recursion Problem
As of late I've started working towards learning REST Api with Django Rest Framework, Cors headers, and mssql connector both for personal purposes, and for a project I'm working on. Beneath I'll include photos of the work I've done, but the main problem is the photo I'm going to show first. An error that I have yet to find the root cause. Working with this project, I got close to completing a Get/Post/Put method, but once I attempted to run the server itself, it ended in an endless recursion. I've attempted to search a variety of threads but I'm quite unsure what the problem may be. I'll leave images of my code as to make this much easier. The images in order are the main URL.py document, models.py, serializer.py, url.py within my app, my view, and the Database settings. I doubt the database settings are causing the recursion, but it never hurts to check as well. As for the major imports I'm using Django 4.0, Django-cors-headers, DjangoRestFramework and MSSQL-Django. If you need more information, or find the error. Let me know and I'll respond as quickly as possible. -
django def save() how to concat multiple fields into an id
I have this postgres function SELECT CONCAT(f_office_id,f_sy,f_sem,'-',office_serial) INTO office_lastnumber from curriculum.clearing_office where office_id=f_office_id; UPDATE curriculum.clearing_office SET office_serial =office_serial+1 where office_id=f_office_id; What it does is when I save an item, it creates an cl_itemid test2021-20221-1. then in table clearing_office the column office_serial increments +1 so next item saved will be test2021-20221-2 { "studid": "4321-4321", "office": "test", "sem": "1", "sy": "2021-2022", } How can I recreate this but in django models.py class Item(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) class Meta: managed = False db_table = 'item' -
Dynamic New Forms in Django
I have this code and I want to create Dynamic New FormSet . By adding and deleting buttons in Models I have Customer, Product and AddProduct classes class Customer(models.Model): customer = models.CharField(max_length=200, null=True, blank=False) class Product(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, related_name='customer_product') product = models.CharField(max_length=200,choices=PRODUCT, blank=False) class AddProduct(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True,related_name='customer_add_product') products = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='product_add_product') add_product = models.CharField(max_length=200, choices=PRODUCT, blank=True,null=True) in forms class PersonCreationForm(forms.ModelForm): class Meta: model = Product fields = ['product'] class AddProductForm(forms.ModelForm): class Meta: model = AddProduct fields = ['add_product'] in views def CreateView(request, pk): customer = get_object_or_404(Customer, pk=pk) formset_addedFormset = modelformset_factory(AddProduct, form=AddProductForm) form = PersonCreationForm(request.POST or None) formset = formset_addedFormset(request.POST or None, queryset=AddProduct.objects.none(), prefix="product_add_product") if request.method == 'POST': if form.is_valid() and formset.is_valid(): new_form = form.save(commit=False) new_form.customer=customer new_form.save() product = Product.objects.all().last() print(product) for add_product in formset: new_formset = add_product.save(commit=False) new_formset.customer=customer new_formset.products = product new_formset.save() else: print('error') context = {'customer':customer, 'formset':formset, 'form':form, } return render(request, create.html',context) in create.html {% load crispy_forms_tags %} {% block content %} <form method="POST"> {% csrf_token %} <!-- here for create Product --> {% for form in form %} <table> <td>{{form.product|as_crispy_field}}</td> {% endfor %} <!-- end for --> {{ formset.management_form }} {% for formset in formset.forms %} {{ formset.field_errors … -
Update foreign key object's fields in drf
I've two models: class User(models.Model): name = models.CharField(max_length=255) email = models.EmailFeild() password = models.CharField(max_length=255) class Profile(models.Model): user = models.ForeignKeyField(User, on_delete=models.CASCADE) image = models.ForeignKeyField(to='media.images', on_delete=models.CASCADE) mobile = models.IntegerField() address = models.CharField(max_length=255) Now I'm creating a patch API for updating profile. Now, a user can also update email and his name. class ProfileUpdateSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' def update(self, instance, validated_data): ......... How would I accept the User model's detail (email and name) in the profile payload and update both the models in my serializer? -
i am creating an API and i am getting the error 'ModelBase' object is not iterable error
this is my views.py @api_view(['GET']) def home(request): if request.method == 'GET': movies=Watchlist.objects.all() serializer=WatchlistSerializer(Watchlist,many=True) return Response(serializer.data) this is serializers.py class WatchlistSerializer(serializers.ModelSerializer): class Meta: model=Watchlist fields="__all__" this is models.py class Watchlist(models.Model): title=models.CharField(max_length=50) storyline=models.CharField(max_length=200) activate=models.BooleanField(default=True) create=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title it is showing error model class not iterable. -
drf-spectacular does not generate parameters in swagger-ui, which I provide in FilterSet class from django_filters
I am trying to implement some API by using GenericViewSet. I have also some FilterSet class with some custom fields. My issue is the generation of these custom fields in swagger-ui endpoint documentation. Generated schema just does not includes all these filtering parameters. Is there any method to solve this problem without using @extend_schema decorator with viewset actions? -
how to access context in serializer queryset
I'm looking for a way to access the context to filter by current user class RemovePermissionsSerializer(serializers.Serializer): user_permissions = serializers.PrimaryKeyRelatedField( many=True, queryset=Permission.objects.filter(user = context.get('request').user) ) I can't access context becuase it's undefined, neither self.context -
What is the best way to use the permission_classes combination in Django?
Writing 'permission_classes' for DRF project, help me decide what is the best way to write it: The DRF documentation describes two ways to write 'permission_classes': in a tuple and in a list. # first way, in a list permission_classes = [IsAuthenticated & IsUserWithAccess] # or in a tuple permission_classes = (IsAuthenticated, IsUserWithAccess) On one side, python is faster with tuples, but writing 'permission_classes' through a list allows you to use the logical '&' operator. Which do you think is the best way to use from a performance point of view? -
NoReverseMatch - Reverse for 'emotion-buttons' with arguments '(1,)' not found. 1 pattern(s) tried: ['student/emotion\\-buttons$']
I keep getting this error message "NoReverseMatch at /student/take-exam/1 Reverse for 'emotion-buttons' with arguments '(1,)' not found. 1 pattern(s) tried: ['student/emotion\-buttons$']'". I have been unable to figure out the problem with my code. When I link take_exam to start_exam it works fine, so the problem should be in linking emotion_buttons to start_exam. Here is what I have so far: urls.py from django.urls import path from student import views from django.contrib.auth.views import LoginView urlpatterns = [ path('student-exam', views.student_exam_view,name='student-exam'), path('take-exam/<int:pk>', views.take_exam_view,name='take-exam'), path('emotion-buttons', views.emotion_buttons_view,name='emotion-buttons'), path('start-exam/<int:pk>', views.start_exam_view,name='start-exam'), ] views.py @login_required(login_url='studentlogin') @user_passes_test(is_student) def take_exam_view(request,pk): course=QMODEL.Course.objects.get(id=pk) total_questions=QMODEL.Question.objects.all().filter(course=course).count() questions=QMODEL.Question.objects.all().filter(course=course) total_marks=0 for q in questions: total_marks=total_marks + q.marks return render(request,'student/take_exam.html',{'course':course,'total_questions':total_questions,'total_marks':total_marks}) @login_required(login_url='studentlogin') @user_passes_test(is_student) def start_exam_view(request,pk): course=QMODEL.Course.objects.get(id=pk) questions=QMODEL.Question.objects.all().filter(course=course) if request.method=='POST': pass response= render(request,'student/start_exam.html',{'course':course,'questions':questions}) response.set_cookie('course_id',course.id) return response @login_required(login_url='studentlogin') @user_passes_test(is_student) def emotion_buttons_view(request): courses=QMODEL.Course.objects.all() return render(request,'student/emotion_buttons.html',{'courses':courses}) take_exam.html <a href="{% url 'emotion-buttons' course.id %}" class="btn btn-info">Let's Start</a> emotion_buttons.html <a href="{% url 'start-exam' course.id %}" class="btn btn-info">End Session</a> Any help would be appreciated -
multiple values in a dropdown to be annotate, and then save in another table which is studentsession,.....Field 'id' expected a number but got ''
The error here, is i'm trying to get lecturersession from it table and then populate the studentsession, but i have multiple values for lecturersession, each lecturer has to registered it own session for student to get registered for session as well, please, am i doing the right thing or not, should i populate it directly from the source, where the session table my views.py class StudentSessionRegistration(View): def get(self, request, *args, **kwargs): student = Students.objects.get(admin=request.user) session = LecturerSession.objects.values('lecturersession'). annotate(Count('lecturersession')).order_by() context = { 'session': session } return render(request, 'superadmin/student/add-session.html', context) def post(self, request, *args, **kwargs): student = request.POST.get('student') student = Students.objects.get(admin=request.user.id) session = request.POST.get('studentsession') session = LecturerSession.objects.get(id=session) if StudentSession.objects.filter(student=student, studentsession=session).exists(): messages.error(request, f'Hello {request.user.username}! Your Session is already registered') return HttpResponseRedirect(reverse('emisapp:student-session-registration')) if not session: messages.error(request, 'Please select session') return HttpResponseRedirect(reverse('emisapp:student-session-registration')) try: StudentSession.objects.create(student=student, studentsession=session) messages.success(request, "Student Session Registration Successfully") return HttpResponseRedirect(reverse('emisapp:student-session-registration')) except: messages.error(request, "Error while saving Student Session Registration") return HttpResponseRedirect(reverse('emisapp:student-session-registration')) template <div class="form-group"> <label>Select Faculty</label> <select name="studentsession" id="studentsession" required class="form-control"> <option value="{{s.id}}">--Select a Session--</option> {% for s in session %} <option value="{{s.id}}">{{ s.slug }}</option> {% endfor %} </select> </div> Models.py class LecturerSession(models.Model): id = models.AutoField(primary_key=True) lecturer = models.ForeignKey('Lecturers', related_name='lecturersession',null=True, on_delete=models.CASCADE) lecturersession = models.ForeignKey(SessionYearModel, related_name='lecturersession',null=True, on_delete=models.CASCADE) slug = models.SlugField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = …