Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload File along with the by default setting "Anyone with the link" in Google Drive using Python?
I am using the following code to upload my file in Google drive using googleapiclient module in Python. from __future__ import print_function from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload from httplib2 import Http from oauth2client import file, client, tools import argparse class Drive: # If modifying these scopes, delete the file token.json. SCOPES = 'https://www.googleapis.com/auth/drive.file' extensions = {"csv":"text/csv","mpeg":"video/mpeg","mpg":"video/mpeg","tiff":"image/tiff","tif":"image/tiff","bmp":"image/bmp","gif":"image/gif","wav":"audio/wav","avi":"video/x-msvideo","bmp":"image/bmp","doc":"application/msword","docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document","jpg":"image/jpeg","jpeg":"image/jpeg","mp4":"video/mp4","mpg":"video/mpeg","pdf":"application/pdf","png":"image/png","ppt":"application/vnd.ms-powerpoint","pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation","rar":"application/octet-stream","tar":"application/x-tar","txt":"text/plain","wmv":"video/x-ms-wmv","xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","zip":"application/x-zip-compressed"} def __init__(self): try: flags = tools.argparser.parse_args([]) except ImportError: flags = None store = file.Storage('token.json') self.creds = store.get() if not self.creds or self.creds.invalid: flow = client.flow_from_clientsecrets(settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES) if flags: self.creds = tools.run_flow(flow, store, flags) self.service = build('drive', 'v3', http=self.creds.authorize(Http())) def create_folder(self,folder_name): folder_id = None query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='" + folder_name + "'" results = self.service.files().list( pageSize=1, q=query, fields="files(id, name)").execute() folders = results.get('files', []) if folders: folder_id = folders[0]['id'] # If folder not found, then create it. else: file_metadata = { 'name': folder_name, 'mimeType': 'application/vnd.google-apps.folder' } folder_file = self.service.files().create(body=file_metadata, fields='id').execute() folder_id = folder_file.get('id') return folder_id def upload_file(self, folder_id, file_name): file_metadata = { 'name': file_name.temporary_file_path(), 'parents': [folder_id] } media = MediaFileUpload(file_name.temporary_file_path(), mimetype= self.extensions[file_name.name.split(".")[1]],resumable=True) print(media) _file = self.service.files().create(body=file_metadata, media_body=media,fields='id').execute() file_id = _file.get('id') return file_id Above code works file but the file which uploads on Google Drive saves with restricted option. What … -
Trouble Generating Avatars from Uploaded Images in OpenAI
I am trying to build an application in OpenAI that allows users to upload their own images and generate avatars based on those images while performing a specific activity that the user inputs. However, I am running into some issues with generating the avatars. Whenever I upload an image and input an activity, the avatar that is generated appears distorted and does not accurately represent the original image or the activity being performed. The colors are off and the details are not crisp. I have tried different image processing techniques such as resizing and cropping the image before generating the avatar, as well as incorporating the user's input activity into the avatar generation process, but none of them seem to improve the quality of the avatar. I suspect that there might be some issue with the way I am generating the avatar or with the code I am using to process the image and activity input. from django.shortcuts import render from django.core.files.storage import default_storage from django.core.files.base import ContentFile import openai import requests from requests.structures import CaseInsensitiveDict from django.conf import settings openai.api_key = settings.OPENAI_API_KEY def generate_images(request): if request.method == "POST": image_file = request.FILES.get('image') activity1 = request.POST.get('activity1') activity2 = request.POST.get('activity2') # Construct … -
Django Cannot keep last 3 row of database
I want to keep latest 3 row of each key and delete oldest row if data of each key more than 3 row. I have sample data like this. id value key created 1 a1 001 2023-04-23 01:01:00 <= delete oldest of key 001 2 a2 001 2023-04-23 01:02:00 3 a3 001 2023-04-23 01:03:00 4 a4 001 2023-04-23 01:04:00 5 a5 002 2023-04-23 01:05:00 <= delete oldest of key 002 6 a6 002 2023-04-23 01:06:00 7 a5 002 2023-04-23 01:07:00 8 a6 002 2023-04-23 01:08:00 I get latest 3 row order by create and delete oldest with this code. if Key.objects.filter(key=key).exists(): objects_to_keep = Data.objects.filter(key=key).order_by('-created').values_list("id", flat=True)[:3] objects_to_keep = list(objects_to_keep) Data.objects.exclude(pk__in=objects_to_keep).delete() If I add new row key=001 it remove all data of key 002 and the same when add new row key=002 it remove all data key 001. The output should be like this. id value key created 2 a2 001 2023-04-23 01:02:00 3 a3 001 2023-04-23 01:03:00 4 a4 001 2023-04-23 01:04:00 6 a6 002 2023-04-23 01:06:00 7 a5 002 2023-04-23 01:07:00 8 a6 002 2023-04-23 01:08:00 How to fix it? -
Django VideoField
I'm want to make a custom FileField that only allows video uploads I'm trying to use pymediainfo to make sure the file uploaded is a video but I keep getting FileNotFoundError here's my code from django.core.exceptions import ValidationError from django.db import models from pymediainfo import MediaInfo from django.db.models.fields.files import FieldFile class VideoField(models.FileField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def validate(self, file : FieldFile, model_instance): super().validate(file, model_instance) media_info = MediaInfo.parse(file.path) if media_info.tracks[0].track_type != 'Video': raise ValidationError('The file must be a video.') and here's the model code def lecture_video_handler(instance, filename): return f"chapters/{instance.chapter_id}/lectures/{instance.id}/{filename}" class Lecture(models.Model): chapter = models.ForeignKey('course.Chapter', models.CASCADE) video = VideoField(upload_to=lecture_video_handler) in settings.py I'm using the default file storage not a custom one MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') what am I doing wrong? -
It is impossible to add a non-nullable field 'mobile' to sales without specifying a default
Here is my models.py class Sales(models.Model): product = models.CharField(max_length=50) name = models.CharField(max_length=50) image = models.ImageField(null=True, blank=True, upload_to="images/") price = models.IntegerField() mobile = models.IntegerField() here i checked the migrations and it shows like that It is impossible to add a non-nullable field 'mobile' to sales without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. help mw to rectify ityour text -
CORS problem, but only on one endpoint and only in Windows
I have a Django backend (using Django REST Framework), and a SvelteKit frontend that talks to it. Everything works perfectly fine in all browsers across Windows and macOS, all POST and DELETE requests and all that have the correct CORS headers. Except the endpoint to upload images. That one doesn't seem to work for Windows users, in Edge, Chrome, or Firefox. The endpoint uses Django REST Framework's APIView, just like many other endpoints. class ImageUploadParser(FileUploadParser): media_type = "image/*" def get_filename(self, stream, media_type, parser_context): # We create our own filename, and we get the extension based on the actual file type return "unused.nope" class ImageUploadView(APIView): permission_classes = (permissions.IsAuthenticated,) parser_classes = [ImageUploadParser] def post(self, request): # [A bunch of logic to upload the file...] return Response({"url": f"{relative_path}/{filename}"}, status=status.HTTP_201_CREATED) I've set up corsheaders.middleware.CorsMiddleware and its CORS_ALLOWED_ORIGINS setting. Like I said, all other endpoints work fine, and the upload endpoint also works fine under macOS (Safari, Edge and Firefox). This is the network inspector in Safari: And this is Edge on Windows: What could cause this one endpoint to not work, and only in Windows? How can I solve it? -
DebugToolbarMiddleware' object is not iterable
TypeError at /playground/hello/ 'DebugToolbarMiddleware' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/playground/hello/ Django Version: 4.2 Exception Type: TypeError Exception Value: 'DebugToolbarMiddleware' object is not iterable Exception Location: C:\Users\DELL\anaconda3\lib\site-packages\debug_toolbar\panels\templates\panel.py, line 47, in _request_context_bind_template Raised during: playground.views.say_hello Python Executable: C:\Users\DELL\anaconda3\python.exe Python Version: 3.9.13 Python Path: ['C:\Users\DELL\OneDrive\Desktop\storefront\storefront', 'C:\Users\DELL\anaconda3\python39.zip', 'C:\Users\DELL\anaconda3\DLLs', 'C:\Users\DELL\anaconda3\lib', 'C:\Users\DELL\anaconda3', 'C:\Users\DELL\anaconda3\lib\site-packages', 'C:\Users\DELL\anaconda3\lib\site-packages\win32', 'C:\Users\DELL\anaconda3\lib\site-packages\win32\lib', 'C:\Users\DELL\anaconda3\lib\site-packages\Pythonwin'] Server time: Sun, 23 Apr 2023 09:37:08 +0000 I tried but i am not getting -
ERD recommendations
I am building a basketball personal trainer management system and I stuck in this.. Each drill type(ball handling, reaction, agility..) has more than one level(Easy,hard,..) and has more than one type of challenges (against quantity and against time) what is the best solution(ERD tables) for this problem?? first i tried to add two more entities one to break the many to many relationship between drill type and drill challenge i called the table (TYPE - Challenge ) and then add another entity to break the many to many relationship between drill type and drill level called (TYPE - LEVEL ) and then break the many to many relationship between (TYPE - CHALLENGE) and (TYPE - LEVEL) by a third entity called (TYPE-CHALLENGE-LEVEL) -
run [python manage.py custom commands] AttributeError: 'PosixPath' object has no attribute 'startswith'
I'm getting an error running python manager.py commands with Django 4.2. My development environment is: Python 3.10.10 Django 4.2 # python manage.py run_cmdb_worker Traceback (most recent call last): File "/usr/local/python/lib/python3.10/pkgutil.py", line 417, in get_importer importer = sys.path_importer_cache[path_item] KeyError: PosixPath('/www/cloudadmin') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/www/cloudadmin/manage.py", line 22, in <module> main() File "/www/cloudadmin/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/.pyvenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/opt/.pyvenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/.pyvenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 275, in fetch_command klass = load_command_class(app_name, subcommand) File "/opt/.pyvenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 48, in load_command_class module = import_module("%s.management.commands.%s" % (app_name, name)) File "/usr/local/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/www/cloudadmin/apps/cmdb/management/commands/run_cmdb_worker.py", line 2, in <module> from cmdb.scheduler import Scheduler File "/www/cloudadmin/apps/cmdb/scheduler.py", line 3, in <module> from apscheduler.schedulers.background import BackgroundScheduler File "/opt/.pyvenv/lib/python3.10/site-packages/apscheduler/__init__.py", line 1, in <module> from pkg_resources import get_distribution, DistributionNotFound File "/opt/.pyvenv/lib/python3.10/site-packages/pkg_resources/__init__.py", line 3260, in <module> def _initialize_master_working_set(): File "/opt/.pyvenv/lib/python3.10/site-packages/pkg_resources/__init__.py", line 3234, in _call_aside … -
AttributeError: 'ContactSerializer' object has no attribute 'get_status'
Hi all I have this error when im trying to save my serializer AttributeError: 'ContactSerializer' object has no attribute 'get_status' I render my serializer as form so I've created custom template for forms just to add new classes class ContactSerializer(serializers.ModelSerializer): status = serializers.SerializerMethodField(read_only=True) name = serializers.CharField( style={ "template": TEMPLATE_PATH, "class": "custom_form_control", "input_type": "input" } ) email = serializers.CharField( style={ "template": TEMPLATE_PATH, "class": "custom_form_control", "input_type": "input" } ) subject = serializers.CharField( style={ "template": TEMPLATE_PATH, "class": "custom_form_control", "input_type": "select", "choice": Contact.SUBJECT } ) message = serializers.CharField( style={ "template": TEMPLATE_PATH, "input_type": "textarea", } ) class Meta: model = Contact fields = "__all__" And everything works great but when I'm trying to POST it (save it) i get attribute error. My guess is that this is related to status field that is read-only and defaults to "New" models class Contact(models.Model): APP = 'app support' PAY = 'payment support' HR = 'HR/Jobs' OTHER = 'other' SUBJECT = [ (APP, _('App Support')), (PAY, _('Payment Support')), (HR, _('HR & Jobs')), (OTHER, _('Non related (Other)')) ] STATUS = ( ('New', _('New')), ('In Progres', _('In Progres - somone is taking an action')), ('Resolved', _('Resolved - action was made')), ) name = models.CharField(blank=False, max_length=50, validators=[MinLengthValidator(4)]) email = models.EmailField(max_length=55, blank=False) subject … -
Python Django - AttributeError: 'IdeaView' object has no attribute 'user'
My website allows users to post their ideas and other users comment on the ideas and rate the idea from 1 to 10. The Idea page loads with the users idea and the rating form and comment form, but when a logged in user tries to submit the comment form or rating form they encounter the AttributeError. Because the page loads I believe the get() method is working, but I don't believe the post() method is working. How do I access the user attribute in my view? Here is my class based view that handles the idea page: class IdeaView(TemplateView): template_name = 'idea.html' def get_average_rating(self, idea): """get average rating for an idea""" ratings = Rating.objects.filter(idea=idea) # aggregate function used to perform calcs on database records. Takes one or more arguments. # returns dictionary containing results of calcs. # rating__sum is the key used to access the sum of the 'rating' values from the dictionary. total_ratings = ratings.aggregate(Sum('rating'))['rating__sum'] or 0 number_of_ratings = ratings.count() or 0 return total_ratings / number_of_ratings def get_context_data(self, **kwargs): # call corresponding method of parent class and updating context dict. with data defined in get_context_data() method context = super().get_context_data(**kwargs) # add additional data to context dictionary that is … -
Accessing Django request inside model manger
I have a model that gets called in 300+ places inside my codebase, each model has to be filtered by the company_filter by default, no exceptions. I need values from the request namely tenant_id and tenant_type, these values are available on every request. I filter the Company model using the tenant_id and then pass the company, tenant_id and tenant_type to the filter which then filters the Queryset, this seems to work just fine but I'm not sure about memory leaks and requests maybe getting mixed up for different users? Is there a better approach to accomplish this or is this a valid approach? Middleware import threading _thread_local = threading.local() class RequestMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): _thread_local.request = request response = self.get_response(request) # Free up the memory after view is returns del _thread_local.request return response def get_request(): return getattr(_thread_local, 'request', None) Model class TariffrateCompanyManger(models.Manager): # Filters the tariff by the company by default def get_queryset(self): from config.middleware import get_request request = get_request() company = Company.objects.get_company_tenant_id(request.tenant_id) company_filter = tariff_company_filter(company, request.tenant_id, request.tenant_type) if request: qs = super().get_queryset().filter(company_filter) else: qs = super().get_queryset() return qs -
Running an application via docker container on http://localhost:8000/ returns Bad Request, but http://127.0.0.1:8000/ works
Disclaimer: I am a docker noob and I'm trying to learn. I am also running this on Windows 10 Here's my Dockerfile.yaml FROM python:3.11 # setup env variables ENV PYTHONBUFFERED=1 ENV DockerHOME=/app/django-app # Expose port EXPOSE 8000 # create work dir RUN mkdir -p $DockerHOME # set work dir WORKDIR $DockerHOME # copy code to work dir COPY . $DockerHOME # install dependencies RUN pip install -r requirements.txt # move working dir to where manage.py is WORKDIR $DockerHOME/flag_games # set default command (I thinkk) ENTRYPOINT ["python"] # run commands for app to run CMD ["manage.py", "collectstatic", "--noinput"] CMD ["manage.py", "runserver", "0.0.0.0:8000"] Here are the commands I use (I run make docker-build and make docker-run) docker-build: docker build --tag docker-django . docker-run: docker run -d -p 8000:8000 --name flag-game docker-django My container runs fine (venv) PS C:\Users\Admin\Projects\flag-games> docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 175c38b4ea9e docker-django "python manage.py ru…" 26 minutes ago Up 26 minutes 0.0.0.0:8000->8000/tcp flag-game When I try to hit the website I get: (venv) PS C:\Users\Admin\Projects\flag-games> curl.exe -v localhost:8000 * Trying 127.0.0.1:8000... * Connected to localhost (127.0.0.1) port 8000 (#0) > GET / HTTP/1.1 > Host: localhost:8000 > User-Agent: curl/8.0.1 > Accept: */* > < … -
How to use StreamingHttpResponse to send content in chunks in a Django project?
I use Django for local development, and use StreamingHttpResponse to send content in chunks. However, when deploying with Django+uwsgi+nginx, the StreamingHttpResponse no longer sends content in chunks, only sending it all at once. What could be causing this? this is my uwsgi config [uwsgi] socket = 127.0.0.1:8082 chdir = /usr/release/publicapi/ wsgi-file = publicapi/wsgi.py module = publicapi.wsgi master = true #home = /usr/local/anaconda3/envs/bg/ daemonize = /usr/release/logs/uwsgi.log vacuum = true processes = 5 pidfile = /usr/local/nginx/uwsgi/uwsgi8086.pid home = /usr/local/anaconda3/envs/bg/ #ignore-sigpipe=true #ignore-write-errors=true #disable-write-exception=true harakiri=3000 post-buffering=56553600 http-timeout=6000 -
How to set a dynamic URL in a parent template in Django?
I am using a parent template in my django project for the navigation menu. In the navigation menu I have a tag that has an href that will point to the current week of NFL games. I want to set this dynamically based on the current time. I am looking for something I can set in my parent template so that I don't have to repeat code in every child template. The model I am using for the Week is: class Week(models.Model): WeekID = models.BigAutoField(primary_key=True) Week = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(18)]) SeasonID = models.ForeignKey('Season', on_delete=models.SET_NULL, null=True) TimeStart = models.DateTimeField() TimeEnd = models.DateTimeField() def __str__(self): return f"{self.SeasonID.Year} Season Week {self.Week}" My parent template code is: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static 'styles.css' %}" /> <title>{% block pageTitle %} {%endblock%}</title> </head> <body> <nav class="navigation"> <ul class="navigation__list"> <li class="navigation__item"> {% for week in current_week %} <a href="/my_app/week/{{week.WeekID}" class="navigation__link">Current Week</a> {% endfor %} </li> </ul> </nav> <main>{% block content %} {% endblock %}</main> </body> </html> The view that I need to get the necessary data: def current_week(request): current_time = datetime.now() current_week = Week.objects.filter(TimeStart_lt=current_time, TimeEnd_gt=current_time) print(current_week) return render(request, … -
DJango app on Nginx - Redirecting links to other servers back to my domain. How do i fix this?
So i messed up when i registered my certbot file and only registered it for www.example.com instead of that plus domain.com to my website so i forced all proxy_pass to the www.example.com to be able to deploy except now when i try to link to my shopify store it redirects the link right back to my www.example.com Here is my nginx.conf, hopefully someone knows what i did wrong... user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 4096; # multi_accept on; } http { sendfile on; tcp_nopush on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; server { listen 80; return 444; } server { server_name www.example.com, example.com; listen 80; return 307 https://www.example.com$request_uri; } server { listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot server_name www.example.com; ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404.; proxy_pass http://unix:/run/gunicorn.sock; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; … -
Does LoginRequiredMixin Allow Two Forms?
I downloaded a cookie-cutter django application that provides some basic user handling pages/views. Typically, login and sign-up pages are separated. This allows for one {{ form }} to be displayed for each. I want to place both forms on the same page. On the front-end, both forms are present with csrf tokens, but submitting the login form POSTs to the sign-up page. I don't know much about the internals of LoginRequiredMixin (and they are hard to find), but I'm assuming that the {{ form }} that it seems to put on the page is limited to one form. Is there a way to allow for the submission of two different forms on the same page/view using this mixin? I assume that this mixin is the issue because the urls it redirects to and the form it mentions are nowhere else in my project code (including urls.py). If I'm assuming wrong, I'm definitely interested in where the real problem lies. Here's a sample of what I'm trying to do. <div class="forms"> <input type="checkbox" id="chk" aria-hidden="true"> <div class="signup"> <form id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} <label class="signup-label" for="chk" aria-hidden="true">Sign up</label> {{ form }} {% if redirect_field_value %} <input type="hidden" … -
My Simple React / Django Application Being Served From the backend cannot Find index.html, why am I getting a 500 error When Deploying?
My react/django app works on my localhost. The backend is serving the files. However, in production, I am getting this error `"Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: /opt/venv/lib/python3.8/site-packages/django/template/loader.py, line 47, in select_template Raised during: django.views.generic.base.TemplateView Python Executable: /opt/venv/bin/python Python Version: 3.8.16 Using engine django: django.template.loaders.filesystem.Loader: /app/frontend/build/index.html (Source does not exist)" ` Here is what is in my settings.py file "BASE_DIR = Path(file).resolve().parent.parent BACKEND_DIR = BASE_DIR # rename variable for clarity FRONTEND_DIR = BASE_DIR.parent / 'frontend'" `"TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [FRONTEND_DIR / 'build'], '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', ], }, }, ] STATICFILES_DIRS = [FRONTEND_DIR / 'build' / 'static'] STATICFILES_STORAGE = ( 'whitenoise.storage.CompressedManifestStaticFilesStorage') STATIC_ROOT = BACKEND_DIR / 'static' STATIC_URL = 'static/' WHITENOISE_ROOT = FRONTEND_DIR / 'build' / 'root' " Here is the view "from django.views.generic import TemplateView catchall = TemplateView.as_view(template_name='index.html') " Here is the url "from django.urls import path, re_path from . import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'', views.catchall), ] " How can I get Django to recognize the index.html? I tried everything I know how when deploying to railway and isolated the error. The way to the index.html file is root - frontend - build - index.html -
django Contact Form data not being saved
I am building a website for my brother and it needs a contact form, the HTML template had one pre built so i custom build a model form based off what was included in the template, so far it all works, except when you press submit on the website the data isnt saved to the database and isnt viewable in admin. but the template renders out all fine and the page redirects when you press submit, it also wont allow you to submit if the required fields arent there or contain invalid entries. index.html <form id="contact" action="" method="post"> {% csrf_token %} {{ form.as_p }} <div class="row"> <div class="col-md-12"> <h2>Contact me</h2> </div> <div class="col-md-6"> <fieldset> <input name="name" type="text" class="form-control" id="name" placeholder="Your name..." required=""> </fieldset> </div> <div class="col-md-6"> <fieldset> <input name="email" type="text" class="form-control" id="email" placeholder="Your email..." required=""> </fieldset> </div> <div class="col-md-12"> <fieldset> <textarea name="message" rows="6" class="form-control" id="message" placeholder="Your message..." required=""></textarea> </fieldset> </div> <div class="col-md-12"> <fieldset> <button type="submit" id="form-submit" class="button">Send Now</button> </fieldset> </div> </form> forms.py from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'message'] views.py from django.shortcuts import render from .forms import ContactForm # Create your views here. def home(request): return render(request, … -
'AttributeError: 'User' object has no attribute 'phone'' in Django Rest Framework
I understand that the default user model does not have a field named 'phone'. However, I am trying to retrieve all the registered users from the default user model, along with additional fields such as 'phone', 'phone_verified', 'email_verified', 'phone_code', and 'email_code' from a custom UserProfile model which inherits from the default user model using a OneToOneField. To achieve this, I have created a UserSerializer which serializes the default User model, and a nested UserProfileSerializer that utilizes the UserSerializer class and the UserProfile model. My goal is to have the nested UserProfileSerializer serialize data from both the user model and the custom UserProfile model. Unfortunately, I am encountering the following error: AttributeError at /register/ - Got AttributeError when attempting to get a value for field 'user' on serializer 'UserProfileSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'User' instance. The original exception text was: 'User' object has no attribute 'user'. models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=20) phone_verified = models.BooleanField(default=False) email_verified = models.BooleanField(default=False) phone_code = models.CharField(max_length=10) email_code = models.CharField(max_length=10) serializer.py: from django.core import validators from rest_framework import … -
__str__ returned non-string (type Bottle), why?
I have a Django project with the following models: class Ingredient(models.Model): drink = models.ForeignKey(DrinkRecipe, on_delete=models.CASCADE) ingredient_rhum = models.ForeignKey(Bottle, on_delete=models.CASCADE, null=True, blank=True) ingredient_name = models.CharField(max_length=255, blank=True) ingredient_amount = models.DecimalField(decimal_places=1,max_digits=5, validators=[MinValueValidator(0.01)]) def __str__(self): if self.ingredient_rhum: return self.ingredient_rhum return self.ingredient_name def get_absolute_url(self): return self.drink.get_absolute_url() and: class Bottle(models.Model): bottle_name = models.CharField(max_length=255, blank=False, verbose_name='Name') bottle_slug = models.SlugField(unique=True, blank=True, null=True) bottle_info = HTMLField(blank=False, verbose_name='Information about the bottle') bottle_tastingnotes_text = HTMLField(verbose_name='Tasting description', blank=False) bottle_tasting_notes = HTMLField(verbose_name='Tasting notes', blank=False) bottle_tastingnotes_finish = HTMLField(verbose_name='Finish',blank=False) bottle_image = models.ImageField(upload_to=image_upload_handler) sorting_number = models.IntegerField() bottle_abv = models.DecimalField(max_digits=3,decimal_places=1, verbose_name='ABV', validators=[MinValueValidator(0.01)]) img_location = 'bottles' def __str__(self): return self.bottle_name class Meta: ordering = ['sorting_number', 'bottle_name'] def get_bottle_link(self): return reverse('rhumSite:drinkBottle',kwargs={'tag':self.bottle_name} ) def get_edit_link(self): return reverse('rhumSite:edit_bottle',kwargs={'id':self.id}) def save(self, *args, **kwargs): abv = str(self.bottle_abv) if not self.id: # Newly created object, so set slug self.bottle_slug = slugify(self.bottle_name + abv) super(Bottle, self).save(*args, **kwargs) It all works fine when I use them in my CreateView with an inline-modelset-factory. However: when I try to add an ingredient in my Admin or try to delete an ingredient or an other object that has a ForeignKey with the Bottle model I get the following error: __str__ returned non-string (type Bottle) What did I do wrong and how do I fix it? -
getting a bad request error when trying to send an axios post request to a django server
Im working with vuejs3 and django rest frame. i used apiView in ,y django view, here is my view class BlogPostView(APIView): def get(self, request, format=None): blogpost=BlogPost.objects.all().order_by('?') serializer=BlogPostSerializer(blogpost, many=True) return Response(serializer.data) def post(self, request, format=None): serializer=BlogPostSerializer(data=request.data) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=statis.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and here is my axios code axios({ url:'http://127.0.0.1:8000/blogs/', method:'post', data:{ title, content:ckData.value.data, category:'programmimg', status:1, publisher:1 }, transformRequest(data){ data=JSON.stringify(data) return data }, headers:{ 'Content-Type':'application/json', 'Authorization':'JWT fefege...', 'X-Requested-With': 'XMLHttpRequest', } }).then((response)=>{ }) getting a 400, bad request when the request is sent to the server it seems the serializer isnt valid, but im using modelsSerializer, all required field are filled with valid type anyone with a solution, i ll appreciate -
DRF not catch django signal exception
I have a model of IP addresses in django, but this model is fed by another one where the networks are stored, for example, if I add the network 10.0.0.0/24 with a signal I populate the IP addresses table from 10.0.0.1 to 10.0.0.255, for a validation issue I raise some exceptions in the signals and it works fine when I try to save with the shell, but when I use DRF I get an error 500 instead of the validationError. Does anyone know how I can make DRF return a BAD_REQUEST with my validationError message instead of return HTTP_500? -
How to deploy Django application through CPanel in production?
I have developed Django/python project with no frontend framework (React, Angular etc). As I've come to understand from the internet, there is significant difference in the behavior dev and production stages which I can't seem to put my finger on (Just going debug False seems too easy to be all that should be done). I'm coming across on the internet of all kinds of "configurations" and ideas on best practices regarding production deployment. My first question is - how is production different from deployment, gonna call it "modes", if someone could throw me a bone here (take into consideration, I've read all there is in the official documentation on the matter - still not getting it). What are the steps you, as a python developer, do when deploying your projects. Should I use gunicorn or daphne or something else and why would do that. So, I have deployed the project to a2hosting through the cpanel menu 'Setup Python App', the project's database im using is MySQL. I've configured with dotenv module for the secret key's, passwords, accounts etc. (sensitive data). I feel like its too good to be true, all I did was click on Cpanel's setup python app and … -
how to call image in react js from render cloud postgresql database api using axios
when i am not hosting the site and running the Django locally its was working fine but when i hosted through render cloud i cannot access my image everythings other is working fine but in image i am getting this error as GET https://django.onrender.com/media/media/carosel/skill.jpg 404 Can anyone please help me why is this not working. THis is my setting.py for Static and Media STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'my-app/build/static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' This is my model.py file to get image Image = models.ImageField(upload_to='media/carosel',blank=False) THis is my Carosel.jsx file import React ,{useEffect , useState ,useRef } from 'react' import { Box, Grid,CardContent ,CardActionArea,CardMedia, Typography, styled, List, ListItem, createStyles, Card, TextField, Link, Button, TextareaAutosize } from '@mui/material'; import {motion , useScroll,AnimatePresence } from 'framer-motion' import '../Style/app.css' import axios from 'axios' import CancelIcon from '@mui/icons-material/Cancel'; export default function Carosel({handleClose}) { const [post,setpost] = useState([]); const getload = async()=>{ const response = await axios.get('https://django.onrender.com/media/carosel'); console.log(response.data); console.log(post); setpost(response.data); console.log(post); } useEffect(()=>{ getload(); },[]) return ( <> <AnimatePresence mode='wait'> <Box component={motion.div} my={3} sx={{height:'50%',zIndex:'1',border:'0.1px solid black'}} className="mods" onClick={(e)=> e.stopPropagation()} > <Button size="small" onClick={handleClose} sx={{color:'black',border:'1px solid black',fontWeight:'bolder',backgroundColor:'crimson',borderRadius:'17px 17px 17px 17px',padding:'5px 5px',zIndex:'1'}}> <CancelIcon /> </Button> { post.map((elem)=>{ …