Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't set up stripe payment method
I'm trying to finish the payment feature on my app, first time trying to do this following a tutorial by Bryan Dunn. I added a SITE_URL like he did but I don't know if I need that since I added a proxy on my package.json and using axios to make api calls, I can use axios instead in this case? And when I click on "Proceed to checkout" button the url doesn't work, I tried changing it to a form.control, it gets redirected to the url but the stripe prebuilt form and product not showing up either. urls: urlpatterns = [ path('', views.getRoutes, name="get-routes"), path('users/register/', views.registerUser, name="register"), path('users/login/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('products/', views.getProducts, name="get-products"), path('products/<str:pk>', views.getProduct, name="get-product"), path('user/profile/', views.getUserProfile, name="get-user-profile"), path('users/', views.getUsers, name="get-users"), path('search/', ProductFilter.as_view(), name="search-product"), path('create-checkout-session/', StripeCheckoutView.as_view()), ] views: class StripeCheckoutView(APIView): def post(self, request): try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'currency': 'usd', 'price': 'price_1MAtSLJU3RVFqD4TnNYWOxPO', 'quantity': 1, }, ], payment_method_types=['card'], mode='payment', success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}', cancel_url=settings.SITE_URL + '/' + '?canceled=true', ) return redirect(checkout_session.url) except: return Response( {'error': 'Something went wrong when creating stripe checkout session'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) cartScreen.js: import React, { useEffect } from "react"; import { Link } from "react-router-dom"; import { Row, Col, Image, ListGroup, Button, Card, Form, } from … -
django How to pass the value returned by ajax to select option?
` <select id='user' class="form-control select2" data-toggle="select2" name="user" required > {% for u in users %} <option value="{{u.id}}" {% ifequal ??? u.id %}selected{% endifequal %}>{{u.username}}</option> {% endfor %} </select> ` $.ajax({ type: 'get', url: "{% url 'list:list_user' %}", dataType: 'json', data: {'u_id': u_id}, success: function(result){ $("#user").val(result.user); }, error: function(){ alert("false"); } }); How to pass the value returned by ajax to select option ??? I was having some trouble designing the edit form, I want select can use the value returned by ajax to select the corresponding text. -
Forgot to migrate free tier Postgres and now my app is empty
My project is again live no problems whatsoever, but the database is empty. I am either trying to restore an old backup to the new Postgres instance or upload a backup from my local disk. But I can’t find any way to do it and I feel a little bit lost. I tried to do pg:restore but I don’t know where to grab the backup (from the free heroKu tier). Hope my ask is clear fellas! Any guide it’s deeply appreciated! -
Comparing django database data with a custom python function not working (Django)
I'm trying to retrieve reserved appointments from database in Django and compare them with custom dates which I have created with a custom function. The problem is that it will work only for the first day and the other days it will copy the appointments from the first day. Please check the images and the code. I think the problem is when I compare using the for loop with jinja in template. {% for date in dates %} <div class="py-2 pr-4"> <button onclick="document.getElementById('id01').style.display='block'" class=""> {{date}}</button> <!-- The Modal --> <div id="id01" class="w3-modal"> <div class="w3-modal-content"> <div class="w3-container"> <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">&times;</span> <h1 class="font-medium leading-tight text-5xl mt-0 mb-2 text-black">Not Available</h1><br><br> <!--Displaying Timeslots--> <!--I think that the problem is here --> {% for a in app %} {% if a.date|date:"c" == date%} {{a.time}}<br> {% endif %} {% endfor %} <br><br> </div> </div> </div> </div> {% endfor %} Please also see the images . all dates generated this appointments are reserved only on the first date,but appears in each date -
How to run Python server in Kubernetes
I have the following Dockerfile which I need to create an image and run as a kubernetes deployment ARG PYTHON_VERSION=3.7 FROM python:${PYTHON_VERSION} ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ARG USERID ARG USERNAME WORKDIR /code COPY requirements.txt ./ COPY manage.py ./ RUN pip install -r requirements.txt RUN useradd -u "${USERID:-1001}" "${USERNAME:-jananath}" USER "${USERNAME:-jananath}" EXPOSE 8080 COPY . /code/ RUN pwd RUN ls ENV PATH="/code/bin:${PATH}" # CMD bash ENTRYPOINT ["/usr/local/bin/python"] # CMD ["manage.py", "runserver", "0.0.0.0:8080"] And I create the image, tag it and pushed to my private repository. And I have the kubernetes manifest file as below: apiVersion: apps/v1 kind: Deployment metadata: labels: tier: my-app name: my-app namespace: my-app spec: replicas: 1 selector: matchLabels: tier: my-app template: metadata: labels: tier: my-app spec: containers: - name: my-app image: "<RETRACTED>.dkr.ecr.eu-central-1.amazonaws.com/my-ecr:webv1.11" imagePullPolicy: Always args: - "manage.py" - "runserver" - "0.0.0.0:8080" env: - name: HOST_POSTGRES valueFrom: configMapKeyRef: key: HOST_POSTGRES name: my-app - name: POSTGRES_DB valueFrom: configMapKeyRef: key: POSTGRES_DB name: my-app - name: POSTGRES_USER valueFrom: configMapKeyRef: key: POSTGRES_USER name: my-app - name: USERID valueFrom: configMapKeyRef: key: USERID name: my-app - name: USERNAME valueFrom: configMapKeyRef: key: USERNAME name: my-app - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: key: POSTGRES_PASSWORD name: my-app ports: - containerPort: 8080 resources: limits: cpu: 1000m memory: 1000Mi requests: cpu: … -
Django Templates Not Updating with CSS Changes
I am currently working on a project using Django and Django Templates, and this also is my first time ever using Django. For this project, I had to overhaul a lot of the design and change a lot of the CSS in the static files. I had previously been running the server on the same Google profile for a while. However, after completing my changes, and running the server on that same Google profile, none of the changes I've made is displayed. However, when I run the server on a guest account, change my Google profile, or run the server on Safari, the changes show. I'm curious to know why this is happening. -
Django, Random migration errors when trying to sync to new Database (PostgreSQL)
I'm currently following a backend tutorial and now were installing postgreSQL into our Django project. But i cannot migrate because of some (for me) random errors. PS: I did install psycopg2 and Pillow. ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd The Errors: PS E:\pythondjango_course\Django\myproject> python manage.py migrate Traceback (most recent call last): File "E:\python\Lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "E:\python\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\db\backends\base\base.py", line 263, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection connection = Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\pythondjango_course\Django\myproject\manage.py", line 22, in <module> main() File "E:\pythondjango_course\Django\myproject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\python\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "E:\python\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\python\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "E:\python\Lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\core\management\commands\migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) … -
Filtering on multiple fields in an Elasticsearch ObjectField()
I am having trouble figuring out the filtering syntax for ObjectFields() in django-elasticsearch-dsl. In particular, when I try to filter on multiple subfields of the same ObjectField(), I'm getting incorrect results. For example, consider the following document class ItemDocument(Document): product = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), 'description': fields.TextField() }) details = fields.ObjectField(properties={ 'category_id': fields.IntegerField(), 'id': fields.IntegerField(), 'value': fields.FloatField() }) description = fields.TextField() I want to find an Item with a detail object that has both category_id == 3 and value < 1.5, so I created the following query x = ItemDocument.search().filter(Q("match",details__category_id=3) & Q("range",details__value={'lt':1.5})).execute() Unfortunately, this returns all items which have a detail object with category_id==3 and a separate detail object with value < 1.5 e.g. { "product": ... "details": [ { "category_id": 3, "id": 7, "value": 20.0 }, { "category_id": 4, "id": 7, "value": 1.0 }, ... ] } instead of my desired result of all items that have a detail object with both category_id==3 AND value < 1.5 e.g. { "product": ... "details": [ { "category_id": 3, "id": 7, "value": 1.0 }, ... ] } How do I properly format this query using django-elasticsearch-dsl? -
Where the .env keys get stored after the nom build command in react?
Hello guys I build a react application using Django as the backend and having many keys at.env file. Now when I build the react app with the ‘npm run build’ command it builds the index file with CSS in the build folder. But where it stores all the keys of the .env file which were used in some components. Or its gets build with all the components -
django-simple-history: How to optimize history diffing?
I am using djangorestframework to display model history alongside which fields have been altered. To add history to my models, HistoricalRecords is being inherited through a modelmixin as shown in docs. Everything is working fine but i have a lot of similar queries (10) and duplicate queries (2). Is there a possible way to optimize this logic (i am out of options) ? // viewsets.py class BaseHistoryModelViewset(viewsets.ModelViewSet): """ Inherit this class to add path '.../history/' to your viewset """ @action(methods=["get"], detail=False, url_path="history") def results_history(self, request, *args, **kwargs): if "simple_history" in settings.INSTALLED_APPS: qs = self.queryset class HistoryModelSerializer(serializers.ModelSerializer): list_changes = serializers.SerializerMethodField() def get_list_changes(self, obj): # Optimize this logic here. if obj.prev_record: delta = obj.diff_against(obj.prev_record) for change in delta.changes: yield change.field, change.old, change.new return None class Meta: model = qs.model.history.model fields = ["history_id", "history_date", "history_user", "get_history_type_display", "list_changes"] serializer = HistoryModelSerializer( qs.model.history.all(), many=True) return Response(serializer.data) return Response(status=status.HTTP_404_NOT_FOUND) // output [ { "history_id": 6, "history_date": "2022-12-04T15:15:09.533340Z", "history_user": 2, "get_history_type_display": "Changed", "list_changes": [ [ "last_login", null, "2022-12-04T15:15:09.516601Z" ] ] }, ... ] -
How to perform a mathematical operation on two instances of object in Django?
I want to add two numbers from two different objects. Here is a simplified version. I have two integers and I multiply those to get multiplied . models.py: class ModelA(models.Model): number_a = models.IntegerField(default=1, null=True, blank=True) number_b = models.IntegerField(default=1, null=True, blank=True) def multiplied(self): return self.number_a * self.number_b views.py: @login_required def homeview(request): numbers = ModelA.objects.all() context = { 'numbers': numbers, } return TemplateResponse... What I'm trying to do is basically multiplied + multiplied in the template but I simply can't figure out how to do it since I first have to loop through the objects. So if I had 2 instances of ModelA and two 'multiplied' values of 100 I want to display 200 in the template. Is this possible? -
How can I write this sql query in django orm?
I have a sql query that works like this, but I couldn't figure out how to write this query in django. Can you help me ? select datetime, array_to_json(array_agg(json_build_object(parameter, raw))) as parameters from dbp_istasyondata group by 1 order by 1; -
http://127.0.0.1:8000 does not match any trusted origins. Docker Django Nginx Gunicorn
I try to log in to the site admin, but display this. I have no clue, this is my code, can someone help me out!!! My All Code Here -
Django rest framework. How i can create endpoint for updating model field in bd?
I wanted to create an endpoint for article_views and update this field in db. I want to change this field on frontend and update it on db. When I go to url(articles/<int:pk>/counter) I want article_views + 1. model.py: Class Articles(models.Model): class Meta: ordering = ["-publish_date"] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255, unique=True) content = models.TextField() annonce = models.TextField(max_length=255, null=True) publisher = models.ForeignKey(User, on_delete= models.DO_NOTHING,related_name='blog_posts') publish_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) article_views = models.PositiveBigIntegerField(default=0) serializers.py: class ArticlesSerializer(serializers.ModelSerializer): tags = TagsField(source="get_tags") author = ProfileSerializer(source="author_id") class Meta: model = Articles fields = ('id','title', 'author', 'tags','annonce', 'content', 'categories', 'article_views') views.py class ArticlesViewSet(viewsets.ModelViewSet): queryset = Articles.objects.all().order_by('title') serializer_class = ArticlesSerializer -
CIDC with BitBucket, Docker Image and Azure
I am learning CICD and Docker. So far I have managed to successfully create a docker image using the code below: Dockerfile # Docker Operating System FROM python:3-slim-buster # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 #App folder on Slim OS WORKDIR /app # Install pip requirements COPY requirements.txt requirements.txt RUN python -m pip install --upgrade pip pip install -r requirements.txt #Copy Files to App folder COPY . /app docker-compose.yml version: '3.4' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 My code is on BitBucket and I have a pipeline file as follows: bitbucket-pipelines.yml image: atlassian/default-image:2 pipelines: branches: master: - step: name: Build And Publish To Azure services: - docker script: - docker login -u $AZURE_USER -p $AZURE_PASS xxx.azurecr.io - docker build -t xxx.azurecr.io . - docker push xxx.azurecr.io With xxx being the Container registry on Azure. When the pipeline job runs I am getting denied: requested access to the resource is denied error on BitBucket. What did I not do correctly? Thanks. -
Django 2.0 website running on a Django 4.0 backend
I am using an old version of Windows, windows 7 to be precise and it seems to only be compatible with Python 3.4 which supports Django 2.0 but heroku doesn't support it anymore So I want to know if I can manually edit the requirements to Django 4.0 and the required Python version in github. I haven't yet tried anything as I am new to this -
Django.models custom blank value
thanks for tanking the time to look at this query. I'm setting an ID field within one of my Django models. This is a CharField and looks like the following: my_id = models.CharField(primary_key=True, max_length=5, validators=[RegexValidator( regex=ID_REGEX, message=ID_ERR_MSG, code=ID_ERR_CODE )]) I would like to add a default/blank or null option that calls a global or class function that will cycle through the existing IDs, find the first one that doesn't exist and assign it as the next user ID. However, when I add the call blank=foo() I get an error code that the function doesn't exist. Best, pb -
How To add Multiple Languages to Web application Based on React and Django Rest API
I had an issue about makeing web application multi languages as I used React with DRF, is the locale way and messages correct to use ? how can I translate only the result data returned on response i sent to react and thank you so much -
printing values django templates using for loop
I have two models interrelated items and broken class Items(models.Model): id = models.AutoField(primary_key=True) item_name = models.CharField(max_length=50, blank=False) item_price = models.IntegerField(blank=True) item_quantity_received = models.IntegerField(blank=False) item_quantity_available = models.IntegerField(blank=True) item_purchased_date = models.DateField(auto_now_add=True, blank=False) item_units = models.CharField(max_length=50, blank=False) def __str__(self): return self.item_name item = models.ForeignKey(Items, default=1, on_delete=models.CASCADE) item_quantity_broken = models.IntegerField(blank=True) item_broken_date = models.DateField(auto_now_add=True, blank=False) item_is_broken = models.BooleanField(default=True) date_repaired = models.DateField(auto_now=True, blank=True) def __str__(self): return self.item.item_name I wrote this view function to retrieve data to a table into a template, def broken_items(request): br = Broken.objects.select_related('item').all() print(br.values_list()) context = { 'title': 'broken', 'items': br, } return render(request, 'store/broken.html', context) this is the executing query, SELECT "store_broken"."id", "store_broken"."item_id", "store_broken"."item_quantity_broken", "store_broken"."item_broken_date", "store_broken"."item_is_broken", "store_broken"."date_repaired", "store_items"."id", "store_items"."item_name", "store_items"."item_price", "store_items"."item_quantity_received", "store_items"."item_quantity_available", "store_items"."item_purchased_date", "store_items"."item_units" FROM "store_broken" INNER JOIN "store_items" ON ("store_broken"."item_id" = "store_items"."id") looks like it gives me all the fields I want.In debugger it shows data from both tables, so I wrote for loop in template, {% for item in items %} <tr> <td>{{item.id}}</td> <td>{{item.item_id}}</td> <td>{{item.item_quantity_broken}}</td> <td>{{item.item_broken_date}}</td> <td>{{item.item_is_broken}}</td> <td>{{item.date_repaired}}</td> <td>{{item.item_name }}</td> <td>{{item.item_item_quantity_received}}</td> <td>{{item.item_quantity_available}}</td> <td>{{item.item_purchased_date}}</td> <td>{{item.items_item_units}}</td> </tr> {% endfor %} The thing is this loop only gives me data from broken table only. I can't see data from Items table. can someone help me to find the reason why other details are … -
Question regarding the object getting serilaized in Django rest
Here I'm with a simple doubt where I'm completely confused. I have Model called ReviewsRatings to shows reviews based on each product.And created a Model Serializer ReviewSerilaizer. In views, am passing this ReviewsRatings instance to ReviewSerilaizer class ShowReviews(APIView): def get(self, request, *args, **kwargs): product_slug = self.kwargs["product_slug"] reviews = ReviewRatings.objects.filter(user=request.user, product__slug=product_slug) if not reviews: return Response([]) serializer = ReviewSerializer(reviews, many=True, context={'request':request}) return Response(serializer.data, status=status.HTTP_200_OK) #Serializer class ReviewSerializer(ModelSerializer): user = SerializerMethodField() class Meta: model = ReviewRatings fields = [ "user", "rating", "review", "created_at", "updated_at", ] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" So my doubt is in def get_user(self, obj) the obj is the product object which am getting. And in the views I,m filtering user = request.user along with product__slug=product_slug. So why Im not getting user object instead getting Products object Here is the Models. class ReviewRatings(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) product = models.ForeignKey(Products, on_delete=models.CASCADE) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)]) created_at = models.DateField(auto_now_add=True) review = models.CharField(max_length=500, null=True) updated_at = models.DateField(auto_now=True) class Meta: verbose_name_plural = "Reviews & Ratings" def __str__(self): return self.product.product_name I don't know it's a dumb question to be asked or I didn't asked the question correctly. But this is making me so confused. -
why form.is_valid() is always false?
I tried to create a contact us form in django but i got always false when i want to use .is_valid() function. this is my form: from django import forms from django.core import validators class ContactForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خود را وارد کنید'}), label="نام ", validators=[ validators.MaxLengthValidator(100, "نام شما نمیتواند بیش از 100 کاراکتر باشد")]) last_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خانوادگی خود را وارد کنید'}), label="نام خانوادگی", validators=[ validators.MaxLengthValidator(100, "نام خانوادگی شما نمیتواند بیش از 100 کاراکتر باشد")]) email = forms.EmailField( widget=forms.EmailInput( attrs={'placeholder': 'ایمیل خود را وارد کنید'}), label="ایمیل", validators=[ validators.MaxLengthValidator(200, "تعداد کاراکترهایایمیل شما نمیتواند بیش از ۲۰۰ کاراکتر باشد.") ]) title = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'عنوان پیام خود را وارد کنید'}), label="عنوان", validators=[ validators.MaxLengthValidator(250, "تعداد کاراکترهای شما نمیتواند بیش از 250 کاراکتر باشد.") ]) text = forms.CharField( widget=forms.Textarea( attrs={'placeholder': 'متن پیام خود را وارد کنید'}), label="متن پیام", ) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__() for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form_field require' this is my view: from django.shortcuts import render from .forms import ContactForm from .models import ContactUs def contact_us(request): contact_form = ContactForm(request.POST or None) if contact_form.is_valid(): first_name = contact_form.cleaned_data.get('first_name') last_name = contact_form.cleaned_data.get('last_name') email = contact_form.cleaned_data.get('email') title = contact_form.cleaned_data.get('title') text = contact_form.cleaned_data.get('text') ContactUs.objects.create(first_name=first_name, last_name=last_name, email=email, … -
how to call a property from values in django
I need the value of the property, which calls through the values call so that later i will use in the union method so used model is class Bills(models.Model): salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) @property def balance(self): return 0 if self.cash == True else self.totalAmount - self.advance when i call the model as bills = Bills.objects.all() I can call the balance property as for bill in bills: bill.balance no issue in above method but i need to use the bills in union with another model so needed fixed vales to call i am calling the method as bill_trans = Bills.objects.filter(purchasedPerson__id__contains = pk, cash = False).values('purchasedPerson', 'purchasedPerson__name', 'cash', 'totalAmount', 'id', 'created') in place of the 'totalamount' i need balance how can i approach this step -
Django cannot save a CharField with choices
I have this CharField with some choices: M = 'Male' F = 'Female' O = 'Other' GENDER = [ (M, "Male"), (F, "Female"), (O, "Other") ] gender = models.CharField(max_length=10, choices=GENDER) When I try and save a model in the database I get the following error: django.db.utils.DataError: malformed array literal: "" LINE 1: ...ddleq', 'Cani', '1971-09-01'::date, '{Male}', '', ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The {Male} value is so because I made the front end send the value like that but it's not that and the error makes no sense. Please can someone tell me why am I getting this error and how to fix it pls? I use the Python 3.8 Django 4.1 PostGreSQL -
nginx unable to load media files - 404 (Not found)
I have tried everything to serve my media file but yet getting same 404 error. Please guide. My docker-compose file: version: "3.9" services: nginx: container_name: realestate_preprod_nginx_con build: ./nginx volumes: - static_volume:/home/inara/RealEstatePreProd/static - media_volume:/home/inara/RealEstatePreProd/media networks: glory1network: ipv4_address: 10.1.1.8 expose: - 8000 depends_on: - realestate_frontend - realestate_backend real_estate_master_db: image: postgres:latest container_name: realestate_master_db_con env_file: - "./database/master_env" restart: "always" networks: glory1network: ipv4_address: 10.1.1.5 expose: - 5432 volumes: - real_estate_master_db_volume:/var/lib/postgresql/data real_estate_tenant1_db: image: postgres:latest container_name: realestate_tenant1_db_con env_file: - "./database/tenant1_env" restart: "always" networks: glory1network: ipv4_address: 10.1.1.9 expose: - 5432 volumes: - real_estate_tenant1_db_volume:/var/lib/postgresql/data realestate_frontend: image: realestate_web_frontend_service container_name: realestate_frontend_con restart: "always" build: ./frontend command: bash -c "./realestate_frontend_ctl.sh" expose: - 8092 networks: glory1network: ipv4_address: 10.1.1.6 depends_on: - real_estate_master_db - real_estate_tenant1_db realestate_backend: image: realestate_web_backend_service container_name: realestate_backend_con restart: "always" build: ./backend command: bash -c "./realestate_backend_ctl.sh" expose: - 8091 volumes: - static_volume:/home/inara/RealEstatePreProd/static - media_volume:/home/inara/RealEstatePreProd/media networks: glory1network: ipv4_address: 10.1.1.7 env_file: - "./database/env" depends_on: - realestate_frontend - real_estate_master_db - real_estate_tenant1_db networks: glory1network: external: true volumes: real_estate_master_db_volume: real_estate_tenant1_db_volume: static_volume: media_volume: My nginx configuration file: upstream realestate_frontend_site { server realestate_frontend:8092; } server { listen 8000; access_log /home/inara/RealEstatePreProd/realestate_frontend-access.log; error_log /home/inara/RealEstatePreProd/realestate_frontend-error.log; client_max_body_size 0; location / { proxy_pass http://realestate_frontend_site; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 0; } } upstream realestate_backend_site { server realestate_backend:8091; } server { listen … -
How to use Django signals when has role based decorators?
I 'm trying to add signals when an employer or admin/staff has created a shift. Currently I have a view like this, I 'm wondering how should I modify it so I can have a post-save signal? @login_required @admin_staff_employer_required def createShift(request): user=request.user employer=Employer.objects.all() form = CreateShiftForm() if request.method == 'POST': form = CreateShiftForm(request.POST) if form.is_valid(): form.save() messages.success(request, "The shift has been created") return redirect('/shifts') else: messages.error(request,"Please correct your input field and try again") context = {'form':form} return render(request, 'create_shift.html', context) Thanks for your help!