Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to integrate an MTN Momoapi for money collection and disbursement into your django application?
i want itegrate mtn momoapi into my django project so that i can be able to capture the details of apyments in the database i already managed to signup to mtn sandbox, and writen codes but not the one integration of mtn into the system -
Django app deployment on heroku wsgi module not found
I'm trying to deploy my app and gunicorn works locally but on heroku it doesn't work and it returns a module not found error. Locally, I have noticed that when I run gunicorn locally it works when I'm on the same file as manage.py but when I cd into the higher level file that has the procfile and requirements.txt, it states that "No module named 'SC_BASIS.wsgi'" and the app crashes. My current file directory looks like this: SCBASIS_Website -> {Procfile SC_BASIS README.md requirements.txt} and in SC_BASIS there is {SCBASIS SC_BASIS db.sqlite3 files manage.py} or in words: SCBASIS_Website Procfile SC_BASIS SCBASIS SC_BASIS db.sqlite3 files manage.py README.md requirements.txt My procfile has the following process: web gunicorn SC_BASIS.wsgi When I run gunicorn locally it works in the file where manage.py is. (base) antheaguo@Anthea SCBASIS_Website % cd SC_BASIS (base) antheaguo@Anthea SC_BASIS % gunicorn SC_BASIS.wsgi [2024-01-23 14:18:41 -0800] [38700] [INFO] Starting gunicorn 20.1.0 [2024-01-23 14:18:41 -0800] [38700] [INFO] Listening at: http://127.0.0.1:8000 (38700) [2024-01-23 14:18:41 -0800] [38700] [INFO] Using worker: sync [2024-01-23 14:18:41 -0800] [38701] [INFO] Booting worker with pid: 38701 however when I gocd.. to go up a file and run gunicorn SCBASIS.wsgi, it gives me the error message: (base) antheaguo@Anthea SC_BASIS % cd .. … -
How to define factory with specific random choice for Django model?
i would like to define a factory class for a User django model like this : class User(models.Model): name = models.CharField(null=True, blank=True) created_date = models.DateField(null=True, blank=True) but for all fields, i would like to have a fake value from Faker or None because the model allow null. Ideally, the choice between fake value and None is made by probability for example 90% for fake value and 10% for none. i guess a factory like this class UserFactory(factory.django.DjangoModelFactory): name = factory.Faker("random_choice", elements=[factory.Faker("name"), None], p=[0.90, 0.10])) created_date = factory.Faker("random_choice", elements=[factory.Faker("date"), None], p=[0.90, 0.10])) -
Can't validate form with a many=true field in Django-rest
I am trying to use Django-rest as an api for a front end in astro, the think is I am finding a problem when doing my post: {'items': [ErrorDetail(string='This field is required.', code='required')]} My code is the next one: views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Ticket, Item from .serializers import TicketSerializer, ItemSerializer import json # Create your views here. class TicketView(APIView): def post(self, request, format=None): items = request.data.pop('items')[0] # Items are given as a string with the json format. We need to parse it. items = json.loads(items)[0] # Add the items to the request data data = request.data data['items'] = items data.pop('itemName0') data.pop('itemPrice0') data.pop('itemCount0') print(data) serializer = TicketSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers from .models import Ticket, Item from rest_framework import serializers class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('name', 'price', 'count') class TicketSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True) class Meta: model = Ticket fields = ('img', 'subtotal', 'service', 'tax', 'etc', 'total', 'items') def create(self, validated_data): items_data = validated_data.pop('items') ticket = Ticket.objects.create(**validated_data) for item_data in items_data: Item.objects.create(ticket=ticket, **item_data) return ticket Output of printing the request.data after modifications in the view: … -
Problem in link subdomain in cloudflare to my django app
I have a problem in linking my subdomain on cloudflare to my django app I have a django app on hetzner cloud and I managed to run app on its ip but I could not link it to subdomain in cloudflare xxx.example.com it give me web server is down error 521 What do you think about cloudflare? I managed to run app on hetzner cloud ip -
"from captcha.fields import RecaptchaFields" Is not recognized by wagtailcaptcha
I run my app on docker, and lately, I the web container does not start due to this error File "/usr/local/lib/python3.8/site-packages/wagtailcaptcha/models.py", line 4, in from .forms import WagtailCaptchaFormBuilder, remove_captcha_field File "/usr/local/lib/python3.8/site-packages/wagtailcaptcha/forms.py", line 4, in from captcha.fields import ReCaptchaField ModuleNotFoundError: No module named 'captcha.fields' I have captcha in installed apps, and wagtail-django-recaptcha 1.0 in my requirements.txt. I dropped the container and recreated it but still see the issue. I've read up on different posts including "from captcha.fields import RecaptchaFields" Is not recognized by Pylance but still I could not resolve the issue. -
How do I fix the Cyrillic display?
my_problem_png class Categories(models.Model): name = models.CharField(max_length=150, unique=True, verbose_name="Название") Please help me with this I am very tormented by this problem I'm trying to create a database fixture, but there's some kind of problem with the encoding of Russian characters, according to the guide, everything should work correctly for the YouTuber, but I have some kind of misunderstanding python manage.py dumpdata goods.Categories > fixtures/goods/carts.json -
Django login username label not being overwritten
I added email to be used as an alternative input for the default Django login form and wish to change the label to Username/Email but the common solution I find isn't working. I tried variations on the following and some other solutions with no change to the default Username label. Create a custom login form extending the normal one. class CustomLoginForm(AuthenticationForm): username = forms.CharField( label="Your Custom Label", widget=forms.TextInput(attrs={'autofocus': True}) ) Configure a view to use the custom form with the custom login template. # views.py from django.contrib.auth.views import LoginView from .forms import CustomAuthenticationForm class CustomLoginView(LoginView): authentication_form = CustomAuthenticationForm template_name = 'login.html' Configure the url. # urls.py from django.urls import path from .views import CustomLoginView urlpatterns = [ path('login/', CustomLoginView.as_view(), name='login'), # other URL patterns ] I'm using crispy forms if that matters so in my template I'm using {{ form|crispy }}. I simply want to change the label but am usually getting doubled up labels with common solutions if I include another {{ form.username|as_crispy_field }} in addition to a label tag. Can I remove the label from this latter implementation somehow as a potential solution? I also tried: class CustomAuthenticationForm(AuthenticationForm): def __init__(self, request=None, *args, **kwargs): super().__init__(request, *args, **kwargs) self.fields['username'].label = … -
Is it possible to deploy a Django application that has no frontend component (i.e. is just a backend API)?
Question I have an app that uses Next.js in the frontend and a Django backend. I was able to get the frontend deployed simply enough but I am not sure how to deploy the backend. There is quite a lot of magic happening when using the Vercel deploy so I am not sure how to debug this. According to the Vercel CLI the deploy has completed successfully (I just used the no-arg vercel tool directly from the Django project root directory). The deploy tool appears to have figured out the project was based on Django/python and installed the missing dependencies and such. But now what? When you run a Django server it listens on port 8000 by default. Does Vercel set up a reverse proxy that forwards :80 and :443 connections on to the right place? As far as I am aware, Django does not itself natively support SSL connections (but the default deploy sets up certs and uses it). I suppose this is managed somehow? The behavior I see is that the deployment appears to complete successfully but when I try to hit the domain name in a browser I just see the NOT_FOUND error page: 404: NOT_FOUND Code: … -
How to create a file-like wrapper that works just like a file but auto-delete on close/__del__?
def (): zip_fd = open(zip_path, mode="rb") file = _TemporaryFileWrapper(zip_fd) # Like the one inside tempfile.NamedTemporaryFile return FileResponse(file) # django I would like my file deleted when eventually django is done responsing it -
Database design for hotel rates
I'm designing a lodging management system for a client. Based on this answer I have organized rates on a per-day basis (Django model example): Rate( price=models.DecimalField(...), date=models.DateField(), room_type=models.ForeignKey(RoomType,...), min_nights = models.PositiveIntegerField() ) class Meta: unique_together = ('date', 'room_type') Using this format, the querying speed is acceptable, and implementing a 1-to-1 relationship on rates to dates makes the various calculations quite simple. Here's a screenshot of what a Django rates table might look like: The one stumbling block I've run into is when I attempt to enforce minimum nights. Consider the following: For two consecutive dates, the minimum nights requirement is 2 (e.g. weekend rates: Friday, Saturday). Starting on the next consecutive date (which would be Sunday in this example), the minimum nights requirement is 1 night. Given the above, when a user tries to create a reservation starting on Saturday, the minimum required nights for that rate will be 2. So booking Saturday/Sunday would work, but I want that to be disallowed due to the 2 night minimum starting on Friday. One option I considered was setting minimum nights to 0 when a rate's minimum nights was dependent on the prior day's rate (or maybe several days back if the … -
Django - If user is a certain value display element
I’m currently building a gaming app where a currently logged in user has access to play different games based on their rank in our application. So if a currently logged in user has a rank of let’s say 100 than all the games rank 100 and below will be displayed. The rest of the games will be locked. What would be the best way to achieve this? How can i display unlocked games based on the logged in user’s rank? The rank of each game is the game_rank field in the Game_Info model. The rank of the currently logged in user is the rank field in the User_Info model. My current HTML shows which games are locked and unlocked. Code is below. Any help is gladly appreciated. Thanks! models.py class Game_Info(models.Model): id = models.IntegerField(primary_key=True, unique=True, blank=True, editable=False) game_title = models.CharField(max_length=100, null=True) game_rank = models.CharField(max_length=1000, null=True, blank=True) game_image = models.ImageField(default='default.png', upload_to='game_covers', null=True, blank=True) locked_game = models.BooleanField(default=0) unlocked_game = models.BooleanField(default=0) class User_Info(models.Model): id = models.IntegerField(primary_key=True, blank=True) image = models.ImageField(default='/profile_pics/default.png', upload_to='profile_pics', null=True, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL,blank=True, null=True, on_delete=models.CASCADE) rank = models.CharField(max_length=100, null=True, blank=True, default=1) user_games_enabled = models.ManyToManyField(Game_Info, blank=True, limit_choices_to={'unlocked_game': True}) home.html {% for content in user_profile_games %} {% if content.locked_game == True %} … -
Django not installing inside virtual environment
I am starting a project from scratch, and I noticed that when I run 'pip install django' on my main folder, it says 'requirement already satisfied'. However, when I try to run the 'python manage.py startproject ' it says 'Import error: Couldn´t import Django'. How do I solve this? It worked on another project I started 2 weeks ago, now is not working. When I check the env/lib/site-packages, there is nothing about django there actually. -
Django movable blocks layout
I wanted to know if anyone has ever done this before and if its even possible to do using django. I have a layout of information with 3 blocks of data, but i wanted to give the user the option to move the blocks around in the way that the user see how they would like the data displayed. Maybe user A would like the first 2 blocks to be on top and the last one to be on the bottom User B would like the bottom block to be on top and the other 2 to be on the bottom I can't really find any documentation on how to do something like that, does any one have any information to accomplish that? -
Invalid HTTP_HOST header: '172.12.2.90'. You may need to add '172.12.2.90'' to ALLOWED_HOSTS
When I deploy my django project to elasticbeanstalk I get the message in the log: "Invalid HTTP_HOST header: '172.12.2.90'. You may need to add '172.12.2.90'' to ALLOWED_HOSTS." and so on... I have to add 3 ip adresses like the one above in total for the health to be ok and no error/warning messages. Why is this the case? Where are these domains/IP addresses coming from? Is there any more convenient way to fix this so that I don't have to add random IP adresses to the array ALLOWED_HOSTS = ["mydomain.com"] in settings.py? I created a file and directories in .ebextensions/nginx/conf.d/myconf.conf. This was because according to https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/java-se-nginx.html, it says "To extend Elastic Beanstalk's default nginx configuration, add .conf configuration files to a folder named .ebextensions/nginx/conf.d/". myconf.conf: if ( $host !~* ^("mydomain.com"|"www.mydomain.com")$ ) { return 444; } This didn't work it still gives the same message as before. The way I interpret it is that my django project is on an AWS physical server somewhere and nginx is a middleman between that and my browser. My understanding of Django and AWS is quite basic so I would appreciate it if the answer was as simple as possible. Thanks in advance! -
Django with Postgres: Bulk insert objects ignoring conflicts, then bulk insert related objects
I have two models: Template and TemplateVersion. I want to bulk insert templates and versions so that if the template already exists, it stays as is, but only new version of this template is created. All fields of Template is guaranteed to be together unique. I know that Django can return pks of bulk created instances when using postgres, so I tried that: created_templates = Template.objects.bulk_create(templates_to_create, ignore_conflicts=True) # ... here goes the code to create version objects with pks from `created_templates` TemplateVersion.objects.bulk_create(versions_to_create) Surpisingly, returning pk's don't work together with ignore_conflicts so I don't get pk's in created_templates. So my question is: is it possible to have N templates and M versions created in less queries than N+1 (using loop to manually get_or_create templates and get their pk's) using Django ORM? -
Change <td> color based on number of days left to today [closed]
Below is my table and the data is from database. I am trying to change the td {{ server.daysleft }} /td to a different color based on number of days left to today. For example, the server warranty expiry date is May 16, 2024 and want it automatically change td color when the days less than 100 days. <table class=""> <tr> <th>Name</th> <th>Warranty</th> <th>Days Left</th> </tr> {% for server in server_list %} <tr> <td>{{ server.server_name }}</td> <td>{{ server.server_warrantyexpirydate }}</td> <td>{{ server.daysleft }}</td> </tr> {% endfor %} </table> I just started learning web development and need help. -
How can I correct this error in the project
The project is running but it's showing this error message as well I was not expecting an error message after installing all the directories. Please if there is anyone who can help me I will be greatful. I have tried to correct it for more than a week now but it's still the same error running on my terminal. -
In Django, in Version: 4.1, how to use a css by taking it from the static folder?
There are similar old questions, but they did not solve the problem. Reading the various answers, my code seems ok. In the Version: 4.1.11 of Django, how can i browse the static files folder? Having a path App1/static/css/style.css, i would like to use use in index.html: <link rel="stylesheet" type="text/css" href ="{% static 'css/style.css' %}"> The css file is not found. I'm using {% load static %} at the beginning of index.html and then in settings.py i'm using: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') I tried too: STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) In Installed_Apps, among other things, there is also 'django.contrib.staticfiles' What am I doing wrong? -
How do I not use the web part of Django?
I don't need the web part (for now), the objective is to make an ORM, django has to be a kafka consumer to receive and send to the postregres database I read the docs, but I didn't understand how not to use the web part struct: code (kafka_consumer.py): import pickle from django.shortcuts import render from kafka import KafkaConsumer import environ env = environ.Env() environ.Env.read_env() # def process_message(message: str) -> None: # print(f"message -- {message}") # class KafkaService: # @staticmethod # def kafka_consumer(): # consumer = KafkaConsumer(env("KAFKA_TOPIC"), bootstrap_servers=env("KAFKA_URI"), group_id="test") # for message in consumer: # process_message(message) # Create your views here. def cons(): consumer = KafkaConsumer(env("KAFKA_TOPIC", bootstrap_servers=[env("KAFKA_URI")], api_version=(0,10)) for message in consumer: deserialized_data = pickle.loads(message.value) print(deserialized_data) cons() code settings.py: import environ env = environ.Env() environ.Env.read_env() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("DB_NAME"), 'USER': env("DB_USER"), 'PASSWORD': env("DB_PASSWORD"), 'HOST': env("DB_HOST"), 'PORT': env("DB_PORT"), } } I don't know if it's structured correctly, just follow the official doc: https://docs.djangoproject.com/en/5.0/intro/tutorial01/ -
Cloned rows using jQuery not submitting to post method
I need some help with javascript code im using for my django project. for context, I'm trying to implement a button that adds new rows of inputs. The button does work (currently using jQuery to clone the previous row), but I can't get new rows to submit to the backend via the post method. javascript code: function addRow_editProduct(currentRowCount, productPK) { var rowCounter = currentRowCount + 1; var container = document.getElementById(productPK + '_productMaterialContainer'); var templateRow = $('#' + productPK + '_productMaterial_row' + currentRowCount); var newRow = templateRow.clone(); newRow.attr('id', productPK + '_productMaterial_row' + rowCounter); newRow.find('[id^="' + productPK + '_product_material"]').attr('id', productPK + '_product_material' + rowCounter).attr('name', productPK + '_product_material' + rowCounter); newRow.find('[id^="quantity"]').attr('id', 'quantity' + rowCounter).attr('name', 'quantity' + rowCounter); newRow.find('[id^="unit"]').attr('id', 'unit' + rowCounter).attr('name', 'unit' + rowCounter); newRow.find('[id^="' + productPK + '_productMaterial_pk"]').val(''); newRow.find('select').val('delete'); newRow.find('input[name^="quantity"]').val(''); newRow.find('input[name^="unit"]').val(''); newRow.find('.delete-productMaterial').attr('data-select-element-id', productPK + '_product_material' + rowCounter); $(container).append(newRow); console.log('document', $('#' + productPK + '_productMaterial_row' + rowCounter).find('[id^="' + productPK + '_product_material"]').attr('name')); // var formData = new FormData($('#test')[0]); // for (var pair of formData.entries()) { // console.log(pair[0] + ': ' + pair[1]); // } } html: <div id="{{product_data.product.pk}}_productMaterialContainer"> {% for y in product_data.materials %} <div class="row align-items-center mt-2" id="{{product_data.product.pk}}_productMaterial_row{{ forloop.counter }}"> <input type="hidden" name="{{product_data.product.pk}}_productMaterial_pk{{ forloop.counter }}" id="{{product_data.product.pk}}_productMaterial_pk{{ forloop.counter }}" value="{{ y.pk }}"> <div class="col-4"> … -
Get weakly-referenced Error in Mongoengin
I use mongoengin in django app. each document in mongo has metadata that is dict and in it there is image address with out base_url. in django serializer I add base_url to it but it sometime get error def to_representation(self, instance): # when we search by image result has similarity and it`s milvus similarity and when search by text, # we show it`s reference similarity # obj.similarity: we had image and have similarity from milvus. # obj.metadata.get('similarity') :we don`t have similarity from milvus use matched item similarity. data = super(ResultSerializer, self).to_representation(instance) if instance.similarity is not None: data['similarity'] = decimal.Decimal(distance_to_score(instance.similarity)).quantize( decimal.Decimal('0.000'), rounding=decimal.ROUND_DOWN) else: data['similarity'] = instance.metadata.get('similarity') if frame_url := instance.metadata.get('frame_url'): data.get('metadata')['frame_url'] = SHAHIN_SETTING['base_url'] + frame_url return data Error: Jan 23 16:17:10.527 | develop-shahin-develop-86df584cf6-wtrcm | paginated_data['results'] = ResultSerializer(el_result, many=True).data Jan 23 16:17:10.527 | develop-shahin-develop-86df584cf6-wtrcm | File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 745, in data Jan 23 16:17:10.527 | develop-shahin-develop-86df584cf6-wtrcm | ret = super().data Jan 23 16:17:10.527 | develop-shahin-develop-86df584cf6-wtrcm | File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data Jan 23 16:17:10.527 | develop-shahin-develop-86df584cf6-wtrcm | self._data = self.to_representation(self.instance) Jan 23 16:17:10.527 | develop-shahin-develop-86df584cf6-wtrcm | File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 663, in to_representation Jan 23 16:17:10.527 | develop-shahin-develop-86df584cf6-wtrcm | return [ Jan 23 16:17:10.527 | develop-shahin-develop-86df584cf6-wtrcm | File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 664, in … -
Cannot Access django development server in google cloud VM instance
I am building a practice django application for CI/CD. I am using GitLab for CI/CD. I containerized the django app and pushed it to dockerhub. From dockerhub I am trying to run it on Google Cloud VM instance. In the dockerfile I made 0.0.0.0:8000 as the server out link. The build and deploy in the GitLab is successful. But I cannot access the server through Browser using google cloud IP address. When I tried docker ps it shows the container running on the port. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1c49ac3654d2 repo_name/image_name:V1 "python manage.py ru…" 11 minutes ago Up 11 minutes 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp laughing_hodgkin But if I go to aa.bb.cc.dd:8000 google cloud VM instance IP its not there. It just say **cannot reach this page** My Dockerfile looks like this, FROM python:3.9.18-slim-bullseye WORKDIR /usr/src/app COPY requirements.txt . RUN pip install --upgrade pip RUN curl https://sh.rustup.rs -sSf | sh RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD python manage.py makemigrations CMD python manage.py migrate CMD python manage.py runserver aa.bb.cc.dd:8000 .gitlab-ci.yml file is, stages: - build - deploy build: stage: build image: docker:25.0.0-cli services: - docker:25.0.0-dind variables: DOCKER_TLS_CERTDIR: "/certs" before_script: - docker login -u $DOC_USER_NAME -p … -
Django Rest deployement on CPanel
I am working on django rest project and it's admin side is working fine and properly loading with their static files on local sever. I tried to deploy my project on CPanel where i setup my python setup application successfully but when i load django admin side with live url link it only shows textfields without classes applied. enter image description here Live django endpoint from where django admin tries to load static files is like (https://example.com/api/static/admin/css/base.css) whereas "api" is the Application url of my python app that i setup on CPanel. I also ran "python manage.py collectstatic" command but still server is not able to locate the files. I tried with all above solutions that i mentioned -
Django website trouble accessing models to make queries to the database
I am creating a dietary tracker website which will use Django, python, sql etc. When I try to access the models to make queries to the database, it gives a long error. I am running the test file in my vs code terminal and am using a macbook pro. /opt/anaconda3 /bin/python /Desktop/nea_project/dietary_app/tests.py Traceback (most recent call last): File "/Desktop/nea_project/dietary_app/tests.py", line 1, in \<module\> from models import Food_Table File "/Desktop/nea_project/dietary_app/models.py", line 4, in \<module\> class Participant(models.Model): File "/opt/anaconda3/lib/python3.9/site-packages/django/db/models/base.py", line 129, in **new** app_config = apps.get_containing_app_config(module) File "/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/opt/anaconda3/lib/python3.9/site-packages/django/conf/**init**.py", line 102, in **getattr** self.\_setup(name) File "/opt/anaconda3/lib/python3.9/site-packages/django/conf/**init**.py", line 82, in \_setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Example program I used to make the queries: from models import Food_Table food_names = Food_Table.objects.all('food_name', flat=True) print(food_names) The model I am trying to pull data from: class Food_Table(models.Model): food_ID = models.AutoField(primary_key = True) food_name = models.CharField(max_length = 40) food_description = models.CharField(max_length = 1000)