Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Headless wagtail - embed tags in HTML
I've setup a headless wagtail as described on https://learnwagtail.com/tutorials/how-to-enable-the-v2-api-to-create-a-headless-cms/ I embedded a Youtube video. In the API endpoint the HTML is like this: { "id": 4, "meta": { "type": "news.NewsPage", "detail_url": "http://localhost/api/v2/pages/4/", "html_url": "http://localhost/test/", "slug": "test", "first_published_at": "2021-12-05T07:32:32.896276" }, "title": "Test", "date": "2021-12-05", "intro": "", "body": "<p data-block-key=\"yj93z\"></p><embed embedtype=\"media\" url=\"https://www.youtube.com/watch?v=u9n7Cw-4_HQ\"/><p data-block-key=\"71b7p\"></p>", "main_image": null } How can get a normal Youtube embed within this HTML? Any ideas? -
How do I preserve content in database while making on going changes to my code?
How do I avoid overwriting my local database when doing a pull request from remote? further, if I use '.gitignore', will I be able to make structural changes to my DB in the future? (for example, if I want to make changes to a model) I am currently using Django with the sqlite3 DB. -
How do I host a function on a server, which I can call from my python script?
I recently made a program which runs a ML model on an image, and predicts what it is. The problem is that, including the model and the dependencies like tensorflow, caused it to be 500mb. So I was wondering if I could host a function in a server, where I would pass in my image, and it would return the output back. Here's the function I wish to host- from keras.models import load_model from PIL import Image, ImageOps import numpy as np labels= ["Banana", "Fan", "Clock","Coin","Leaf","Paper_airplane","Pen","Phone","Spoon","Tomato"] model = load_model('keras_model.h5') data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) #Here I wish to pass the image, from my python program, and recieve the prediction def RunPrediction(img): image = img size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) image_array = np.asarray(image) normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1 data[0] = normalized_image_array #And I want to recieve this output in my code prediction = model.predict(data) return prediction How do I achieve this? Thanks! -
How can I use django url <slug> as a subdomain (i.e <slug>.domain.com)?
I am quite familiar with django but there is one thing I need to do and I have no idea how. I have a generic details-view page, whose url is /<slug>/ i.e domain.com/<slug> but now I want to change that url to <slug>.domain.com instead. I want to use the slug as a subdomain but I don't have even the slightest idea how to do so. Is there anyway that I can achieve this? -
Disable button on django-comments-dab
this is how it works for me in django-comments-dab and the button is disabled, please help disable button -
Is there any way to get rid of Pylance(reportMissingModuleSource)?
I was following a Django tutorial. But I get this error on my apps.py file 'Import "django.apps" could not be resolved from source Pylance(reportMissingModuleSource)'. I am running the project inside a virtual environment and made sure I'm inside the virtual environment while working on the project. How can I get rid of this error? I am new to Django. -
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>