Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use double curly brases in double curly brases in Django?
<p><i class="fas fa-print mr-3"></i>{{ contact.phone2|default_if_none:'{{ contact.phone }}'}}</p> I want a value on double curly braces if_none like above. But it makes an error. How can I use it, when Django gives templage tag? -
how to create record in database for each month by participants in django
I am working on an app where a user can create a committee and the participants will pay the amount each month like this.I am quite new with coding and databases so i am little confused. class committee(models.Mode): name= ... per_amount=... and some other columns will go here... class participants(models.Model): parti_name= .. parti_committee_name = models.foreignkey(Committee) some other columns here now what I want is I want the records of each participant for each month, They can only pay once a month and then they are allow to pay next month. now I am confused where to put the month coloumn, is there gonna be a new coloumn for this or not? -
How Can I upload All types of files (videos, audios, pdfs, zip) in cloudinary in django model ? and how can i delete them?
models.py from django.db import models from cloudinary.models import CloudinaryField class File(models.Model): caption = models.TextField(blank=True) file = CloudinaryField() # trying to delete the File model and cloudinary file (error) def delete(self, *args, **kwargs): self.file.delete(*args, **kwargs) super().delete(*args, **kwargs) settings.py import cloudinary import cloudinary.uploader import cloudinary.api ... INSTALLED_APPS = [ '....', 'myapp', 'cloudinary', ] ... cloudinary.config( cloud_name = "...", api_key = "...", api_secret = "...", secure = True ) i can upload images only, when i try to upload any (video, pdf, audio, zip) it says INVALID IMAGE FILE. and sometimes file size error occurs when image size exceeds 10 mb size limit. -
Django Conditional Signals (or better solution)
I have two user types, UserTypeA and UserTypeB. I have created a CustomUser Model, and added a flag is_userA, is_userB in this model. When registering, I am successfully setting the flag for each user type correctly. I have created a model for UserTypeAProfile. When I register a new user, I can successfully create a Profile instance. The issue is that this happens for both UserTypes. I want it to only happen for the UserType that is registering. Below is the CustomUser Model. class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) is_userA = models.BooleanField(default=False) is_userB = models.BooleanField(default=False) def __str__(self): return self.email Below is the UserTypeAProfile Model class UserTypeAProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) bio = models.CharField(max_length=50, blank=True) @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserTypeAProfile.objects.create(user=instance) def __str__(self): return str(self.user) I have tried: @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if CustomUser.is_userA: UserTypeA.objects.create(user=instance) But it doesn't seem to work, still when I test by creating both userTypes, I get a profile instance for both types. Is there a good way to do this? Basically, when userA signs up, I want to create a profile for them with specific UserA attributes, and when userB signs up, I want to create a profile for … -
Custom order field with Django Rest Framework
I have a model like class MyModel(models.Model): COLOR_CODES = ['RED', 'YELLOW', 'GREEN'] name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) colorCode = EnumField(db_column='color_code', choices=COLOR_CODES, null=False, default='GREEN') class Meta: managed = True db_table = 'MyModel' ordering = ['colorCode'] I would like to order the quesryset by colorCode, but not as GREEN, RED, YELLOW items. I want to make the order like RED, YELLOW, GREEN items. Is it possible? Is there something like Java Comparator? Thanks in advance. -
How to upload and save a pickle file to a django rest framework?
As it says in the title, I am trying to upload a model.pkl and save it in an API made in django. I manage to save the model.pkl correctly in the API, however the file is uploaded in a corrupt way, because I cannot read the pickle file. Im open to any solutions that can make the pickle file be uploaded, stored and readed in the API. Class to upload the file and save it class FileUploadView(APIView): parser_classes = (FileUploadParser,) def put(self, request): file = request.data.get('file', None) file_name = f'path/{file.name}' path = default_storage.save(name=file_name, content=ContentFile(file.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) if file is not None: return Response(f'File: {file.name} successfully uploaded and saved!', status=HTTP_200_OK) else: return Response(f'File not found!', status=HTTP_400_BAD_REQUEST) Error when reading the file def read_PickleModel(path_to_PickleModel): with open(path_to_PickleModel, 'rb') as f: pickle_model = pickle.load(f) return pickle_model read_PickleModel(path_to_PickleModel) Traceback: DEBUG: An exception has ocurred: invalid load key, '-'. Im new in this, please before voting down, tell me how do you think I can improve the question to get an accurate solution. -
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