Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to log in on the Django side and also be logged in on the Vue side
I have a Django app with some pages and then I use Django Rest Framework to supply data to a Vue application, including loggin the user in. The Django website and the Vue application are not on the same domain or server or country or universe for that matter. I want to know how can I make it that if I log in on the Django side and I am redirected to the Vue app that I am also logged in on the Vue side? And visa versa if I log in on the Vue side that I am also logged in on the Django side. I am using JWT authentication and I thought about sending the token to the page (Django side if logged in on Vue side) I go to after being logged in but this seems to be impossible to do, or I just cannot find an answer of how to do it. -
AES encryption/decryption issue with RSA-encrypted key and IV in Python
'''import base64 import os import json import requests from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.backends import default_backend from cryptography.x509 import load_pem_x509_certificate import requests import json from cryptography.hazmat.primitives.ciphers import Cipher, algorithms from cryptography.hazmat.primitives.ciphers.aead import AESGCM import secrets import binascii def aes_gcm_encrypt(key, iv, plaintext, authenticated_data): aesgcm = AESGCM(key) ciphertext = aesgcm.encrypt(iv, plaintext, authenticated_data) return ciphertext def aes_gcm_decrypt(key, iv, ciphertext, authenticated_data): aesgcm = AESGCM(key) plaintext = aesgcm.decrypt(iv, ciphertext, authenticated_data) return plaintext ivs = "abcdefghijklmnop" keys = "abcdefghijklmnopqrstuvwxyzabcdef" iv_bytes = ivs.encode('utf-8') key_bytes = keys.encode('utf-8') print("len of bytes: ",len(iv_bytes),len(key_bytes)) plaintext = b'This is going to encrypt' authenticated_data = b'Additional data for authentication' ciphertext = aes_gcm_encrypt(key_bytes, iv_bytes, plaintext, authenticated_data) ciphertext_hex = binascii.hexlify(ciphertext).decode('utf-8') decrypted_text = aes_gcm_decrypt(key_bytes, iv_bytes, ciphertext, authenticated_data) """print(f"Ciphertext: {ciphertext}") print(f"Ciphertext hex: {ciphertext_hex}") print(f"Decrypted text: {decrypted_text}")""" def encrypt_data(iv,key, certificate): encoded = "" encrypted = None try: # Load the certificate cert = load_pem_x509_certificate(certificate.encode(), default_backend()) # Extract the public key public_key = cert.public_key() # Encrypt the data encrypted = public_key.encrypt( iv, padding.PKCS1v15() ) encrypted1 = public_key.encrypt( key, padding.PKCS1v15() ) # Base64-encode the encrypted data encoded = base64.b64encode(encrypted).decode() encoded1 = base64.b64encode(encrypted1).decode() except Exception as e: print(e) return encoded.replace("\\r", "").replace("\\n", ""),encoded1.replace("\\r", "").replace("\\n", "") AES encryption print("AES … -
Custom third party API authentication and restful services using django
I am basically pretty new in django and learning. I have started learning making APIs and authentications and stuffs like that. But I need some guidance. So, basically I am supposed to use some third party APIs for logging in which will provide me with the bearer auth token. And by using that token I am supposed to use the other APIs of the provider. If someone can guide me towards some proper tutorial or post which could help me that would be great. Tried using Django Rest Framework but most of them are for creating new APIs but not for consuming any third party API. -
User doesn't exist problem in login page of django User model
I have created one simple recipe website. In which i am creating a login page and register page. The register page is working fine and it saving the user credential into the User model. but when i have created the login page. it showing that username doesn't exist but the user is registered with same username and password. I have tried all the query like using filter and get separately..but didn't get any desired result. I expect that when user type their user name and password it redirect to recipe page. if the credentials are wrong it redirect to login page def login_page(request): if request.method == "POST": username = request.POST['username'] print(username) password = request.POST['password'] # print(User.objects.filter(username=username)) user = authenticate(username = username, password = password) if user is None: messages.info(request, "user do not exit. please REGISTER") return redirect('/user_login/') else: login(request, user) return redirect('/receipes/') return render(request, 'login_page.html') def register_page(request): try: if request.method == "POST": username = request.POST['username'], first_name = request.POST['first_name'], last_name = request.POST['last_name'] if User.objects.filter(username=username): messages.info( request, "Username already exist! Please try some other username.") return redirect('/user_register/') user = User.objects.create( username=username, first_name=first_name, last_name=last_name ) user.set_password(request.POST['password']) user.save() messages.success( request, "Your Account has been created succesfully!!") return redirect('/user_register/') except: pass return render(request, 'register_page.html') -
Django- How can I add sizes for my product?
I created my models but now I don't know how to create a form with all the sizes I added for every product to add it to detail view. can you please help me, Thanks. here is my models.py. from django.db import models from django.shortcuts import reverse class Size(models.Model): size = models.CharField(max_length=250) def __str__(self): return self.size class Product(models.Model): title = models.CharField(max_length=150) description = models.TextField() price = models.PositiveIntegerField() image = models.ImageField(upload_to='product/product_cover', blank=False) active = models.BooleanField(default=True) sizes = models.ManyToManyField(Size, through='ProductSize') datetime_created = models.DateTimeField(auto_now_add=True) datetime_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product_detail', args=[self.id]) class ProductSize(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) count = models.IntegerField(default=1) def __str__(self): return self.product -
how installing chained foreignkey
django.db.utils.OperationalError: (1045, "Access denied for user '91815'@'localhost' (using password: YES)") ERROR: Could not find a version that satisfies the requirement django-chained-foreignkey (from versions: none) ERROR: No matching distribution found for django-chained-foreignkey -
Hi,How can I add a photo to a web page with Django?
how can I create this feature so that the user can choose a photo for a product from within the system or enter its URL? This image should be added to the product list along with other information. This is my code. The page loads, but it doesn't do anything special and it doesn't have the URL box either. {% extends "auctions/layout.html" %} {% block body %} <h2 id="h2">Create List</h2> <form method="POST"> {% csrf_token %} <h3 id="h3">Title:</h3> <input id="input" placeholder="Title" type="text" name="createlist_title"/> <h3 id="h3">Category:</h3> <input id="input" placeholder="Category" type="text" name="category"/> <h3 id="h3">Description:</h3> <textarea id="input" placeholder="Description" type="text" name="createlist_description"> </textarea> <h3 id="h3">Firstprice:</h3> <input id="input" placeholder="first_price" type="number" name="createlist_price"/> <form action="upload.php" method="post" enctype="multipart/form-data"> <h3 id="h3"> Upload image:</h3> <input id="input" type="file" id="fileUpload" name="fileUpload"> <input id="button2" type="submit" value="upload"> </form>`` <form method="post" enctype="multipart/form-data" action="{%url "upload_image" %}"> <h3 id="h3"> Upload image with URL:</h3> {% csrf_token %} {{ form.as_p }} <button id="button2" type="submit">Upload</button> </form> <button id="button" class="btn btn-outline-primary" type="submit">Submit</button> </form> -
Why is Heroku unable to find my "manage.py" file in the Django app I'm trying to deploy?
When I deploy my Django app on Heroku I get this: As you can see it says that there is a dyno running and then when I enter "heroku ps" it says that no dynos are running. "herokeroku ps eroku ps" is just a glitch in the CLI. I checked the logs and it said that the deployment failed and in the release logs of that deployment it says it can't find the "manage.py" file. However, the "manage.py" file is there in the root folder and the Heroku branch is up to date. I can run the app locally with "heroku local". Do you know why Heroku might not be able to find a "manage.py" file? Thank you -
Implementing Secure Data Encryption and Decryption between Frontend and Backend using Public and Private Keys
Front end will invoke some API which will provide Public key: Using that public key front end should encrypt it Use the API(POST/PUT) to send the data back. Back end API will decrypt the data using private and public key and store the content. When the same data is retrieved at front end: Generate the keys and encrypt the data using public key Decrypt the data at front end using the private and public key. what heading can i give for this question I have three fields which needed to be encrypted and decrypted but I'm only able to encrypt its not decrypting .can u help how to decrypt? myapp/utils.py from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import base64 def encrypt_data(data, public_key_path): with open(public_key_path, 'rb') as f: public_key = RSA.import_key(f.read()) cipher_rsa = PKCS1_OAEP.new(public_key) encrypted_data = cipher_rsa.encrypt(data.encode('utf-8')) return base64.b64encode(encrypted_data).decode('utf-8') def decrypt_data(encrypted_data, private_key_path): encrypted_data = base64.b64decode(encrypted_data) with open(private_key_path, 'rb') as f: private_key = RSA.import_key(f.read()) cipher_rsa = PKCS1_OAEP.new(private_key) decrypted_data = cipher_rsa.decrypt(encrypted_data) return decrypted_data.decode('utf-8') myapp/views.py def add_candidate(request): if request.method == 'POST': form = CandidateForm(request.POST) if form.is_valid(): candidate = form.save(commit=False) # Encrypt sensitive fields using the public key candidate.adharnumber = encrypt_data(candidate.adharnumber, settings.PUBLIC_KEY_PATH) candidate.pannumber = encrypt_data(candidate.pannumber, settings.PUBLIC_KEY_PATH) candidate.passportnumber = encrypt_data(candidate.passportnumber, settings.PUBLIC_KEY_PATH) candidate.save() return redirect('candidate_list') else: … -
Javascript integration with django template problem
In my django project when i write show password script within login.html file it works fine but when i place the script in static directory of my project it will effect email and password1 field not password1 and password2 field. {% load static %} {% load widget_tweaks %} {% load socialaccount %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static 'Notes/signup.css' %}" /> <!--Font Awesome Link--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <title>Signup Page</title> </head> <style> .errors label{ font-size: 11px; color: red; position: relative; bottom: 9px; } </style> <body> <div class="container"> <form id="login" method="post"> {% csrf_token %} <h1>Signup</h1> {% render_field form.username type="text" placeholder="Username" %} {% if messages %} {% for message in messages %} {% if message.tags == "username error" %} <div class="errors"> <label><i class="fa-sharp fa-solid fa-circle-exclamation"></i>{{message}}</label> </div> {% endif %} {% endfor %} {% endif %} {% render_field form.email type="email" placeholder="Email" %} {% if messages %} {% for message in messages %} {% if message.tags == "email error" %} <div class="errors"> <label><i class="fa-sharp fa-solid fa-circle-exclamation"></i>{{message}}</label> </div> {% endif %} {% endfor %} {% endif %} {% render_field form.password1 type="password" placeholder="Password" %} {% render_field form.password2 type="password" placeholder="Confirm Password" %} {% … -
No Audio Detected Assembly API
I'm using the Assembly API's transcribe model and when I run it on the server it returns that the video has no audio only text? any reason for this? I am providing youtube share links and I've tried the YouTube URL links as well? Suggestions for better FREE transcription API's would also be a valid solution just as long as they have decent readable documentation,Heres the code but its basically just a copy from the docs aside from the fact Im taking in user input transcriber = aai.Transcriber() #transcriber model def process_input(user_input): base_url = "https://api.assemblyai.com/v2" transcript_endpoint = "https://api.assemblyai.com/v2/transcript" response = requests.post(base_url + "/upload", headers=headers, data=user_input) upload_url = response.json()["upload_url"] data = { "audio_url": upload_url } response = requests.post(transcript_endpoint, json=data, headers=headers) transcript_id = response.json()['id'] polling_endpoint = f"https://api.assemblyai.com/v2/transcript/{transcript_id}" # run until transcription is done while True: transcription_result = requests.get(polling_endpoint, headers=headers).json() if transcription_result['status'] == 'completed': return transcription_result['text'] elif transcription_result['status'] == 'error': #the Error print HERE raise RuntimeError(f"Transcription failed: {transcription_result['error']}") -
Why does the 'UWSGI listen queue of socket full' error cause a Python application to time out during a third-party API call?
According to the logs, before the occurrence of "UWSGI listen queue of socket full", the third-party requests made by the application took only milliseconds. However, after this occurred, the same requests took more than ten seconds to complete. "I tried increasing the value of the listen parameter and the number of threads in uwsgi, which resolved the 5xx error in my application. However, my confusion is that the listen parameter should only affect the efficiency of receiving requests sent by nginx, so why does it affect calling third-party services?" -
Django - Mail is not sent
Email is not sent. What is interesting... before (like 3 mos ago) entire code worked perfectly fine. Settings: DEBUG = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT: 587 EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_HOST_PASSWORD = 'xyz' EMAIL_USE_TLS = True ALLOWED_HOSTS = [] view.py: def index(request): """The home page.""" # Send a message. if request.method != 'POST': # No data submitted; create a blank form. form_email = EmailForm() form_message = EmailMessageForm() else: # POST data submitted; proecess data. form_email = EmailForm(data=request.POST) form_message = EmailMessageForm(data=request.POST) if form_email.is_valid() and form_message.is_valid(): try: email = Email.objects.get(text=request.POST['text']) except: form_email.save() email = Email.objects.last() message_db = form_message.save(commit=False) message_db.email = email message_db.save() message_owner = ( f'New email on your website from {request.POST["text"]}', f"Email has been sent from: {request.POST['text']}\n\n" f"Full message:\n\"{request.POST['message']}\"", 'settings.EMAIL_HOST_USER', ['my@gmail.com',], ) message_guest = ('Your email has been sent', "Many thanks for getting in contact with me. Your message was " "successfully sent. I will reach out to you as soon as possible." f"\n\nYour message:\n\"{request.POST['message']}\"", 'settings.EMAIL_HOST_USER', [request.POST['text'],], ) send_mass_mail((message_owner, message_guest), fail_silently=False) return redirect('home:contact_thank_you') # Display a blank or invalid form. context = {'form_email': form_email, 'form_message': form_message} return render(request, 'home/index.html', context) Traceback: Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.5 Exception Type: TimeoutError Exception Value: [WinError 10060] Raised during: home.views.index C:\Users\danie\Desktop\python_work\page\home\views.py, line … -
Django - How to control 'add another' links in django-nested-admin areas
I have a very complicated object structure that the django admin section handles like a champ. As you can see below there are sub-references to other objects or even the same object. In many cases the sub objects are created in a certain pattern and I'd like to be able to generate stubs for that pattern. What i'd like to be able to do is I guess customize what happens when you click on the 'Add another Crafted Item' link, or add another link that will add multiple sub-item stubs. Right now if you click on that link, you get ONE stub with default values in it from the model object. I wanna do the same thing, but I want to be able to do more than one and be able to specify different default values than what are specified in the model object. Does anyone have any idea how I can tap into that functionality? Is there a name for it or something? thanks for the assistance, EK -
What is causing `tzlocal` to throw `Please use a timezone in the form of Continent/City. tzlocal() does not support non-zoneinfo timezones like UTC`?
Please use a timezone in the form of Continent/City. tzlocal() does not support non-zoneinfo timezones like UTC This was raised by requests.raise_for_status() My settings.py: USE_TZ = True TIME_ZONE = 'UTC' What is causing tzlocal to throw this? I couldn't find this error in other places. It usually complains about specific timezones but not 'UTC' -
Open ListView with foreignkey from anotherlist view using a slug in django
I was able to do basically what this article - link - says, and in the comments the person says that it would be beneficial to use a slug. How would I go about implementing the above article but with a slug. I understand how slug:pk works, I'm just not sure how to link that to a foreign key and have it filter by that pk, and then how to have it passed into the url as well. I don't really know where to start trying to figure this out, so any help at all is appreciated, Thanks(: -
Wagtail Sporadic 502 Errors in Image Admin
I am getting a 502 error when uploading new images to wagtail (this after uploading successfully many times since last update). The site runs on nginx. Sometimes, this leads to 502 error on the main image admin page, but these often clear with refreshing. This is the related error get in my Wagtail error log: Wagtail AttributeError: type object 'RequestContext' has no attribute 'locale' I expected this to resolve with reloading nginx and gunicorn and rebooting ubuntu. Unfortunately nothing works. I've also tried running a search for corrupt images and deleting all offenders. The problem remains. Have also tried uploading problematic images directly via SFTP which solves the problem temporarily, but doesn't allow for new uploads. I am using Django>=4.1,<4.2, wagtail>=5.0,<5.1 -
How to handle django static files for production
I am a newbie django developer and this is the django project i will be deploying. Everything works in development but I am been having issues in production. PS: I am using shared hosting for the deployment. First, the website loads but images are not showing. I tried using whitenoise but keeps getting the error File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/publishm/PUBLISHMYCRAFT/learnwithjdd/index/urls.py", line 12, in <module> path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon_io/favicon.ico'))), File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 203, in url return self._url(self.stored_name, name, force) File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 182, in _url hashed_name = hashed_name_func(*args) File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 513, in stored_name raise ValueError( ValueError: Missing staticfiles manifest entry for 'images/favicon_io/favicon.ico' part of my urls.py from . import views from django.urls import path from . views import BlogHomeView, BlogDetailsView, AddPostView, EditPostView, DeletePostView, AddCategoryView, DraftsListView, AddDraftPostView, DraftPostDetailsView, EditDraftPostView, DeleteDraftPostView from django.views.generic.base import RedirectView from django.contrib.staticfiles.storage import staticfiles_storage app_name = 'index' urlpatterns = [ path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('favicon.ico'))) ] part of the settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" I tried using the whitenoise and play around with the path but the static files and the ckeditor are not working. The error disppears and … -
for loop for search engine not working properly
similar_entries = [] for entry in all_entries: for letters in entry: if letters in entry: if entry not in similar_entries: similar_entries.append(entry) This code is for a search engine but it is displaying all elements of the list instead of a showing strings with the same couple of words. all entries is a list I was stuck on this problem for so long -
Pytest doesn't find tests written in django project
I am learning about test-driven development and am using pytest-django to conduct unit tests for my django project. I wrote a few tests, but when I run pytest, it says that it collected 0 items and that a file or directory wasn't found. Terminal text: mariojerez@Marios-MacBook-Pro zhulimoon % pytest ============================================================================== test session starts =============================================================================== platform darwin -- Python 3.9.6, pytest-7.3.0, pluggy-1.0.0 django: settings: zhulimoon.test_settings (from ini) rootdir: /Users/mariojerez/Documents/coding/ZhuLi Moon/zhulimoon configfile: pytest.ini plugins: django-4.5.2 collected 0 items ============================================================================= no tests ran in 0.00s ============================================================================== ERROR: file or directory not found: #After mariojerez@Marios-MacBook-Pro zhulimoon % tests.py file inside the django app: import pytest from .models import * @pytest.fixture(scope='module') @pytest.mark.django_db def create_project_no_framework(): yield Project.objects.create(name="The Bikini Bottom", description="Model of the Spongebob Universe") @pytest.fixture(scope='module') @pytest.mark.django_db def create_node_type_in_project(): yield NodeType.objects.create(name="character", project=Project.objects.get(name="The Bikini Bottom")) @pytest.fixture(scope='module') @pytest.mark.django_db def create_node_in_project(): yield Node.objects.create(name="Spongebob", description="The protagonist of the show", nodeType=NodeType.objects.get(name="character"), project=Project.objects.get(name="The Bikini Bottom")) @pytest.fixture(scope='module') @pytest.mark.django_db def create_node_type_property(): yield Property.objects.create(type="physical", name="height", description="height of character", dataType="dec", unit="cm") @pytest.mark.django_db def test_create_project_no_framework(create_project_no_framework): create_project_no_framework project = Project.objects.get(name="The Bikini Bottom") assert str(project) == "The Bikini Bottom" @pytest.mark.django_db def test_create_node_type_in_project(create_node_type_in_project): create_node_type_in_project nodeType = NodeType.objects.get(name="character") assert str(nodeType.project) == "The Bikini Bottom" assert nodeType in NodeType.objects.filter(project=Project.objects.get(name="The Bikini Bottom")) assert str(nodeType) == "character" @pytest.mark.django_db def test_create_node(create_node_in_project): create_node_in_project node = Node.objects.get(name="Spongebob") assert … -
Django, extraction problem when i use SELECT2 for two comboboxes contained in two different models
I'm trying to use Select2 in Django. I saw a guide on the official site, but it doesn't show how to use it when there are two or more comboboxes (dropdown) in the same model (here), because the official site shows how to use Select2 with one combobox for each model. In my case I have only one model with 2 comboboxes inside. I would like to make the country combobox dependent on the voyage combobox models.py class NextVoyage(models.Model): country = models.CharField(max_length=30) departure = models.CharField(max_length=30) destination = models.CharField(max_length=30) def __str__(self): voyage = f"{self.departure}-{self.destination}" return voyage forms.py This is the base code with which I normally display the contents of combobx. This works and displays correctly (when they are not dependent) class Form_SelectVoyage(forms.Form): country = forms.ModelChoiceField(queryset=NextVoyage.objects.values_list('country', flat=True).distinct()) destination = forms.ModelChoiceField(queryset=NextVoyage.objects.all()) In Select2, I try to make them dependent like this, but it does not work. The comboboxes are empty. It doesn't work because as you can see I have 2 comboboxes in the same model, but the example on the official site shows how to make 2 comboboxes dependent in 2 different models. Can anyone help me? Thank you class Form_SelectVoyage(forms.Form): country = forms.ModelChoiceField( queryset=NextVoyage.objects.values_list('country', flat=True).distinct(), label="Country", widget=ModelSelect2Widget( model=NextVoyage, search_fields=['name__icontains'], ) … -
Writing forms in django generates duplicated rows when using save() method
I'm building a form based on different models using django and I was struggling because I was generating duplicates rows and I fixed it with the code below but I'm interested in hearing suggestions to write this code better: #views.py def make_customer(request, id): # Get the customer object or return a 404 response if it doesn't exist customer = get_object_or_404(Customer, pk=id) print(request.POST) if request.method == 'POST': contact_form = ContactForm(request.POST) address_form = AddressForm(request.POST) company_form = CompanyForm(request.POST) if contact_form.is_valid() and address_form.is_valid() and company_form.is_valid(): if customer.company: # Update existing company, contact, and address company = customer.company print(company_form.cleaned_data) company.name = company_form.cleaned_data['name'] company.customer_information_file_number = company_form.cleaned_data['customer_information_file_number'] company.contact.name = contact_form.cleaned_data['name'] company.contact.email = contact_form.cleaned_data['email'] company.contact.cc_email = contact_form.cleaned_data['cc_email'] company.address.street = address_form.cleaned_data['street'] company.address.city = address_form.cleaned_data['city'] company.address.postal_code = address_form.cleaned_data['postal_code'] company.contact.save() company.address.save() company.save() else: # Create a new company if it doesn't exist contact = contact_form.save() address = address_form.save() company = Company.objects.create( name=company_form.cleaned_data['name'], customer_information_file_number=company_form.cleaned_data['customer_information_file_number'], contact=contact, address=address ) customer.company = company customer.save() messages.success(request, 'Customer saved successfully') return redirect('view_customers') else: # GET request contact_form = ContactForm( instance=customer.company.contact) if customer.company else ContactForm() address_form = AddressForm( instance=customer.company.address) if customer.company else AddressForm() company_form = CompanyForm( instance=customer.company) if customer.company else CompanyForm() context = { 'contact_form': contact_form, 'address_form': address_form, 'company_form': company_form, } return render(request, 'invoices/form_customer.html', context) This is the … -
Django multiple databases and multiple apps
I have an app_login that I want to store the information in the default database and I have a folder with the name client where there will be several clients one of them is flowon all the models of app_flowon I want it to stay in the app_flowon database, but I'm having difficulty making it work, or I'm migrating all the models to the default database or everything is going to the app_flown database, I don't want to mix the models, I want to leave everything separate, I want the models of the app_login to be in default and the models from app_flowon is in app_flowon database, what can i do? -
How to combine Django and Next.js to deploy under a single domain?
My goal is to create a website with Django as a backend, and React/Nextjs as a frontend. At the moment, I have found a perfect example of a repository which fits for the purpose, but it combines React and Django: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial/tree/main/Tutorial%207 I was wondering if is possible to add Next.js to it. If it is possible, how can it be done? I tried a naive approach of replacing the frontend with nextjs app, didn't work. Then i tried installing next.js as a package and using it's features except for routing, did not work either. Due to me being not well versed with bundling and tranpiling tools such as Webpack and Babel, I am unsure how to configure them to attain the intended result. When I tried to replace frontend with next.js app, the frontend became decoupled from the backend. Then I tried to install next as a package and use 'next/link' feature, both approaches didn't work. What I was expecting is that the code written using next package would be added to the generated static main.js file from the example: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial/tree/main/Tutorial%207/frontend/static/frontend -
Error : This queryset contains a reference to an outer query and may only be used in a subquery
This might be a very easy to spot mistake but I am not the most familiar with the Django queries so I have been breaking my head for hours trying to solve that. I have a Django Rest app and there I have 2 models: class Student(models.Model): name = models.CharField(max_length=20) status = models.CharField(max_length=4, blank=True, default="UNK", choices=STATUS_TYPES) started_date = models.DateTimeField(null=False, auto_now_add=True) class StudentStatusHistory(BaseTimestampModel): """Table of status changes for Students""" student = models.ForeignKey( "core.Student", on_delete=models.CASCADE, related_name="StatusHistory" ) status = models.CharField( max_length=4, blank=True, default="UNK", choices=STATUS_TYPES ) created_on = models.DateTimeField(null=False, auto_now_add=True) For reference: STATUS_TYPES = [("UNK", "Unknown"), (“PASS", “Passed"), (“FAIL", “Failed")] I am trying to write a query that calculates for how many students their status changed to Pass within the time window of a week or less. So for example if a Student.started_date is 2023-07-15 12:22:22 and the StudentStatusHistory.created_on field is 2023-07-21 12:22:22, for a student with Student.status that equals PASS, I want to count this student because they passed in less than a week (in 6 days in this example). Additionaly, I want to calculate this count only for students that started the current month. What I have so far is: current_month_start = datetime(datetime.today().year, datetime.today().month, 1) # Subquery to filter StudentStatusHistory objects …