Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use choices of a Select field of a form, when defined in the view in Django?
I have an issue with a form with a Select input. This input is used to select a user in a list. The list should only contain user from the group currently used. I found a solution, however I am not completely sure of what am I doing in the form definition (I do not fully understand how works the def __init__ part). And of course, my code is not working : I obtain the right form, with the choices I need, however if a submit data, it's not saved in the database. I have been able to check if the form is valid (it is not), the error is the following : Category - Select a valid choice. That choice is not one of the available choices. (I have the same error for the user field). I can't find my way in this, so if you can help, would be very appreciated! My models: class Group(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class User(AbstractUser): groups = models.ManyToManyField(Group) current_group = models.ForeignKey(Group, on_delete=models.SET_NULL,blank = True , null = True, related_name="current_group") class Category(models.Model): name = models.CharField(max_length=100) groups = models.ManyToManyField(Group) def __str__(self): return self.name class Expanses(models.Model): date = models.DateTimeField() amount = models.DecimalField(decimal_places=2, … -
Django ORM - How to get max price and the associated date
To follow the price of what I buy at the grocery. I have these models : Class Product(models.Model): title = models.CharField(max_length=255) name = models.CharField(max_length=255) information = models.CharField(max_length=255) Class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date_seen = models.DateTimeField(auto_now_add=True) price = models.IntegerField(blank=True, null=True) And I try to have for each product the max price and the associated date. If I do def get_max_price_for_product(request): max_price_list = ( Price.objects.values("product__title", "product__name") .annotate(score=Max("price")) .order_by("-price") ) context = {"max_price_list": max_price_list} return render(request, "prices/max_list.html", context) I've the max price for each product but without the date. I read the Django doc but I didn't find (or I didn't understand what I read) how to do this. Can somebody help me ? Thank you in advance. -
How to sort a model's objects if the model has foreign key relations and I have to sort based on the properties of the foreign model?
How to sort a model's objects if the model has foreign key relations and I have to sort based on the properties of the foreign model? Here is my model class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(550), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class TimeSlot(models.Model): class Meta: ordering = ['available_from'] room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) check_in_date = models.DateField() timeslot = models.ForeignKey(TimeSlot, on_delete=models.CASCADE) Suppose I have to sort the objects of the Booking model on the basis of available_from or number how will I do it? -
ASGI does not start in Django
I am following the tutorial by Dennis Ivy on YouTube: Django Channels & WebSockets Oversimplified I want to make a simple website using websockets in Django. I am using Python 3.7.0 When I use the python manage.py runserver it outputs the following Starting development server at http://127.0.0.1:8000/ It should, however, output the following Starting ASGI/Channels version 3.0.0 development server at http://127.0.0.1:8000/ This is my settings.py file INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', ] ASGI_APPLICATION = 'myWebsite.asgi.application' The asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myWebsite.settings') application = ProtocolTypeRouter({ 'http':get_asgi_application() }) -
Chart JS line graph displaying as blank canvas upon render
I'm using Chart JS to try and add a graph into my web app. I've included the <script></script> directly into my template (using Django MVT framework) and I'm trying to render the HTML into Chrome but the chart isn't showing, even though the code is an almost direct copy from the Chart JS website's "getting started" section (which works fine!). The data is coming from the back-end properly because I can see it with chrome dev tools, however the canvas is just a blank square. I've seen about a dozen videos and guides online where people use the same code and their graphs are working. Other Stack threads don't help either as they are either to do with refreshing data or thread never got closed, so stuck on what's going on. Things I've tried: Tried setting dates to strings instead to see if that makes a difference, nope. Tried moving the CDN placement in my code, no difference. Setting "beginAtZero: false" Been playing spot the difference for a couple of days with no success. The only thing I can possibly think is it's something to do with the options for the line graph... no idea where to begin though as … -
django clean function in forms.py does not work
Im reading a book called "Web development with Django" which I like a lot. One of the things which gets taught there is that you can change a value coming from the form. I have tested raising errors (validation error from django core) which works fine. But I can't get the "clean_name" function to work on the input. The function is located at the bottom. I hope someone here knows what im doing wrong :) from django import forms from django.forms import widgets from django.core.exceptions import ValidationError def validate_regnr(value): if value[:3].upper() != value[:3]: raise ValidationError(f'{value} is not correct') class BookingForm(forms.Form): SERVICES = ( ('1', 'Årsservice'), ('2', 'Storservice'), ('3', 'Bromsservice') ) regnr = forms.CharField(min_length=6, max_length=6, validators=[validate_regnr]) service = forms.ChoiceField(choices=SERVICES) name = forms.CharField(max_length=255) tel = forms.CharField(max_length=20) email = forms.EmailField() datetime = forms.DateTimeField(widget=widgets.DateInput(attrs={'type': 'datetime-local'})) kommentar = forms.TextInput() def clean_name(self): value = self.cleaned_data['name'] return value.upper() -
Connect a Django user to a Discord server and assign a role
I see a lot of pip package to manage bots or messages in Discord via Django, however, I'm just looking for a simple way to connect a client of my Django website to my discord server. I need to be able to add or remove them from the discord, assign them a role. Can you point me to a maintained package that would help me do this? -
Flask for Python with MySQL
After my program can detect the relevant objects, it successfully grabs the information of the database and displays it on the web, but I don’t know why AttributeError: 'tuple' object has no attribute 'encode' keeps appearing after detecting the objects. Then my Occasionally, the detection program will automatically turn off. my app.py from flask import Flask, render_template, Response, request, redirect, url_for, flash import cv2 import numpy as np import torch import time import base64 import mysql.connector app = Flask(__name__) model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt', force_reload=True) cap = cv2.VideoCapture(0) height, width, _ = cap.read()[1].shape baseline = height // 2 + 100 video_paused = False object_names = [] # 使用列表來存儲檢測到的物體名稱 def get_product_data(object_name): cnx = mysql.connector.connect(user='root', password='', host='localhost', database='product') cursor = cnx.cursor() query = f"SELECT * FROM information WHERE product_name = '{object_name}'" cursor.execute(query) data = cursor.fetchone() cursor.fetchall() # 確保所有結果都被讀取 select_query = "SELECT image_data FROM information WHERE product_name = %s" cursor.execute(select_query, (object_name,)) result = cursor.fetchone() cursor.close() cnx.close() if data : message = f"<br>產品名稱:{data[1]}<br>價格:{data[2]}<br>折扣價格:{data[3]}<br>折扣:{data[4]}<br>" image_data = result[0] return message, image_data else: return message def detect_objects(): while cap.isOpened(): success, frame = cap.read() if not success: print("Ignoring empty camera frame.") continue frame = cv2.resize(frame, (800, 480)) if video_paused: time.sleep(1) continue results = model(frame) detected_objects = results.xyxy[0] cv2.line(frame, … -
How to connect localhost Django Rest API to Android emulator?
I'm new to Django and Flutter. I have working Django Rest Api and I need to connect it to my flutter application. I have trouble connecting it to Pixel 2 API 30 android emulator. I have corsheaders installed, tried multiple tutorials but it just doesn't work. My ALLOWED_HOSTS are '127.0.0.1', 'localhost', my IP and also my pc name. My API used to work perfectly fine, but when I tried to connect my android app, it tried to find port :443, which I don't have. For some reason, right now it gives me an error whenever I run django server. Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /142.250.74.42:443 [21/May/2023 17:59:14] "CONNECT 142.250.74.42:443 HTTP/1.1" 404 1800 Not Found: /216.58.207.234:443 [21/May/2023 17:59:14] "CONNECT 216.58.207.234:443 HTTP/1.1" 404 1803 Not Found: /216.58.207.202:443 [21/May/2023 17:59:14] "CONNECT 216.58.207.202:443 HTTP/1.1" 404 1803 Not Found: /[2a00:1450:400f:803::200a]:443 Django API works perfectly fine, I can access my database and admin panel, but I just can't connect my app to it. It searches for 127.0.0.1:443 which doesn't exist. How do I fix this problem? When I run my app through Google Chrome, it connects but there are other problems. For Chrome I use BASE_URL = "http://127.0.0.1:8000" which … -
Combine Images to make a video with transitions
Am using moviepy library to come up with a video from list of Images am having a table which is from Django Models (It has a field for Images). So it's basically a Django command which will be executed to create a video of Images transitioning. The video first shows well the first 2 Images, but afterwards it shows blurred Images. There's also an audio which is inserted into the video. What could be the Issue, here's my code : from django.core.management.base import BaseCommand from faker import Faker from moviepy.audio.io.AudioFileClip import AudioFileClip from moviepy.video.compositing.concatenate import concatenate_videoclips from moviepy.video.io.ImageSequenceClip import ImageSequenceClip from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip from moviepy.editor import vfx from moviepy.audio.fx.audio_fadeout import audio_fadeout from django.core.files import File from events.models import Events, AudioFiles, LiveShortVideos import random import requests from PIL import Image import io import os def crossfade(clip1, clip2, transition_duration): clip1_end = clip1.duration - transition_duration clip2_start = 0 crossfaded_clip1 = clip1.crossfadeout(transition_duration) crossfaded_clip2 = clip2.crossfadein(transition_duration).set_start(clip1_end) return CompositeVideoClip([crossfaded_clip1, crossfaded_clip2]) class Command(BaseCommand): help = 'Generate short video for a particular event' def add_arguments(self, parser): parser.add_argument( 'event_code', type=str, help='ID of the event for which to generate a video') def handle(self, *args, **kwargs): event_code = kwargs['event_code'] event = Events.objects.get(event_code=event_code) # Select up to 5 images randomly related … -
Deployment error. Error running WSGI application. ModuleNotFoundError: No module named 'api.urls'
I deployed my django project to pythonanywhere, but when I enter the page, this error is displayed in the logs: Error running WSGI application ModuleNotFoundError: No module named 'api.urls' Structure: /home/danialsk/unitree/ # Main project directory unitree/ # Main project's Python package settings.py # Django settings file urls.py # Main project's URL configuration file ... api/ # 'api' app directory urls.py # URLs for the 'api' app ... features/ urls.py # URLs for the 'features' app ... pip list: (env) 13:42 ~/unitree/unitree (master)$ pip list Package Version ------------------- -------- api 0.0.7 asgiref 3.6.0 blinker 1.6.2 certifi 2023.5.7 charset-normalizer 3.1.0 click 8.1.3 colorama 0.4.6 Django 4.2.1 django-ckeditor 6.5.1 django-embed-video 1.4.8 django-filter 23.2 django-js-asset 2.0.0 djangorestframework 3.14.0 Flask 2.3.2 gunicorn 20.1.0 idna 3.4 itsdangerous 2.1.2 Jinja2 3.1.2 Markdown 3.4.3 MarkupSafe 2.1.2 nose 1.3.7 Pillow 9.5.0 pip 22.1.2 psycopg2 2.9.6 pytz 2023.3 requests 2.30.0 setuptools 62.6.0 sqlparse 0.4.4 tzdata 2023.3 urllib3 2.0.2 Werkzeug 2.3.4 wheel 0.37.1 whitenoise 6.4.0 WSGI file: import os import sys # assuming your django settings file is at '/home/danialsk/mysite/mysite/settings.py' # and your manage.py is is at '/home/danialsk/mysite/manage.py' path = '/home/danialsk/unitree/unitree' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'unitree.settings' # then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Main urls: … -
Regroup many-to-many fields in django
I have these model relationships class ExerciseCategory(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=100) class UserExercises(models.Model): #Through table for the many-to-many relationship between User and Exercise user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="user") exercise = models.ForeignKey('Exercise', on_delete=models.CASCADE) class Exercise(models.Model): category= models.ManyToManyField(ExerciseCategory, through='CategoryExercisesThrough',blank=True, null=True) assignee = models.ManyToManyField(get_user_model(), blank=True, null=True, through=UserExercises, related_name="assignee", through_fields=('exercise', 'user')) class CategoryExercisesThrough(models.Model): #Through table for the many-to-many relationship between ExerciseCategory and Exercise category= models.ForeignKey(ExerciseCollections, on_delete=models.CASCADE) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) I want to get all the UserExercises of a given user and then display them in my template grouped by category, so if I have: {Ex1: {category: ["C1", "C2"]}, Ex2: {category: "C2"}}, I want them reordered like this: {"C1": ["Ex1"], "C2": ["Ex2", "Ex1"]} -
import dj_database_url ModuleNotFoundError: No module named 'dj_database_url'- DJANGO HEROKU
Running python manage.py makemigrations on ⬢ chatnwrite-cli... up, run.3184 (Basic) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/checks/translation.py", line 60, in check_language_settings_consistent get_supported_language_variant(settings.LANGUAGE_CODE) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/app/mainapp/settings.py", line 196, in <module> import dj_database_url ModuleNotFoundError: No module named 'dj_database_url' I HAVE IMPORTED AND DELETED IT SINCE THIS MORNING, WHY DO I HAVE THIS CONTINUOS ERROR? DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME':'', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': 5432, 'CONN_MAX_AGE': 500 } } -
Image not displaying in HTML template using Django and static files
I'm developing a web application using Django and I'm facing an issue with displaying images in an HTML template. Instead of showing the image, it only displays the alt text. Here's the relevant part of my code: <!DOCTYPE html> <html lang="en"> <head> <!-- Head content --> </head> <body> <!-- Top Section --> <!-- Mid Section --> <div class="ProfileCardConatiner"> {% for t in donors %} <div class="card"> <div class="cardDetailCont"> <div class="profile-image"> <img src="{% static t.profile_pic.url %}" alt="Donor Profile" /> </div> <!-- Other card content --> </div> <!-- Card buttons --> </div> {% endfor %} </div> </body> </html> In my Django project, I have correctly set up the STATIC_URL and STATIC_ROOT in the settings file. The images are stored in the correct directory within the static folder, and I have verified that the image URLs are correctly generated in the rendered HTML. Despite this, when I load the page, instead of displaying the actual images, only the alt text "Donor Profile" is shown. I have checked the image file paths, and they seem to be correct. I'm not sure why the images are not displaying as expected. Could someone please guide me on how to troubleshoot and resolve this issue? Any suggestions … -
Django and Wagtail send_mail are using EMAIL_HOST_USER as from_email
The task: I´m sending a newsletter subscription notification to an email address with Wagtail. For this I overwride the send_mail function (of the AbstractEmailForm) and use from wagtail.admin.mail import send_mail to send the email – simple and straight-forward. The problem: I provide a from_email, but for some reason the email I receive contains the EMAIL_HOST_USER (as sender). I also tried from django.core.mail import send_mail but it´s the same. Is there any clue, how I can manage to make it work? Maybe the block to use custom email address showed as a sender? Details: smtp.gmail.com and django.core.mail.backends.smtp.EmailBackend is used for the email backend. -
Efficient way for Refreshing Database Entries Without Downtime or Data Loss
I am designing a service for providing bestseller products in a branch for last 30 days. These entries have to be refreshed each day as to accommodate the last day sales too. Table structure branch_id product_id i wrote a function to provide the bestsellers. def bestsellers(branch_id): //returns list of product_ids One way is to i delete all the entries and then dump new entries, but as i have been told by my senior that you should not delete the entries, Also for few seconds there wont be any products in the table. I am expecting that the service should always return some products. what should be the best way to achieve this? -
Django "Operational Error - no such table" (multiple databases)
I'm trying to use 2 databases in a Django project. The first 3 apps I made used sqlite3; I wanted to keep the data from those apps (/polls, /cats and /autos) in the first database and switch to mysql from here on. So I created dbRouters for the 3 previous apps and set mysql as the new default database. ('original' is the old one.) settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ... ... } }, 'original': { 'ENGINE': 'django.db.backends.sqlite3', ... ... }, } DATABASE_ROUTERS = ['polls.dbRouter.PollsDBRouter', 'autos.dbRouter.AutosDBRouter', 'cats.dbRouter.CatsDBRouter', ] Now the old apps would work, but the new one (/ads) wouldn't load, saying "Operational Error - no such table". Exception Location "/.../.../django/db/backends/sqlite3/base.py" line 477. I've verified in mysql client that the table for the new app (ads) does exist: +----------------------------+ | Tables_in_cini$ads | +----------------------------+ | ads_ad | *** | autos_auto | | autos_make | | cats_breed | | cats_cat | *** | polls_choice | | polls_question | *** +----------------------------+ The interesting thing is, if I comment out the database routers & 'original' database in settings.py, the new 'ads' app loads fine. (But in that case, the other apps aren't pulling from the database). If I create a dbRouter.py for … -
How can i get the name of each item that has been looped?
How do I get the name of each item from the looped Django model? I am doing a little project and I have hit a wall on this, <div class="row row-cols-1 row-cols-md-4 g-4 mb-4"> {% for pizza in pizzas %} <div class="col"> <div class="card h-100"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">**{{pizza.name|title}}**</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div class="card-footer d-flex justify-content-between"> <a href="{% url 'store:custompizza' pk=pizza.pk %}" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#exampleModal">Customize</a> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">{{pizza.name|title}}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="defaultCheck1"> <label class="form-check-label" for="defaultCheck1"> Default checkbox </label> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button> <button type="button" class="btn btn-warning">Add to cart</button> </div> </div> </div> </div> <small class="fw-bold">${{pizza.price}}</small> The model: class pizza(models.Model): name = models.CharField(max_length=40, blank=True) price = models.DecimalField(decimal_places=2, max_digits=3) def get_absolute_url(self): return reverse("store:custompizza", kwargs={"pk": self.pk}) The View: class PizzaList(ListView): model = pizza context_object_name = 'pizzas' So what i'm trying to do in this little project is for each item that I looped I want … -
Getting error "Error getting credentials - err: exit status 1, out : ``" when trying to build on my mac but in ubuntu everything looks good
When is was trying to build on my Mac, the following issue occurred "Error getting credentials - err: exit status 1, out:" When I was building the django project on my mac. following issue is occuring. sudo docker-compose -f docker-compose.dev.yml up -d --build Password: WARN[0000] The "hl0" variable is not set. Defaulting to a blank string. WARN[0000] The "hl0" variable is not set. Defaulting to a blank string. WARN[0000] The "hl0" variable is not set. Defaulting to a blank string. WARN[0000] The "hl0" variable is not set. Defaulting to a blank string. 2023/05/21 14:09:08 must use ASL logging (which requires CGO) if running as root [+] Running 0/0 ⠋ db Pulling 0.0s error getting credentials - err: exit status 1, out: `` My docker-compose Looks like version: "3.3" services: db: image: postgres:14.0-alpine environment: POSTGRES_USER: ${SQL_USER} POSTGRES_PASSWORD: ${SQL_PASSWORD} POSTGRES_DB: ${SQL_DATABASE} volumes: - rbn_db:/var/lib/postgresql/data networks: - rbn web: build: ./ # command: gunicorn monsite.wsgi:application --bind 0.0.0.0:8000 command: python manage.py runserver 0.0.0.0:8000 volumes: - ./:/code ports: - "9005:8000" env_file: - ./.env depends_on: - db networks: - rbn volumes: rbn_db: networks: rbn: driver: bridge .env file looks like DEBUG=1 SECRET_KEY=(gq!il9r&&a49rweb47qxwwogjsqeq2$hl0+6s6nx8dx^3 DJANGO_ALLOWED_HOSTS=localhost;127.0.0.1 SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=rbn SQL_USER=rbn_user SQL_PASSWORD=gjjhgfjgfdgfgdsfsf SQL_HOST=db SQL_PORT=5432 DJANGO_DEBUG=True -
Django: Adding a field which allows multiple images
Forms.py class SellerForm(forms.ModelForm): username = forms.CharField() class Meta: model = Seller fields = [ 'username', 'first_name', 'last_name', 'country', 'image_of_seller', 'city', 'date_of_birth', 'describe_yourself' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].initial = self.instance.seller.username @transaction.atomic def save(self, commit=True): seller = super().save(commit=False) user = seller.seller self.instance.seller.username = self.cleaned_data['username'] if commit: seller.save() user.save() return seller Views.py class SellerUpdateView(UpdateView): model = Seller form_class = SellerForm template_name = 'core/seller_update_form.html' def get_object(self, queryset=None): return self.request.user.seller Models.py class Seller(models.Model): seller = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, default=False) country = models.CharField(max_length=50, null=False, blank=False) identification = models.ImageField(null=False, blank=False) image_of_seller = models.ImageField(null=False, blank=True) # I want this to accept multiple files, which are images. city = models.CharField(max_length=30) date_of_birth = models.DateField(null=False, blank=False) describe_yourself = models.TextField(null=False, blank=False) slug = models.SlugField(unique = True, blank = True) def __str__(self): return self.seller.username def save(self, *args, **kwargs): self.slug = slugify(self.seller.username) super().save(*args, **kwargs) I know I can create another model, with a ForeignKey to the Seller model, then have inline while creating ModelAdmin. But is there a way to have this for the form instead? I want the user to be able to update their pictures. -
How can I request data from a C# service using Django and Python?
I want to post a request of data to a c# service using django... this is c# sampel and i want do this with python. TestService.TestServiceClient srv = new CarDamageService.TestServiceClient(); TestService.Response response = new TestService.Response (); TestService.RequestTestData Request = new TestService. { prv = new List<TestService.RequestTestPrv> { new TestService.RequestTestPrv { Id =97475390127457, }.ToArray(), adjusted = new List<TestService.RequestTestData> { new TestService.RequestTestData { Id =352907, }, }.ToArray() }; response = srv.FinalTest (user, pass, Request); what can I do??? i try send data with this format: <RequestTestData><Prv><Id>1216</Id></Prv><adjusted><Id>1234</Id></RequestTestData> but this format was not correct... -
Why does pressing login redirect to register page and show MultivalueDictError in Django?
def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('/') else: messages.info(request , 'Credentials not correct') return redirect('login') return render(request,'login.html') i dont know why when i press login it redirect to register and show multivaluedicterror. even i have not redirected to register page in code login.html ERROR -
How to access Foreign Fields in Django
I'm a beginner with Django. I have a set of tables with relationships defined in my models, and I am looking to retrieve linked values in the front end. I'm unable to find out how to do this, and would appreciate help. I can currently see something that looks like this, where 1 is the key of the currency EUR in the Currency table: Spend Amount | Spend Currency 10 | 1 I instead want it to look like this: Spend Amount | Spend Currency 10 | EUR Models class Currency (models.Model): currCode = models.CharField('Currency',max_length=3) currName = models.CharField('Name',max_length=100) class Spend (models.Model): spendAmount = models.DecimalField('Amount', max_digits=12,decimal_places=2) spendCurrency = models.ForeignKey(Currency) Views from .models import Spend def all_spends(request): spend_list = Spend.objects.all() return render(request, 'spends/spend_list.html', {'spend_list': spend_list}) HTML Template {% for spend in spend_list %} <tr> <th>{{ spend.spendAmount }}</th> <th>{{ spend.spendCurrency }}</th> </tr> {% endfor %} -
Django CORS issue with VUE
I am running python 3.11.3 with the following packages: Package Version ------------------- ------- asgiref 3.6.0 Django 4.2.1 django-cors-headers 4.0.0 pip 23.1.2 setuptools 67.6.1 sqlparse 0.4.4 whitenoise 6.4.0 I am trying to enable cors for Vue but I keep running into the orbidden (Origin checking failed - http://127.0.0.1:8090 does not match any trusted origins.): /api/login/ In settings.py, I have: CORS_ALLOW_ALL_ORIGINS = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'reports', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] Browser response header access-control-allow-origin: http://127.0.0.1:8090 Content-Length: 2569 Content-Type: text/html; charset=utf-8 Cross-Origin-Opener-Policy: same-origin Date: Sun, 21 May 2023 08:13:21 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.11.3 Vary: origin X-Content-Type-Options: nosniff X-Frame-Options: DENY Request header Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,es;q=0.8 Connection: keep-alive Content-Length: 40 Content-Type: application/json DNT: 1 Host: 127.0.0.1:8000 Origin: http://127.0.0.1:8090 Referer: http://127.0.0.1:8090/ sec-ch-ua: "Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "macOS" Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Do you have any idea what I am doing wrong? Any help would be appreciated. Thanks, -
How to include to IP address/username in Django logging?
Background I am trying to write logs in Django that not only stores the messages but also necessary information of the requests like IP address and user in the logs. I noticed that I could use the extra attribute of logger to include request like logger.info("my message", extra={'ip': request.ip, 'user': request.user}. But this will be extremely cumbersome to include this extra block for every log in my app. It will also be unmanageable if I wish to add an extra attribute to display in the future. Based on my understanding LogAdapter is only useful when the extra context is static. I tried to follow How can I add the currently logged in username to the access log of django.server? to use a custom middleware to store request object in thread local storage and read the object from my custom filter. import logging import threading local = threading.local() class RequestFilter(logging.Filter): def filter(self, record): request = getattr(local, 'request', None) if request: record.ip = request.META.get('REMOTE_ADDR') record.user = request.user.username else: record.ip = '-' record.user = '-' return True class LogRequestMiddleware: """ A middleware that stores request object into the thread local storage, so that logging filter can access it and populate necessary information to …