Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Redirect to previous page when login form submitted
How would I get the djangos built in LOGIN_REDIRECT_URL to redirect to previous page before logging in? I have tried: LOGIN_REDIRECT_URL = 'request.META.HTTP_REFERER' LOGOUT_REDIRECT_URL = 'request.META.HTTP_REFERER' - 
        
how to write complex sql-constraints with django-db-models
I want to know how to write a complex sql-constraints like below with django . create table fiscalyeartable (fiscal_year integer not null primary key, start_date,date not null, constraint valid_start_date check((extract(year from start_date)=fiscal_year-1) and(extract (month from start_date)=10) and(extract (dat from start_date)=01)), end_date date not null, constraint valid_end_date check((extract(year from end_date)=fiscal_year) Is it possible? I find this constraint from first problems of『sql puzzles and Answers 』. I wrote code like this. class FiscalYear(models.Model): fiscal_year=models.IntegerField(unique=True) start_date=models.DateField(unique=True) end_date=models.DateField(unique=True) class Meta: db_table="fisical_year" constraints=[ models.CheckConstraint( check=Q(end_date__gte=F("start_date")+timedelta(days=365)), name="end_date constarint") , models.CheckConstraint( check=Q(end_date__month="9"), name="month constraint") ] - 
        
Why my django project doesn't see the changes I made in my html file?
I'm working with "Web Development with Django" book where I'm building bookr project. It is a web page that shows books, their reviews and ratings. I am on chapter 5, where main thing that I am supposed to do is to add logo image to my page using static file serving and block brand. My main base.html in templates directory has everything required to call static image from another html file directory: bookr/templates/base.html {% load static %} <a class="navbar-brand" href="/">{% block brand %}Book Review{% endblock %}</a> Another base.html has block brand directory: bookr/reviews/templates/reviews/base.html {% extends 'base.html' %} {% load static %} {% block brand %}<img src="{% static 'static/logoo.png' %}">{% endblock %} the logo image is in this directory: bookr/reviews/static/logoo.png (it is not corrupted and working perfectly well) the setting.py for templates looks like this TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and finally the view.py def index(request): return render(request, "base.html") I want to note that any changes on html are not working, I tried to make the whole page red, django doesn't show any mistakes - 
        
User Authorization with Djoser, DRF and Pinia
I've been facing difficulties with authorization for several days now. While my authentication appears to be functioning properly, I haven't been able to successfully implement posting data to my backend that uses DRF and Djoser. I think the issue is minor and I'm using Pinia, Nuxt3, Django, and DRF. my settings INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken', 'djoser', 'corsheaders', 'blog', 'users', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } MIDDLEWARE = [ 'django.contrib.auth.middleware.AuthenticationMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] my main urls from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), path('user/', include('users.urls', namespace='user')), ] and user urls from django.urls import path, include from .views import CustomUserViewSet app_name = 'user' urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path('auth/', include('djoser.urls.jwt')), path('custom/', CustomUserViewSet.as_view({'get': 'list'}), name='custom-list'), path('custom/<int:pk>/', CustomUserViewSet.as_view({'get': 'retrieve'}), name='custom-detail'), ] and my views from django.shortcuts import get_object_or_404 from rest_framework import generics, status, permissions from rest_framework.response import Response from .models import Category, Comment, Post from .serializers import PostSerializer, CommentSerializer, CategorySerializer User = get_user_model() class PostListCreateAPIView(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer lookup_field = "slug" permission_classes = [permissions.IsAuthenticated] def create(self, request, *args, **kwargs): … - 
        
Resolve function resolving wrong view_name in django
Django 4.0 Python 3.9 I recently upgraded my django project from 3.14 to 4.0 and django.urls.resolve function seems broken. Resolve is always returning app_name.views.view instead of app_name.views.actual_function_name. Here is my code - path = request.path match = resolve(path) view_name = match.view_name after the above code "view_name" variable is always "view" irrespective of the url. Any help is appreciated. Thanks for your time. - 
        
dynamic choice field got 'Select a valid choice. That choice is not one of the available choices'
I have 5 simple model class like this # Province class Provinsi(models.Model): id = models.CharField(max_length=3, primary_key=True) name = models.CharField(max_length=40) def __str__(self) -> str: return self.name # City class Kota(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=40) parent = models.ForeignKey(Provinsi, on_delete=models.CASCADE) def __str__(self) -> str: return self.name # District class Kecamatan(models.Model): id = models.CharField(max_length=8, primary_key=True) name = models.CharField(max_length=40) parent = models.ForeignKey(Kota, on_delete=models.CASCADE) def __str__(self) -> str: return self.name # Vilages class Desa(models.Model): id = models.CharField(max_length=12, primary_key=True) name = models.CharField(max_length=40) parent = models.ForeignKey(Kecamatan, on_delete=models.CASCADE) def __str__(self) -> str: return self.name # Locations class Lokasi(models.Model): name = models.CharField(max_length=10) provinsi = models.ForeignKey(Provinsi, on_delete=models.CASCADE) kota = models.ForeignKey(Kota, on_delete=models.CASCADE, blank=True) kecamatan = models.ForeignKey(Kecamatan, on_delete=models.CASCADE, blank=True) desa = models.ForeignKey(Desa, on_delete=models.CASCADE, blank=True) def __str__(self) -> str: return self.name All first 4 class don't have admin page, it's "injected" using custom manage command admin.py looks like class LokasiAdmin(admin.ModelAdmin): form = LokasiAdminForm change_form_template = 'lokasi_change.html' admin.site.register(Lokasi, LokasiAdmin) the template (lokasi_change.html) have some ajax call to update some choice fields based on change of other choice field. {% extends "admin/change_form.html" %} {% block after_field_sets %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> // add listeners document.getElementById("id_provinsi").addEventListener("change", changedProvinsi); document.getElementById("id_kota").addEventListener("change", changedKota); document.getElementById("id_kecamatan").addEventListener("change", changedKecamatan); function changedProvinsi(){ var myselect = document.querySelector('#id_provinsi'); var myvalue = myselect.value; var baseurl = window.location.origin; … - 
        
TypeError: Field 'id' expected a number but got OrderedDict([('food', <FoodDetails: Nasi Goreng>), ('quantity', 2)])
I am trying to learn react and create a cart for my application I have two urls one for ordered items and one for the order in ordered items i store my multiple items and quantity and finally store the ordered items as items in my order here first i take ordereditems from my fooddetails url and then use that array of items for my order The food here is the id of ordered food, so that i can access its other properties if necessary The data i am sending seems okay as but the items array is empty in backend after i send the data const orderedItems = await Promise.all( cartItems.map(async (item) => { const response = await fetch( "http://127.0.0.1:8000/api/menu/fooddetails/" + item.id ); const food = await response.json(); const orderedItem: OrderedItem = { food: food.food_id, quantity: item.quantity, }; return orderedItem; }) ); const order: IOrderData = { items: orderedItems, total_price: totalAmount, total_items: totalQuantity, }; const response = await fetch("http://127.0.0.1:8000/api/order/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(order), }); const data = await response.json(); console.log(data); }; This is my models.py and serializers.py from menu.models import FoodDetails class OrderedItem(models.Model): food = models.ForeignKey(FoodDetails, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return … - 
        
Trouble with login when gmail ALLAUTH and user's email coincide
models.py class MyUser(AbstractUser): username = None # remove username field email = models.EmailField(_("Email Address"), unique=True) full_name = models.CharField(verbose_name="Full Name",max_length=100) phone = PhoneNumberField(verbose_name="Phone Number", blank=True) is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # fields required when creating a new user in terminal objects = MyUserManager() def __str__(self): return self.full_name urls.py # gmail OAUTH path('accounts/', include('allauth.urls')), settings.py # Allauth Settings SITE_ID = 1 ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' SOCIALACCOUNT_LOGOUT_ON_GET=True SOCIALACCOUNT_LOGIN_ON_GET=True SOCIALACCOUNT_QUERY_EMAIL = True For your context, my app uses email instead of username to log the user in, and for OAUTH, I use gmail. At the moment, if I log in through gmail using an email that DID NOT REGISTER directly to the app, I will be able to log in like usual and redirected to the home page. But if I try to log in through gmail with an email that DID REGISTER to my app beforehand, I will be instead redirected to this url: http://127.0.0.1:8000/accounts/social/signup/ I am not sure why this is happening. Can someone help me with this? The desired result should be that for the latter scenario, the user should be redirected … - 
        
How can I solve this ModuleNotFoundError: No module named 'core' error?
I am trying to deploy a django app using docker compose. I am currently having this error when the django app image is building. Two errors that stand out in the errors below is: noted_app | ModuleNotFoundError: No module named 'core' and postgres | 2023-04-08 00:44:43.169 UTC [50] FATAL: role "noted}" does not exist Please how can I resolve both errors. I am currently stuck with the deployment. postgres | postgres | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres | postgres | 2023-04-08 00:44:23.060 UTC [1] LOG: starting PostgreSQL 15.2 (Debian 15.2-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit postgres | 2023-04-08 00:44:23.061 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres | 2023-04-08 00:44:23.061 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres | 2023-04-08 00:44:23.069 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres | 2023-04-08 00:44:23.078 UTC [28] LOG: database system was shut down at 2023-04-08 00:43:52 UTC postgres | 2023-04-08 00:44:23.089 UTC [1] LOG: database system is ready to accept connections redis | 1:C 08 Apr 2023 00:44:23.465 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis | 1:C 08 Apr 2023 00:44:23.466 # Redis version=7.0.10, bits=64, … - 
        
X.MultipleObjectsReturned: get() returned more than one X -- it returned 2
I have a model, Chapter, linked to the Book model through a ForeignKey. One of it's fields, the integer field, number, is "slugified" to make the slug field, chapter_slug. The problem is my DetailView. When I call it the error "raise self.model.MultipleObjectsReturned(books.models.Chapter.MultipleObjectsReturned: get() returned more than one Chapter -- it returned 2!" That happens when I have more than one chapter 1, in this case, in two different books. class Chapter(models.Model): manga = models.ForeignKey(Manga, on_delete=models.PROTECT) number = models.IntegerField(default=1) name = models.CharField(max_length=200, blank=True) chapter_slug = models.SlugField(null=True) ... def get_absolute_url(self): return reverse('chapter', kwargs={'manga_slug': self.manga.manga_slug, 'chapter_slug': self.chapter_slug}) def save(self, *args, **kwargs): if not self.chapter_slug: self.chapter_slug = slugify(self.number) return super().save(*args, **kwargs) ... path('book/<slug:book_slug>/chapter/<slug:chapter_slug>/', views.ChapterView.as_view(), name='chapter'), class ChapterView(DetailView): model = Chapter template_name = books/chapter.html' context_object_name = 'chapter' slug_field = 'chapter_slug' slug_url_kwarg = 'chapter_slug' ... Even tough I know what the problem is I can't solve it. I've tried changing my DetailView but I got the error "NameError: name 'request' is not defined" and I'm not sure if it would work even without that error. class ChapterView(DetailView): model = Chapter.objects.get(id=request.get('chapter_id')) template_name = 'mangas/chapter.html' context_object_name = 'chapter' slug_field = 'chapter_slug' slug_url_kwarg = 'chapter_slug' ... - 
        
Django not generating prefixe or form ID in formset
I have a formset for creating criteria which generates the fields properly with an ID like this: <textarea name="form-0-criteriaDescription" cols="40" rows="10" class="textarea form-control" id="id_form-0-criteriaDescription"></textarea> However in a new formset these identifiers are not being generated properly, and each form field has the same identifier. For example, the comment always has the ID id_comment rather than a specific identifier for each form. <textarea name="comment" cols="40" rows="10" class="textarea form-control" required="" id="id_comment"></textarea> This is causing the POST data to be incorrectly formatted and so the form cannot be validated or saved or anything. The view code which generates the forms is as follows, I'm more than happy to add more details if need be, and thank you in advance for any pointers. formset = FeedbackFormset(queryset=Feedback.objects.none()) # Create a list of dictionaries containing the criteria description and the form instance feedbackForms = [] for criterion in criteria: feedbackForm = FeedbackForm() feedbackForm.fields['criteriaLevelID'].queryset = criterion.criterialevel_set.all() #limits choices for criteria Level feedbackForms.append({'form': feedbackForm, 'description': criterion.criteriaDescription}) context = {'submission': submission, 'feedbackForms': feedbackForms, # 'prefixes': [form.prefix for form in formset.forms], } return render(request, 'markingApp/createFeedback.html', context) - 
        
Can't run selenium driver on ec2
I collect reviews through a parser that uses chromedriver , I run parsing in a celery task on the server, i faced the following error (The process started from chrome location /home/ubuntu/.../chromedriver is no longer running, so ChromeDriver is assuming that Chrome has crashed.) this is the path returned by the ChromeDriverManager. Do I need to somehow install and configure the Google browser on the server? Here my chrome options: chrome_options = Options() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--headless") # Adding argument to disable the AutomationControlled flag chrome_options.add_argument("--remote-debugging-port=9222") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_argument("start-maximized") # Exclude the collection of enable-automation switches chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_argument("window-size=1280,800") # Turn-off userAutomationExtension chrome_options.add_experimental_option("useAutomationExtension", False) path = ChromeDriverManager().install() chrome_options.binary_location = path #"/home/ubuntu/chromedriver" service = Service(path) driver = webdriver.Chrome(service=service, options=chrome_options) - 
        
APACHE SOLR version 7.4 integrating with django haystack
I m trying to integrate apache solr into my django application to use as the search functionality. I have generated the schema.xml file and rebuild the index. When i try to search for a term in my application, I m getting the following error: app_label, model_name = raw_result[DJANGO_CT].split(".") AttributeError: 'list' object has no attribute 'split' Please help on how to fix this thank you! I am using apache solr version 7.4. I m using windows! - 
        
create consistant department name and code
I have a department model in django: from django.db import models class Departement(models.Model): name = models.CharField(max_length=128, db_index=True) code = models.CharField(max_length=3, db_index=True) I'd like to create a fixture with factory_boy with a consistent department name and code. Faker has a department provider which returns a tuple with the code and the department (ex for french: https://faker.readthedocs.io/en/master/locales/fr_FR.html#faker.providers.address.fr_FR.Provider.department) I have created a DepartmentFixture class but fail to understand how to use an instance of faker to call the faker.derpartments() method then populate the code/name fields accordingly. - 
        
AttributeError: 'Settings' object has no attribute 'decode'
Trying to migrate using on django and I have read the documentation and still getting an attribute error which I don't know how to debug _init_.py def __getattr__(self, name ,): """Return the value of a setting and cache it in self.__dict__.""" if (_wrapped := self._wrapped) is empty: self._setup(name) _wrapped = self._wrapped val = getattr(_wrapped, name ,) - 
        
How to fix an error with opening the API in the browser?
I am developing a project for react + django, using docker, docker launches a backend application at address 0.0.0.0:8000, 3 days ago everything worked fine, but today there was such an error. At the same time, requests through postman pass successfully. File entrypoint.sh File docker-compose Logs docker I tried to give a different address, switch to the last commit, change ports in the hosts file. The container itself starts successfully, but there is no access from outside. I suspect that the matter is that the host is blocked, but I do not know how to check it. - 
        
Django: Trying to create an average from a "ratings" field from two different models
Forgive me, this may be long: Using the Python shell, I have figured out how to accumulate an average from the ratings field from two different models: Review, the initial review posted by a user; and AddedReview, additional reviews from other users posted to the initial Review. (The code below is targeting a specific Review: (id=13)): >>> from django.db.models import Sum, Count >>> >>> added_ratings_sum = Review.objects.filter(id=13).aggregate(Sum('addedreview__rating')) >>> >>> added_ratings_sum {'addedreview__rating__sum': 27} >>> >>> for i in added_ratings_sum.values(): ... a_r_sum = i ... print(a_r_sum) ... 27 >>> >>> type(a_r_sum) <class 'int'> >>> >>> orig_ratings_sum = Review.objects.filter(id=13).aggregate(Sum(‘rating')) >>> orig_ratings_sum {'rating__sum': 9} >>> >>> for j in orig_ratings_sum.values(): ... r_sum = j ... print(r_sum) ... 9 >>> >>> total_sum = a_r_sum + r_sum >>> total_sum 36 >>> >>> ratings_count = review1.addedreview_set.count() + 1 >>> ratings_count 4 >>> >>> ratings_avg = total_sum / ratings_count >>> ratings_avg 9.0 The results are returned perfectly. However, when I add this code (reconfigured for all of the Reviews) in my home() view: def home(request, pk): ... added_ratings_sum = Review.objects.get(id=pk).aggregate(Sum('addedreview__rating')) for i in added_ratings_sum.values(): a_r_sum = i orig_ratings_sum = Review.objects.get(id=pk).aggregate(Sum('rating')) for j in orig_ratings_sum.values(): r_sum = j total_sum = a_r_sum + r_sum ratings_count = Review.objects.get(id=pk).addedreview_set.count() + 1 ratings_avg … - 
        
Using a non-editable field in a formset
I have a model class Application(models.Model): ... few fields ... pub_date = models.DateTimeField(.., auto_now_add=True, ..) For create few objects i'm using FormSet class ApplicationForm(forms.ModelForm): ... ApplicationFormSet = modelformsetfactory(..) Field "pub_date" add automatically in new objects. Also i'm using FormSet for update my forms. This is showed in the view: def applications_list(request): applications = Application.objects.all() if request.method == 'POST': formset = ApplicationFormSet(request.POST, queryset=applications) if formset.is_valid(): formset.save() formset = ApplicationFormSet(queryset=applications) return render(request, 'applications/applications_list.html', {'formset': formset}) In template i use table with: {% for form in formset.forms %} and {% for field in form.visible_fields %} for show all objects and update it. But i can't bring to content "pub_date" because it's field not editable and cannot be added to form (formset) How i can add "pub_date" (non-editable) in one line with other fields of forms? - 
        
Django/Python: How to use the If-Statement
I would like to, If a file is selected, that a image is shown. I wrote the {% if file.selected %} myself, because I couldn't find anything online. I know this ptompt is wrong, but just to get an Idea, If someone selects a file, it should show the image, else the text. I just need the right prompt. <div class="mystyle"> <div class="titleit"> <input contenteditable="true" placeholder="An Interesting Titel... " type="text" name="title" maxlength="100" required id="id_title"> </div> <br><br><br> <div class="options"> {% if file.selected %} <img class="preview" src="/media/fitmedia/california.jpg"> {% else %} <p class="p-text">Upload a Picture or Video </p> <input class="fileit" type="file" name="file" required id="id_file"> {% endif %} </div> </div> - 
        
Django Crispy Forms cancel button
I have a Django Crispy Form that I want to add a cancel button to. Unlike the answers here and here, however, the user can get to the form via multiple pages, so I need to send them back to the page they came from if they cancel, not send them to a static page. How can I accomplish this? - 
        
find deleted records
I have a Django application that processes a weekly CSV dump of 1.5 years of data and stores it in a PostgreSQL database. The data contains a primary key column and an uploadDate column, among other columns. If a record is deleted from the source, the new dump won't have this record, but the record will exist in my database. I want to use pandas or sql to sort the data by uploadDate in ascending order and compare the records from the older file with the next consecutive one. If there are records in the old file that do not exist in the next one, it means those records were deleted. How can I solve this using sql or python pandas? enter image description here import pandas as pd def find_deleted_records(df: pd.DataFrame, primary_key: str, upload_date: str) -> pd.DataFrame: """ Find records that were deleted from a database table based on a weekly CSV dump. Args: df (pd.DataFrame): The dataframe containing the table data. primary_key (str): The name of the primary key column. upload_date (str): The name of the upload date column. Returns: pd.DataFrame: A dataframe containing the deleted records. """ # Sort the data by Peildatum in ascending order data … - 
        
Django with django-tenants not copying all static folders to AWS S3 bucket
I have a django-tenants site that I am attempting to prepare for moving to a live server. I want to use an AWS S3 bucket for static files. I have been able to get a few folders the local static directory to copy to the S3 bucket but many are not copied when I run "python manage.py collectstatic." I have the following folders in the static directory: admin, bootstrap, CACHE, constrainedfilefield, core_images, css, django_ckeditor_5, django_extensions, django_tinymce, tagulous, tinymce. However only the following folders are getting copied to the S3 bucket: admin, constrainedfilefield, django_ckeditor_5, django_extensions, django_tinymce, tagulous settings.py file: """ Django settings for config project. Generated by 'django-admin startproject' using Django 3.1.14. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os.path #from environs import Env from django.conf.locale.en import formats as en_formats EMPLOYEE_PERMISSIONS_FILE = 'config.employee_permissions' MANAGER_PERMISSIONS_FILE = 'config.manager_permissions' ADMINISTRATOR_PERMISSIONS_FILE = 'config.administrator_permissions' from importlib import import_module employee_permissions = import_module(EMPLOYEE_PERMISSIONS_FILE).EMPLOYEE_PERMISSIONS manager_permissions = import_module(MANAGER_PERMISSIONS_FILE).MANAGER_PERMISSIONS administrator_permissions = import_module(ADMINISTRATOR_PERMISSIONS_FILE).ADMINISTRATOR_PERMISSIONS # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret … - 
        
Stop addresses been recorded if already exists for customer
I wanted to make my code record an address for a customer when making an order, I wanted this separate from shipping addresses. At the moment I'm struggling to figure out how to stop it continuously recorded the same address if the same customer places and order with the same address. So to put it simply, if address already exists for customer do not add, if it does not exist add it. This is the view that records the address def process_order(request): transaction_id = datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, order_status='P') else: customer, order = guestOrder(request, data) total = float(data['form']['total']) order.transaction_id = transaction_id if total == float(order.get_cart_total): order.order_status = 'C' order.save() if order.shipping == True: ShippingAddress.objects.create( customer=customer, order=order, house=data['shipping']['house'], street=data['shipping']['street'], city=data['shipping']['city'], postcode=data['shipping']['postcode'], ) Address.objects.create( customer=customer, house=data['shipping']['house'], street=data['shipping']['street'], city=data['shipping']['city'], postcode=data['shipping']['postcode'], ) MOdels class Customer(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True,) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) def __str__(self): return '%s %s' % (self.first_name, self.last_name) class Address(models.Model): house = models.CharField(max_length=255) street = models.CharField(max_length=255) city = models.CharField(max_length=255) postcode = models.CharField(max_length=25) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) def __str__(self): return 'Username: %s - Name: %s %s' % ( self.customer.user ,self.customer.first_name, self.customer.last_name) screenshot of issue - 
        
PWA with React & Django
I'm relatively new to web development and I have a PWA question. I have a React project and the PWA can be installed normally if I deploy the frontend project, but I generate a frontend build and leave the folder inside a Django directory, where it forwards requests to index.html. The problem is that after deploying, even though the service-worker and manifest.json are recognized, it is not possible to install the PWA Can anyone explain why? I would like to be able to install the PWA by just deploying the django project with the react build inside it and not leaving the front and backend in different deploys - 
        
Encrypting python scripts in web application for Django and flask
I am working on developing two applications for a client using Flask and Django frameworks. However, I am seeking guidance on encrypting my Python script to ensure the client cannot access my code. Furthermore, I am planning to deploy the applications using Docker Compose with Nginx and Postgres.I would appreciate any feedback on whether this deployment approach is optimal or if there is a better alternative. i found pyinstaller which will convert code to exe but not sure if its optimal way for web application like flask and django