Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to work with 2 or more related tables in a Post request
I have 3 tables: Employee (access for Standart Users) CustomUser (access for Only Adminns) Departament (access for Standart Users) I have a view with react where to store users (only admins can enter) I have another view to store Employees Employees (adminins and standard users can enter) The problem is that I don't know how to manipulate 3 tables in a single request In this view the standard user can register in a single request the data of these 3 tables EndPoints domainapp.com/dashboard/users/ domainapp.com/dashboard/employees/ Employee Logic from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from .models import Employee from .serializer import EmployeeSerializer, DepartamentSerializer # Employee Logic class EmployeeList(APIView): def get(self, request, format=None): employees = Employee.objects.all()[:99] serialized_users = EmployeeSerializer(employees, many=True) return Response(serialized_users.data, status=status.HTTP_200_OK) class EmployerRegister(APIView): def post(self, request): # save all fields all tables serialized_user = EmployeeSerializer(data=request.data) serialized_employee = EmployeeSerializer(data=request.data) serialized_departament = DepartamentSerializer(data=request.data) if serialized_user.is_valid() and serialized_employee.is_valid( ) and serialized_departament.is_valid(): # this is wrong? serialized_user.save() serialized_employee(serialized_user) serialized_employee.save() serialized_departament(serialized_user) serialized_departament.save() return Response(serialized_user.data, status=status.HTTP_201_CREATED) return Response(serialized_user.errors) -
Django - Why does Django set `request.data` to QueryDict class when a file is attached, but a dict when no file is attached?
So I have a test where I don't attach a file to the request >>>request.data {'description': 'Some Goal text', 'end_date': '2021-12-04', 'goal_category': 'health', 'body': 'Some text #blah\r#weeeee\x0c#foo', 'creator': '6badb4b8-33ba-4bb9-aa9a-2e3afb359960', 'type': <PostType.DECLARE: 'DE'>} >>>type(request.data) <class 'dict'> >>> denotes where I input into the debug console and below it is what is printed out. Then I attach a file and send in the request and I get this. >>>type(request.data) <class 'django.http.request.QueryDict'> >>>request.data <QueryDict: {'join_goal': ['d2f5aa8d-4cd0-4051-9d1a-35b28af276d5'], 'body': ['Some text and an image'], 'images': [<InMemoryUploadedFile: test.jpg (text/plain)>], 'creator': ['6badb4b8-33ba-4bb9-aa9a-2e3afb359960'], 'type': [<PostType.UPDATE: 'UP'>]}> Why does Django use a QueryDict when an image comes in? -
How can I save a variable (or data) that I send in a view to a html to use it in another view redirected to another view?
I am quite new and wanted to know if it is possible that a data that you send in a view to your html, take it and with a button send it to another view that redirects it (or save it in the database to use it in the view ) Excuse me if the question is very silly, I am very new to programming. this is the view that has the data that I want to save def selectCombat(request): enemigosFacil = Enemigo.objects.filter(dificultad__contains = 'Facil') enemigosMedio = Enemigo.objects.filter(dificultad__contains = 'Medio') enemigosDificil = Enemigo.objects.filter(dificultad__contains = 'Dificil') enemigoRandomFacil = str(random.randint(11, 19)) enemigoRandomMedio = str(random.randint(1, 9)) enemigoRandomDificil = str(random.randint(20, 25)) enemigoSelecFacil = Enemigo.objects.get(pk=enemigoRandomFacil) enemigoSelecMedio = Enemigo.objects.get(pk=enemigoRandomMedio) enemigoSelecDificil = Enemigo.objects.get(pk=enemigoRandomDificil) equipoPokemonFacil = (enemigoSelecFacil.equipo).split(',') equipo_pokemonMedio = (enemigoSelecMedio.equipo).split(',') equipo_pokemonDificil = (enemigoSelecDificil.equipo).split(',') equipoPokemonFacil = armarDificultad(equipoPokemonFacil) equipo_pokemonMedio = armarDificultad(equipo_pokemonMedio) equipo_pokemonDificil = armarDificultad(equipo_pokemonDificil) perfilEnemy = Enemigo.objects.all() print(enemigosFacil[0].imag) print(enemigoSelecDificil) context = { 'perfilEnemys': perfilEnemy, 'equipoPokemonFacil':equipoPokemonFacil, 'equipo_pokemonMedio':equipo_pokemonMedio, 'equipo_pokemonDificil':equipo_pokemonDificil, 'enemigosFacil':enemigosFacil, 'enemigosMedio':enemigosMedio, 'enemigosDificil':enemigosDificil, 'enemigoSelecFacil':enemigoSelecFacil, 'enemigoSelecMedio':enemigoSelecMedio, 'enemigoSelecDificil':enemigoSelecDificil } return render(request,'social/combates.html',context) # return render(request,'social/combates.html',{'listaPokemonEnemigo':listaPokemonEnemigo}) def armarDificultad(equipo_pokemon): listaPokemonEnemigo = [] for i in equipo_pokemon: url = "https://pokeapi.co/api/v2/pokemon/" + str(i) response = requests.get(url) content = response.json() pokemonEnemigo= { 'name':content['name'], 'id':content['id'], 'sprites':content['sprites']['front_default'], 'types':content['types'][0]['type']['name'] } listaPokemonEnemigo.append(pokemonEnemigo) return listaPokemonEnemigo def batalla(request): return render(request, 'social/batalla.html') this is the button with the … -
Django Create View URL conflicts with Single View URL
My url.py file is as below. urlpatterns = [ path('', views.loans, name='loans'), path('loans/<str:pk>/', views.loan, name='loan'), path('loans/create/', views.create_loan, name='create-loan'), ] Whenever I try to access the loans/create route, Django throws the below exception. ValidationError at /loans/create/ ['“create” is not a valid UUID.'] It looks like Django is passing 'create' into 'loans/<str:pk>/' How can I resolve this? Thanks in advance. -
Django websocket asgi on cpanel
can someone tell me how we can host Django channel websocket app via asgi on cpanel, Thanks you already for your answers! when i use passenger_wsgi with wsgi the websocket not work he getting an error route not found. -
Heroku pipelines - How do I make staging apps working on a different database compared to production apps?
I have a django app and I am deploying it using Heroku pipeline. I am trying to understand what's the best way to handle the fact that each staging apps should not use production databases (right?) What's the best way to do so? It seems that I can't set env variable that are "phase" specific (can i?) -
Django select objects where field is in range
I have a django model called MyModel which has two fields: a = models.IntegerField(...) b = models.DateTimeField(...) I would like to select all of the MyModels which have an a value between 0 and 10. For example: results = [obj for obj in MyModel.objects.all() if 0 <= obj.a <= 10] This works, but requires looping through every row in Python and is not efficient whatsoever. As an extension to this, how would I perform a similar query for field b, selecting every object which has time within the last 15 minutes. This is how I would write the query in SQL: SELECT * FROM appname_mymodel WHERE TIMESTAMPDIFF(MINUTE, b, CURRENT_TIMESTAMP) <= 15; I would like a python + django way of writing this query, if possible. -
Add an action to filter nested APIs
I have two models with one to many relationship and I would like to add an action in order to be able to list all object A (startups) with at least one nested object B having attribute active to True. I have added this extra action however it's returning an error : 'Q' object is not callable here is my code : @action(detail=False, methods=['get']) def get_active_startups(self, request, pk=None): Startup.objects.annotate( active_investments=Count('startup_investments', filter=Q(startup_investments__active=True)).filter( active_investments__gt=0)) My second question is if this code works will it hit the DB each time I request this list? if so is there a better way to do the same on serializer level? Here are my serializeres : class InvestmentSerializer(serializers.ModelSerializer): class Meta: model = Investment fields = ('id', 'Investment_title', 'collected_amount', 'goal_percentage', 'number_of_investors', 'days_left', 'active') class StartupSerializer(serializers.ModelSerializer): startup_investments = InvestmentSerializer(many=True, read_only=True) class Meta: model = Startup fields = ('id', 'header', 'title', 'description', 'tags', 'card_image', 'logo_image', 'main_img', 'startup_investments') I want to to list startups with as least one invetment having field active set to true. Thanks -
Django-python- TestCase - transactions should never have a timestamp in the Future
I am working on a payment system that is registering transactions and timestamps. I would like to make a test to ensure that transactions are only made on a past date - it should not be possible to have a transaction with a future date. models.py 20 class Ledger(models.Model): 19 account = models.ForeignKey(Account, on_delete=models.PROTECT) 18 transaction = models.ForeignKey(UID, on_delete=models.PROTECT) 17 amount = models.DecimalField(max_digits=10, decimal_places=2) 16 timestamp = models.DateTimeField(auto_now_add=True, db_index=True) 15 text = models.TextField() 14 13 @classmethod 12 def transfer(cls, amount, debit_account, debit_text, credit_account, credit_text, is_loan=False) -> int: 11 assert amount >= 0, 'Negative amount not allowed for transfer.' 10 with transaction.atomic(): 9 if debit_account.balance >= amount or is_loan: 8 uid = UID.uid 7 cls(amount=-amount, transaction=uid, account=debit_account, text=debit_text).save() 6 cls(amount=amount, transaction=uid, account=credit_account, text=credit_text).save() 5 else: 4 raise InsufficientFunds 3 return uid 2 1 def __str__(self): 122 return f'{self.amount} :: {self.transaction} :: {self.timestamp} :: {self.account} :: {self. text}' I honestly don't even know where to start testing this class because Testing is very new to me. I have tested some things I saw online close to the below, but cannot see anything happening. Does it make any sense? Maybe there is something that makes more sense testing here instead... Suggestions are more … -
Type Hint for Django model with annotated field
Let's say I have the following Django models: class Toolbox(models.Model): name = models.CharField(max_length=255) tools = models.ManyToManyField("Tool") class Tool(models.Model): class Size(models.TextChoices): SMALL = "S" MEDIUM = "M" LARGE = "L" name = models.CharField(max_length=255) size = models.CharField(max_length=10, choices=Size.choices) I have a function to get all small tools for each toolbox. The argument type hint comes from this SO answer: from django.db.models import QuerySet def get_toolbox_to_small_tools_mappings( toolboxes: QuerySet | list[Toolbox], ) -> dict[Toolbox, list[Tool]]: return {toolbox: toolbox.small_tools for toolbox in toolboxes} The idea here is to require users of this function to prefetch this small_tools field using prefetch_related() to reduce the number of db hits and speed up the code: toolboxes = Toolbox.objects.prefetch_related( Prefetch( "tools", queryset=Tool.objects.filter(size=Tool.Size.SMALL), to_attr="small_tools", ) ) toolbox_to_small_tools_mappings = get_toolbox_to_small_tools_mappings(toolboxes) This all works great but mypy is complaining with the following error: error: "Toolbox" has no attribute "small_tools" [attr-defined] Is there anyway to fix this? The WithAnnotations[Model] type from django-subs (see here) is an option but it's buggy. -
Django writable nested serializers, create method not working
I have a nested serializer, the create method does not work. I have searched over the internet and no method worked for me. The most popular one is the one listed below. models.py class Displays(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) name = models.CharField(max_length=45, blank=True, null=True) class OrdersDj(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) class AdsDj(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) order = models.ForeignKey( OrdersDj, on_delete=models.CASCADE, blank=False, null=True) display = models.ForeignKey( Displays, on_delete=models.CASCADE, blank=True, null=True) serializers.py class AdsSerializer(serializers.ModelSerializer): display = DisplaySerializer() def create(self, validated_data): print("validated_data", validated_data) display_id = validated_data.pop('display') display = Displays.objects.get(id=display_id) ad = Displays.objects.create(display=display, **validated_data) return ad class Meta: model = Ads fields = "__all__" class OrderSerializer(serializers.ModelSerializer): ads = AdsSerializer(source="adsdj_set", many=True) def create(self, validated_data): validated_data.pop('adsdj_set') order = Orders.objects.create(**validated_data) return order class Meta: model = Orders fields = "__all__" views.py class AdsCreate(APIView): def put(self, request): print('request.data', request.data) serializer = serializers.AdsSerializer(data=request.data) if serializer.is_valid(): serializer.save() print('serializer.data > serializer.valid', serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) print('serializer.errors > serializer.invalid', serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) print outs request.data <QueryDict: {'order': ['18bb2225cf6e407a943f2941072d06de'], 'display': ['91'], 'firstday': ['2021-12-4'], 'lastday': ['2021-12-21'], 'duration': ['17'], 'filetype': ['image/png'], 'originalname': ['Picture1.png'], 'price': ['2550'], 'status': ['0'], 'filehash': ['not available yet'], 'orderByNum': ['-1'], 'imgWidth': ['1061'], 'imgHeight': ['708'], 'image': [<InMemoryUploadedFile: Picture1.png (image/png)>]}> serializer.errors > serializer.invalid {'display': [ErrorDetail(string='This field is required.', code='required')]} … -
ERROR: Failed building wheel for twisted-iocpsupport
I am getting error while using command git push heroku master error is ERROR: Could not build wheels for twisted-iocpsupport, which is required to install pyproject.toml-based projects how can I remove this error -
suppress form field errors in Django
I have my form (code below) - it's working perfectly. But it's showing the form field errors, even before it's been submitted (on page load!). Is there a way to supress the errors, if the form hasn't been submitted? <form method="post"> {% csrf_token %} {% for field in form %} <p> <font color = 'white'>{{ field.label_tag }}</font> <br>{{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> -
Testing a custom auth backend with Django RestFramework
I created a custom authentication backend for my DRF application. I can't figure out how to test it. Calling the client.post calls my authenticate function (cause that's in my view) But I need to mock an internal method in my ModelBackend. Kinda confused how to go about this? View: class Web3UserToken(APIView): authentication_classes = [] permission_classes = [] def post(self, request, **kwargs): public_address = request.data["public_address"] web3 = Web3Backend() user, token = web3.authenticate(request) if token: return JsonResponse({'token': token}) else: return Response({'message': 'Missing token'}, status=400) Test: class TestWeb3AuthBackend(APITestCase): def setUp(self): #TODO: set up test user self.client = APIClient() #self.factory = APIRequestFactory() def test_authenticatepasseswithexistinguser(self): self.user = Web3User(public_address=TEST_PUBLIC_ADDRESS) auth_backend = Web3Backend() import ipdb; ipdb.sset_trace() request = self.client.post('/api/token/', {'public_address': TEST_PUBLIC_ADDRESS, 'nonce': '0xsomething_random'},follow=True) with mock.patch.object(auth_backend, '_check_nonce', return_value=True) as method: token, user = auth_backend.authenticate(request) self.assertTrue(token) self.assertTrue(user) -
Validation not working, defined max and error message but even then not working
I want that participant can not place bid for more than the remaining fund. If he has invested in 30 each in first three rounds, he can not invest more than 110 in the next round.(200-3*30) I am not getting any error while running this, but validation is not working, the error message is not popping up. even if the first investment bid is more than 200. I want that total bids compiled for all rounds should not cross the budget given initially. Please help class Constants(BaseConstants): name_in_url = 'C' players_per_group = None num_rounds = 18 budget = 200 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): invest = models.IntegerField( label="How much would you like to invest in this proposal?", min=0 ) total_invest = models.IntegerField() # PAGES class MyPage(Page): form_model = 'player' form_fields = ['invest'] @staticmethod def total_invest(player: Player): player_in_all_rounds = player.in_all_rounds() return sum([p.invest for p in player_in_all_rounds]) @staticmethod def avail_invest(player: Player): return Constants.budget - player.total_invest @staticmethod def invest_error_message(player, value): print('value is', value) if value > player.avail_invest: return 'Cannot invest more than your remaining fund' class ResultsWaitPage(WaitPage): pass **strong text** class Results(Page): pass page_sequence = [MyPage] -
Simulate server restart in Django tests
I am working on a package for caching Django querysets in redis. I want to simulate server restarts in tests so I can see if the objects are still cached after server restars. Package -
embedding jupyter notebook/ google colab in djnago app
I wanted to build a website and embed the jupyter notebook functionality of being able to create cells and run python code within it into my website For creating a website I m using Django and I would like to embed either the google collab or jupyter notebook By the way I have researched enough and have been stuck with the StackOverflow links where there no answer about this or the one where they want to use django in jupyter notebook Thanks in advance for any guidance or any reference that you guys can provide. -
Django Gmail auth fails despite correct credentials
My sending mail from django through gmail suddenly stopped working. It was working fine for over a year now, so I assume my basic setup should still be fine. The Google Account in question has 2FA enabled and the password used in the config below is a generated app-password, not the main accuont password. I already logged into Gmail via browser and checked that it hasn't been locked and that it isn't over quota. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '<MY-MAIL-ADDRESS>' EMAIL_HOST_PASSWORD = '<PASSWORD>' DEFAULT_FROM_EMAIL = '<MY-MAIL-ADDRESS>' I already verified my credentials by using the command below: (ofc shell expansion doesn't work i just pasted the output of the command at that location) $ openssl s_client -connect smtp.gmail.com:587 -starttls smtp >AUTH PLAIN $(echo -ne '\0MY-MAIL-ADDRESS\0PASSWORD' | base64) >235 2.7.0 Accepted However, if I try to use send_mail it bounces: In [1]: from django.core.mail import send_mail In [2]: send_mail('Subject', 'This is a test message', 'MY-MAIL-ADDRESS', ('recipient@address.com',)) (Output shortened) SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials r17sm9826202wmq.5 - gsmtp') Any hints on what might (suddenly) be wrong? -
Django - TypeError: put() missing 1 required positional argument: 'filename'
I am trying to upload a pdf file or a pickle file through an API made in Django using FileUploadParser. However, when making the API call using postman using the put method, I get the following error, even using the right HTTP header: TypeError: put () missing 1 required positional argument: 'filename' Here is how it looks my POSTMAN header and body: views.py urls.py -
Can security vulnerabilities in npm packages be of concern for a ReactJs/Django website?
I am developing a website with React.js frontend and Django backend. After updating all npm packages to their newest versions and performing npm audit fix, I still get the following message from npm audit: found 14 vulnerabilities (8 moderate, 5 high, 1 critical) run `npm audit fix` to fix them, or `npm audit` for details I wonder whether I should be concerned about these vulnerabilities, given that they concern only the frontend? When I wrote the backend, I always assumed that an ill-intending user can substitute the frontend and submit any request whatsoever to the backend. -
Deploying asgi django on heroku
I'm unable to deploy asgi django on heroku. Build is successful but it shows Application Error after deployment. Here is my procfile Here is my asgi file here is routing.py here is settings.py Also i've no add-ons on heroku. Please help me out how can i deploy it on heroku. Your any advice would be highly appreciable. Thank you in advance -
Django virtual environment wrong directory
I need help with setting up my virtual environment for Django. I am creating a virtual environment for the Django directory, as shown in the picture. But somehow the virtual environment is created in the gurtaj directory. -
TypeError at /accounts/signup/ View.__init__() takes 1 positional argument but 2 were given
I am using Django allauth to authenticate users to signup and login. But this error TypeError at /accounts/signup/ View.__init__() takes 1 positional argument but 2 were given comes up as I try to access django allauth signup and login templates. callback <class 'allauth.account.views.SignupView'> callback_args () callback_kwargs {} middleware_method <bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at 0x0000017B8F25B070>> request <WSGIRequest: GET '/accounts/signup/'> response None self <django.core.handlers.wsgi.WSGIHandler object at 0x0000017B8DF32290> wrapped_callback <class 'allauth.account.views.SignupView'> -
Django 3.2 - querie multiple Models in view (SQL comparison)
I'm quite new to django and have problems with the ORM and the view-queries. We have already migrated and synched some Models from our productive DB to the django DB, but I have problems with connecting two Models to each other. e.g. models.py: class SsdgSendung(models.Model): sdg_sdgid = models.CharField(primary_key=True, max_length=30) sdg_konz = models.CharField(max_length=12, blank=True, null=True) class Meta: db_table = 'ssdg_sendung' class SsdaSdgadr(models.Model): sda_sdgid = models.ForeignKey(SsdgSendung, on_delete=models.CASCADE, blank=True, null=True) sda_satid = models.CharField(max_length=4, blank=True, null=True) class Meta: db_table = 'ssda_sdgadr' unique_together = (('sda_sdgid', 'sda_satid'),) Sample Data SsdgSendung: sdg_sdgid = BL-1237781-BL-1 sdg_konz = 009874 SsdaSdgadr: sdg_sdgid = BL-1237781-BL-1 sda_satid = IV sdg_sdgid = BL-1237781-BL-1 sda_satid = CN How should the correct "django"-query look for this equivalent SQL: SELECT * FROM SsdgSendung inner join SsdaSdgadr on sdg_sdgid = sda_sdgid and sda_satid = 'IV' WHERE sdg_konz = '1234' I tried this, but I don't get any result on the template: Sendungen = SsdgSendung.objects.filter(sdg_konz = current_user_konz).order_by('-sdg_datum').prefetch_related('sda_sdgid') template {% for la_item in SDG_Overview %} <tr> <td>{{ la_item.sdg_sdgid }}</td> <!-- works well --> <td>{{ la_item.sda_satid }}</td> <!-- don't work --> </tr> -
Django How to connect in local network to my chatt app (channels and redis)
I've implemented the Stein example! https://codewithstein.com/django-realtime-chat-app-tutorial-simple-django-tutorial-with-channels-and-redis/ It works! However, only on my computer! If I try to connect to the local network from another computer, nothing comes out. Earlier, when it was just WSGI, I connected. I think there is also docker involved. That my settings: docker run -p 6379:6379 -d redis:5 - ((I thing this note is wrong for local network) CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('192.168.1.126', 6379)], - my local ip # ('127.0.0.1', 6379) }, }, And last command what i use: python manage.py runserver 192.168.1.126:8000