Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't upload a file
I am writing an application in django, drf, I use drf_spectacular for documentation, the problem is downloading the file through the documentation, I do not need to process the file or store it, I just want to upload it and send it to another service. class PFX_key(serializers.Serializer): file = serializers.FileField() pin = serializers.IntegerField(required=False) description = serializers.CharField(required=False) @extend_schema(request=serializers.PFX_key) @action(detail=False, methods=['post'], parser_classes=[MultiPartParser,], serializer_class=serializers.PFX_key) def load_pfx_key(self, request: Request) -> Response: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try: datatools.send_pfx_key(serializer.validated_data, self.request.user.username) except Exception as ex: raise ex return Response() The logic is fully working, all I need is the ability to upload files via drf_spectacular so that the fronts can work with it. I've tried adding different parameters, one of them even seems to fit the needs: OpenApiTypes.BINARY, but I get an error Please correct the following validation errors and try again. For 'file': Value must be a string. -
Django & React native, I can't login back after I logged out
const handleLogin = () => { axios.post('https://8d16-103-62-155-152.ngrok-free.app/api/auth/mobile-login/', { username, password }) .then(response => { // Clear existing user data AsyncStorage.removeItem('username'); // Assuming you stored the username in AsyncStorage // Set new username and navigate to Main screen setUsername(username); navigation.navigate('Main'); }) .catch(error => { Alert.alert('Login Failed', 'Invalid username or password'); }); }; THIS IS MY ERROR : Forbidden: /api/auth/mobile-login/ [29/May/2024 13:38:49] "POST /api/auth/mobile-login/ HTTP/1.1" 403 58 I can log in once but after I click logout I can't login again I think something is preventing it to access on my django after logging out. I just used navagation for my logout function -
What are the most common mistakes devs make? what can i learn from them? [closed]
I have joined a company as an intern. Recently, the manager told me to use best practices for coding etc.I wanna know what are professional best practices. I searched the net but couldn't find a satisfactory answer. ..... C'mon stack-overflow genies. -
How Do I Fix the errors in Django Models?
I am trying to create models in Django, but when I go to the admin page and click into the models, it gives me an error. Please see my code in python below. I also had problems when I was trying to make migrations, but it worked in the end, and in my admin panel. I could see the two models I created, but when I click into any of them, I got an error page. models.py from django.db import models from datetime import datetime import uuid # Create your models here. class ProductType(models.Model): Type_Name = models.CharField(max_length=200) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.Type_Name class ProductItem(models.Model): product_title = models.CharField(max_length=500, default="Product Name") product_type = models.ForeignKey('ProductType', on_delete=models.CASCADE) product_size = models.CharField(max_length=500, default="Product Size") product_finish = models.CharField(max_length=500, default="Product Finish") date = models.DateField(default=datetime.now, blank=False) quantity = models.IntegerField(default=0) unit_cost = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) unit_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) reorder_quantity = models.IntegerField(default=0) reorder_date = models.DateField(default=datetime.now, blank=False) image = models.ImageField(null=True, blank=True, default='404-img.png') id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.product_title admin.py from django.contrib import admin from .models import ProductItem, ProductType # Register your models here. admin.site.register(ProductItem) admin.site.register(ProductType) models.py from django.db import models from datetime import datetime import uuid # Create your models here. … -
Extracting text from PDF after uploading (Django app on AWS)
@login_required(login_url="/login/") def upload_view(request): posts = Temp.objects.all() common_tags = Temp.tags.most_common() if request.method == "POST": form = TempForm(request.POST, request.FILES, initial={"user": request.user}) if form.is_valid(): newpost = form.save(commit=False) newpost.slug = slugify(newpost.title) unique_slug = newpost.slug num = 1 while Temp.objects.filter(slug=unique_slug).exists(): unique_slug = "{}-{}".format(newpost.slug, num) num += 1 newpost.slug = unique_slug newpost.user = request.user # Process the document before saving extracted_text = process_document( request.FILES["file_upload"], newpost.language ) # Save the post and the extracted text newpost.ocr_text = extracted_text newpost.save() # Save the file first form.save_m2m() notify_users_about_new_post(form) messages.success(request, "Your Post has been uploaded successfully.") else: messages.warning(request, "Upload unsuccessful. Please try again.") else: form = TempForm() context = { "posts": posts, "common_tags": common_tags, "form": form, } return render(request, "upload_file.html", context) Currently, users can upload files and it will be stored in S3. I want to extract the content from the file and store it in the mySQL database. I tried different ways and they all failed. I used the following code. It works when I am testing it locally, but fail to download in Production. urllib.request.urlretrieve( [link to S3 storage, where the document can be viewed publicly], "temp.pdf", ) I used boto3. It works when I am testing it locally, but fail to download in Production. import boto3 # … -
How to Write Tests for Password Recovery in Django?
Could you please recommend where to find tutorial examples on how to write tests for authentication in Django, especially for password recovery via email and ensuring that the password reset link is valid only once? I want to add testing to my project, but I lack experience with testing password resets. There are some bugs, and the status code in some places is not what is expected according to the unit tests. The link remains valid after setting a new password, although it stops being valid after setting a new password during manual testing. I would like to see examples of how password recovery is tested in a standard project. ChatGPT is not helping, absolutely useless idiot on this matter. -
Changing from abstractuser to abstractbaseuser mid project to remove username field
I created a project initially with abstractuser so I could add additional fields to users profiles as well as set session variables during user login. Ive realised that abstractuser still has a need for the username field even though I have set authentication field to be email. I have tried setting username = None in the model but it throws an error during makemigrations saying unknown field 'username' specified for CustomUser. If I change the base class from abstract user to abstractbaseuser I still get the error mentioned above when makemigrations. code below, help would be very appreciated. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') user = self.model(email=self.normalize_email(email), **extra_fields,) user.set_password(password) user.save(using=self._db) print("user save from UserManager.create_user method") return user def create_superuser(self, email, password=None, **extra_fields): user = self.create_user(email, password=password, **extra_fields,) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(unique=True, db_index=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone = models.IntegerField(null=False, blank=False) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] def __str__(self): return self.email … -
poorly executed ajax submission
I have a code in django and ajax which, although it works for me, it is supposed that if it creates a user it should give me the if response and it gives me the else response but with the message that "I created the user" however it should not be like that since it also takes the else if you see an error if the gmail already exists... how can I correct this?: var csrftoken = 'YOUR_CSRF_TOKEN_VALUE'; $(document).ready(function() { $('#registrar_usuario').submit(function(event) { event.preventDefault(); // Prevent default form submission var form = $(this); var csrftoken = form.find('input[name="csrfmiddlewaretoken"]').val(); // Validate passwords and required fields if (!validarCamposRequeridos()) { return; // Prevent AJAX request if validation fails } // Send AJAX request to validate email on server $.ajax({ url: '/login/', // URL of the 'validarCampos' view method: 'POST', data: { 'csrfmiddlewaretoken': csrftoken, 'email_usuario': $('#email_usuario').val(), 'nombre_usuario': $('#nombre_usuario').val(), 'fecha_nacimiento': $('#fecha_nacimiento').val(), 'password1': $('#password1').val(), 'password2': $('#password2').val(), }, dataType: 'json', success: function(response) { if (response.success && response.status === 200) { console.log("si ejecuta envio") // aqui se presenta el mensaje cuando deberia mostrar el que funciona xd $('#alertaError').css('color', '#29A52D'); $('#alertaError').text("Usuario creado correctamente!"); // Consider a slight delay if needed setTimeout(function() { $('#registrar_usuario').submit(); // Submit the form after a delay }, … -
django reverting change of user info
I want to change the user email (and other informations about the user) So I created a route for it: @login_required def change_email(request): email = request.POST['email'] if email != request.user.email: request.user.email = email request.user.save() return JsonResponse({ 'message': 'Email updated' }) On the frontend, I get the 'Email updated' message. When I render a template with request.user.email after the change, I can see the new email, but after I reload the page once more, the old value is back there. I tried to manually query the user with refresh_from_db and nothing. I also tried checking through the admin page, and when I check, the value IS updated and then the next requests STILL updated. So I believe that it's something to do with caching and when I manually lookup the cache updates correctly? -
pymysql.err.OperationalError: (1045, "Access denied for user 'Mikael'@'localhost' (using password: NO)")
I've seen many threads and solutions but none have worked for me. I'm trying to run migrations on my django project via Mac. After running python manage.py makemigrations, I get this return stack line 150, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1045, "Access denied for user 'Mikael'@'localhost' (using password: NO)") It made sense that I don't have permissions for my database, so I went ahead and granted privileges for the user stated above ('Mikael'@'localhost') via terminal. To do so, I logged into the root user to grant privileges to 'Mikael'. mysql -u root -p Then granted all privileges for the user grant all privileges on *.* to 'Mikael'@'localhost' WITH grant option; Yet I'm still getting access denied. If it weren't clear through the initial error (in title), I'm using pymysql. I've also granted privileges in user: 'Mikael' -
Creating an Ebola reporting System
[enterenter image description here image description here](https://i.sstatic.net/H3oS2DkO.png) I created the site for reporting and diagnosing ebola cases. it allows for registration of users as either provider or patient, but I get that error when someone tries to register or login. it was created using django and streamlit. -
Django Admin Interface: Understanding Form Saving Behavior with commit Parameter
I'm currently working with Django's admin interface and encountering some unexpected behavior related to form saving with the commit parameter. Here's what I'm trying to understand: Context: I'm using a custom form (DeckCreateForm) with a save method overridden to handle saving deck data. Within this method, I've set the commit parameter to False to prevent immediate database commits. Observation: Despite setting commit to False, when saving a form instance through the admin interface, it appears that the form data is being committed to the database. Understanding Needed: I'm seeking clarification on why the form data is being committed to the database even when commit is explicitly set to False. Additionally, I want to understand the factors that could influence the behavior of the commit parameter within the context of Django's admin interface. Efforts Made: I've reviewed the Django documentation regarding form saving and the admin interface but haven't found a clear explanation for this behavior. I've also examined my code and haven't identified any obvious bugs or misconfigurations. Request: I'm looking for insights or explanations from the Django community on how Django's admin interface handles form saving and the factors that might affect the behavior of the commit parameter. Additionally, … -
salut problement sur django
Hi please I can't share my project developing in django in network so that another machine can access it in the same network as me I don't know what to do I have already run on 0.0.0.0:8000 and in addition to this ALLOWED_HOSTS = ['*'] is configured comsa when I type the ip address of my pc on the other pc without the port I access apache2 but when I add the port it says that this site is inaccessible need to 'help Salut svp je n'arrive pas a partager mon projet developper en django en reseau pour que une autre machine y accede dans le meme reseau que moi je ne sais pas quoi faire j'ai deja run sur 0.0.0.0:8000 et en plus de cela ALLOWED_HOSTS = ['*'] est configurer comsa quand je tape l'adresse ip de mon pc sur l'autre pc sans le port j'accede a apache2 mais quand j'ajoute le port on dit que se site est inaccecible besoin d'aide -
How to Resolve HttpRequest AssertionError in Django Friend Request View?
I'm working on a Django project where users can send and accept friend requests. When a friend request is accepted, I want to add the sender and receiver to each other's friend list and send a notification. However, I'm encountering an error when trying to send the notification. Problem Description: When a user accepts a friend request, I want to add the sender to the receiver's friends list and vice versa. However, I get the following error: AssertionError: The requestargument must be an instance ofdjango.http.HttpRequest, not userauths.models.User. [28/May/2024 16:09:33] "GET /accept-friend-request/?id=8 HTTP/1.1" 500 121207 so let me provide the link api to the function path("accept-friend-request/", views.accept_friend_request, name="accept-friend-request"), let me provide the accept_friend_request function @api_view(['GET']) @login_required def accept_friend_request(request): if request.method == 'GET': sender_id = request.GET.get('id') receiver = request.user # Log the sender_id logger.debug(f"Sender ID: {sender_id}") try: # Retrieve the sender user from the database sender = User.objects.get(id=sender_id) # Retrieve the sender's profile sender_profile = sender.profile # Add sender's profile to receiver's friends and vice versa receiver.profile.friends.add(sender_profile) sender_profile.friends.add(receiver.profile) # Delete the friend request friend_request = FriendRequest.objects.filter(receiver=receiver, sender=sender).first() friend_request.delete() # Send notification send_notification(sender, receiver, None, None, noti_friend_request_accepted) data = { "message": "Accepted", "bool": True, } return JsonResponse({'data': data}) except User.DoesNotExist: logger.error(f"User with ID … -
In django path error when try to submit the normal user regitration from
typ<form action="register" method="post"> {% csrf_token %} <input type="text" name="first_name" placeholder="First name"><br> <input type="text" name="last_name" placeholder="Last name"><br> <input type="username" name="username" placeholder="Username"><br> <input type="email" name="email" placeholder="Email"><br> <input type="password" name="password" placeholder="password"><br> <input type="password" name="confirm_password" placeholder="confirm_password"><br> <input type="submit" name="submit" value="Register"> </form>e here def register(request): # print("in register") # if request.method=="GET": # return render (request,"register.html") if request.method=="POST": print("IN POST") first_name=request.POST.get('first_name') last_name=request.POST['last_name'] username=request.POST['username'] email=request.POST['email'] password=request.POST['password'] confirm_password=request.POST['confirm_password'] user=User.objects.create_user(username=username,password=password,email=email,first_name=first_name,last_name=last_name) user.save() print("User Created") return redirect(home) # if password==confirm_password: # if User.objects.filter(username=username).exists(): # print("Username Already Taken") # elif (User.objects.filter(email=email)): # print("Email Already Taken") # else: # user=User.objects.create_user(username=username,password=password,email=email,first_name=First_name,last_name=Lirst_name) # user.save() # print("User Created") # return redirect('/') # else: # print("Password and Confirm Password Does Not Match") else: return render (request,"register.html") Expecting redirect to home page but its showing error: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/register/register Using the URLconf defined in Finance_Tracker.urls, Django tried these URL patterns, in this order: [name='home'] register/ [name='register'] admin/ The current path, register/register, didn’t match any of these. -
Why isn't my nav updating after htmx trigger?
I have a django project with a left navbar list of projects. I am new to htmx and I'm using it to update the project list after a new project is created from a form. I can see the htmx trigger event and the payload looks correct and the target div element looks correct. However, the update doesn't occur. I've tried including from:body. I have a hx-target in the form and I generate the HX-Trigger in the view, but I'm not sure if that's correct. Here is my views.py: from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from apps.projects.models import Project, ProjectUser from apps.projects.forms import ProjectForm from apps.teams.models import Team from apps.users.models import CustomUser from django.http import JsonResponse from django.db.models import Q from django.shortcuts import render, get_object_or_404, HttpResponse from .utils import is_htmx_request from django.template.loader import render_to_string import logging # Configure logging logger = logging.getLogger(__name__) @login_required def project_create(request, team_slug): print(f'made it in creaTE') team = Team.objects.get(slug=team_slug) form = ProjectForm(team=team) if request.method == "POST": form = ProjectForm(request.POST, team=team) if form.is_valid(): print(f'form: {form}') project = form.save(commit=False) project.team = team project.save() # Save the project to get a project_id members_ids = request.POST.getlist("members") add_from_projects_ids = request.POST.getlist("add_from_projects") # Add current user to the project if … -
How to use poetry in Supervisor
I am trying to run huey, precisely django_huey, but each time I try to connect to DB. in the background task, 'root' is used as the user for the DB. Other parts of the application work well with the database config in django settings, like migration, etc. [program:application] directory=/home/.../django_project command=/home/.../.cache/pypoetry/virtualenvs/..../bin/python /home/.../.../manage.py djangohuey --queue application user='...' autostart=true autorestart=true redirect_stderr = true stdout_logfile = /etc/supervisor/realtime.log environment=PATH="/home/.../.../lib/python3.12/site-packages" stopwaitsecs=30 # task @db_periodic_task(crontab(minute='*/1'), queue='application') def app_task(): # current date and time current_timestamp = timezone.localtime(timezone.now()) # get all event get_events = Mymodel.objects.order_by('-creation_time').filter( time_ends__lt=current_timestamp ) if get_events.exists(): ... Error: connection failed: connection to the server at "127.0.0.1", port 5432 failed: FATAL: password authentication failed for user "root" -
Django View Causing ConnectionError in Production When Fetching TMDB API Data
Problem I am encountering a ConnectionError when trying to fetch data from the TMDB API and add it to my database in a production environment. The error message indicates that the connection was reset by the peer: This issue does not occur in the local development environment. Below are the relevant parts of my views.py and nginx settings. Code Snippets views.py: def SeriesAddView(request): org = Org.objects.first() if request.method == 'POST': tmdb_id = request.POST.get('tmdb_id') reqUrl = f"https://api.themoviedb.org/3/tv/{tmdb_id}?language=en-US" headersList = { "accept": "application/json", "Authorization": f"Bearer {org.tmdb_token}" } payload = "" series_details = requests.request("GET", reqUrl, data=payload, headers=headersList) update_series = Series.objects.filter(tmdb_id=tmdb_id).first() if series_details.status_code == 200: data = series_details.json() genre_data = data["genres"] genre_list = [] for genre_data in genre_data: genre_id = genre_data.get("id") genre_name = genre_data.get("name") if genre_id and genre_name: genre = Genre.objects.filter(genre_id=genre_id).exists() try: genre = Genre.objects.get(genre_id=genre_id) except Genre.DoesNotExist: genre = Genre.objects.create(genre_id=genre_id, name=genre_name) genre_list.append(genre) # Check if the poster image already exists img_path = data["poster_path"] poster_path = f"media/posters/tv{img_path}" if not os.path.exists(poster_path): # Save the poster image locally poster_url = "https://image.tmdb.org/t/p/original" + img_path poster_response = requests.get(poster_url) if poster_response.status_code == 200: with open(f"media/posters/tv/series{img_path}", 'wb') as f: f.write(poster_response.content) if update_series: # Update the existing movie update_series.adult = data["adult"] update_series.title = data["name"] update_series.original_title = data["original_name"] update_series.overview = data["overview"] update_series.release_date = … -
error in django application packaged with pyinstaller version > 5.1
Greetings to the community. I have an issue that is driving me nuts for a long time now. I have a Django application and I am trying to package it with pyinstaller (Windows). Everything works when I use Pyinstaller 5.1, which is quite old. With any pyinstaller version above 5.1, I am getting the following error To make it even weirder, in the more recent versions of pyinstaller it works when using the --console=True option. But i don't want the console to appear in my packaged application. With --console=False, I am still getting the error. Tried to use both python 3.11 and 3.12, i doubt it has anything to do with the python version. From what I could gather from my limited Django knowledge, the NoneType is one of the Django basic models like the User, which are not supposed to be None hence the weird bug. I am sorry, I cannot provide any code from the Django app. Anyone has any idea (so I can start looking somewhere) would be highly appreciated, because now I really don't know what to look for. Thanks -
GeoDjango_Installation_don't_work
in my GeoDjango installation process (https://docs.djangoproject.com/fr/5.0/ref/contrib/gis/install/#windows), GDAL is an important component. I followed the recommendations from the Python website by using OSGeo4W. When I run gdalinfo --version (as you can see in the image), Django recommends installing Python 3.12, which I have already done! I have also installed PostgreSQL and PostGIS. However, when I install OSGeo4W, it directly installs GDAL 0.9. I’m not sure why it’s asking for GDAL 0.8 when I run gdalinfo --version. I also tried another method by following this video https://youtu.be/ZpD-pkmquTo?si=hMsSalfOoGOEg8Eq. When I run pipwin install gdal, I get this error. Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Scripts\pipwin.exe\__main__.py", line 4, in <module> File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Lib\site-packages\pipwin\command.py", line 28, in <module> from . import pipwin, __version__ File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Lib\site-packages\js2py\base.py", line 1377, in __init__ cand = fix_js_args(func) ^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Lib\site-packages\js2py\utils\injector.py", line 27, in fix_js_args code = append_arguments(six.get_function_code(func), ('this', 'arguments')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Lib\site-packages\js2py\utils\injector.py", line 121, in append_arguments arg = name_translations[inst.arg] ~~~~~~~~~~~~~~~~~^^^^^^^^^^ KeyError: 3 ``` Thank you for helping me and not ignoring this. -
If you continue to make changes such as debugging with pythonAnywere 3.10, an error like the one shown in the image will appear
I want to deploy a Django app with pythonAnywhere. If I'm using Python3.12, is it okay to use the latest 3.10? If you continue to make changes such as debugging in 3.10, an error like the one shown in the image will appear. -
list of object evrey object contine image whene i send it from vue.js axios to django viewset the data come messy data
pice of data that come in django <QueryDict: {'user[username]': ['اسم المستخدم'], 'user[password]': ['123'], 'user[first_name]': ['الاسم الاول بيانات الشهادة'], 'user[last_name]': ['بيانات الشهادة الاسم الاخير'], 'user[email]': ['samer@gmail.com'], 'user[date_of_birth]': ['2024-05-21'], 'user[mobile_no]': ['7478888888'], 'user[phone_no]': ['7878787897898'], 'user[gender]': ['1'], 'user_fk_ssn_archive[document_no]': ['22222222222222222222222222222'], 'user_fk_ssn_archive[document_type]': ['1'], 'user_fk_ssn_archive[issue_date]': ['2024-05-21'], 'user_fk_ssn_archive[expiration_date]': ['2024-05-21'], 'user_fk_ssn_archive[issue_place]': ['مكان الاصدار بيانات البطاقة'], 'user_fk_ssn_archive[code]': ['4444444444'], 'user_fk_place_of_brith[street]': ['الشارع بيانات البطاقة '], 'user_fk_place_of_brith[fk_region]': ['1'], 'user_fk_address[street]': ['الشارع بيانات الاقامة'], 'user_fk_address[fk_region]': ['1'], 'academic_qualification[0][fk_qualification][fk_documnet_type]': ['1'], 'academic_qualification[0][fk_qualification][qualification_type]': ['1'], 'academic_qualification[0][fk_qualification][name_ar]': ['الاسم العربي الموؤهل'], 'academic_qualification[0][fk_qualification][educational_level]': ['1'], 'academic_qualification[0][fk_document][document_no]': ['121231231'], 'academic_qualification[0][fk_document][document_type]': ['1'], 'academic_qualification[0][fk_document][issue_date]': ['2024-05-21'], 'academic_qualification[0][fk_document][expiration_date]': ['2024-05-21'], 'academic_qualification[0][fk_document][issue_place]': ['مكان الاصدار المؤهلات'], i used serializer to save data -
Django RESTFRAMEWORK Serializer with nested Serializer
I've got a problem with adding a serializer to another serializer and call it correctly. My models.py with just the WorkshopMaterials Model class WorkshopMaterials(models.Model): id = models.BigAutoField(primary_key=True) workshop = models.ForeignKey(Workshop, on_delete=models.CASCADE, related_name="workshop") material = models.ForeignKey(Material, on_delete=models.CASCADE, related_name="material") amount = models.IntegerField(blank=False, default=1) amountType = models.CharField( max_length=3, choices=AmountType.choices, default=AmountType.PCT, blank=False ) My serializer.py class MaterialSerializer(ModelSerializer): class Meta: model = Material fields = ('id', 'name', 'amount', 'amountType', 'link', 'status') extra_kwargs = {'id': {'read_only': True}} class WorkshopMaterialsSerializer(ModelSerializer): class Meta: model = WorkshopMaterials fields = ('amount', 'amountType', 'material', 'workshop') def to_representation(self, instance): rep = super().to_representation(instance) rep["material"] = MaterialSerializer(instance.material).data["name"] rep["workshop"] = WorkshopSerializer(instance.workshop).data["id"] return rep class WorkshopSerializer(ModelSerializer): class Meta: model = Workshop exclude = ['created_at', 'updated_at'] def __init__(self, *args, **kwargs): fields = kwargs.pop('fields', None) super().__init__(*args, **kwargs) if fields is not None: allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) def to_representation(self, instance): rep = super().to_representation(instance) workshopLeaderData = WorkshopLeaderSerializer(instance.leader).data workshopLeaderName = workshopLeaderData["name"] if workshopLeaderData["displayname"] == "AN": workshopLeaderName = workshopLeaderData["artistname"] rep["leader"] = workshopLeaderName return rep My views.py class WorkshopListView(APIView): #permission_classes = (IsAuthenticated,) def get(self, request): ### TESTED MATERIALS FOR DIFFERENT WORKSHOPS #workshop = WorkshopMaterials.objects.prefetch_related(Prefetch('workshop', queryset=Workshop.objects.filter(id=3))) #serializer = WorkshopMaterialsSerializer(workshop, many=True) ### WORKING FOR LIST VIEW (NO DETAILS) #workshops = Workshop.objects.prefetch_related('workshop').all() #serializer = WorkshopSerializer(workshops, many=True, fields=('id', … -
Filtering queryset depending on incoming parameters?
I have the filter parameters that I get through GET request. These parameters are used for filtering QuerySet: class FilterData(TypedDict): title: str min_price: int max_price: int freeDelivery: bool available: bool tags: list[int | None] As you can see, the list of tags can be empty and this field shouldn't be in the filter query. So what's the best way to change my filter query depending on incoming parameters? if might help, but I'm not sure it's a good solution: if not tags: result = Product.objects.filter( Q( price__gte=filter_data["min_price"], price__lte=filter_data["max_price"], ) & Q(freeDelivery=filter_data["freeDelivery"]) & Q(available=filter_data["available"]) & Q(title__icontains=filter_data["title"])) ).order_by(order_field) else: result = Product.objects.filter( Q( price__gte=filter_data["min_price"], price__lte=filter_data["max_price"], ) & Q(freeDelivery=filter_data["freeDelivery"]) & Q(available=filter_data["available"]) & Q(title__icontains=filter_data["title"]) & Q(tags__contains=[1, 2, 3]) ).order_by(order_field) Thx. -
testing django oauth2_provider authentication endpoint
I need to test o/token endpoint of the oauth2_provider. I wrote the test in pytest. I think I considered every thing but I get invalid_client error. The code: factory: class UserApplicationFactory(factory.django.DjangoModelFactory): name = factory.Faker('pystr', min_chars=5, max_chars=255) client_id = factory.LazyAttribute(lambda _: generate_client_id()) client_secret = factory.LazyAttribute(lambda _: generate_client_secret()) client_type = factory.Iterator(['confidential', 'public']) authorization_grant_type = factory.Iterator(['client-credentials', 'password', 'openid-hybrid', 'authorization-code']) class Meta: model = UserApplication The test: @pytest.mark.django_db def test_token_generation(api_client, user): # secret is 12345 hashed_secret = "pbkdf2_sha256$600000$fB3GLAgzjFjcBAzaHTMyrP$/0qtnsOKi3KRqQgbZ7B0/PcudGTSIgItHXxg9R9Zkf4=" application=UserApplicationFactory( name='test app', client_type='confidential', client_secret=hashed_secret, authorization_grant_type='client_credentials', user=user ) token_url = reverse('oauth2_provider:token') authorization = base64.b64encode( bytes(application.client_id + ":12345" , "ISO-8859-1") ).decode("ascii") bearer = f"Basic {authorization}" data = { "grant_type": "client_credentials", } headers = { "Authorization": bearer, "Cache-Control": "no-cache", "Content-Type": "application/x-www-form-urlencoded", } response = api_client.post(token_url, data=data, headers=headers) response_data = json.loads(response.content) access_token = response_data['access_token'] AccessToken = get_access_token_model() token = AccessToken.objects.get(token=access_token) assert response.status_code == 200 I printed the application.client_secret the result was different from hashed_secret: print(application.client_secret) #result : md5$20JXardwR2tDHMzpZAGkVy$45cdd904b795af35d7a9f64d15086a59