Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form submission not redirecting to success page and the post request is not being done
I'm encountering an issue with Django where form submission is not redirecting to the success page as expected and the data input its not happening . Here's a breakdown of the problem: I have a Django application where users can book rooms using a form. Upon successful submission of the form, the user should be redirected to a "booking success" page. However, after submitting the form, the page remains unchanged, and there's no redirection happening.Yes need authentication for book it . **this is my views.py ** `def book_room(request): if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): form.save_booking() return redirect('booking_success') else: form = BookingForm() return render(request, 'bookings/appbooking.html', {'form': form})` my urls `from . import views from django.urls import path urlpatterns = [ path('', views.index, name='bookings'), path('booking_success/', views.booking_success, name='booking_success'), path('book_room/', views.book_room, name='book_room'), ` -
Docker compose enter debug mode upon breakpoint while dropping stdout from web server
Have a question on using docker-compose when entering into debug mode by manually setting breakpoint(). This is my service and it has a /health which calls almost every 5s, and it prints out 200 status code to stdout. However, when using docker attach <container_id> to enter into the container, as it hits a breakpoint, it is interlaced with the (pdb) debugger. Is there a way to redirect these stdout from /health temporarily to not "bother" the debugger session? -
Displaying an image doesn't work Django python
So this is my views.py when I use atrakcjatest my images work, but when I try to use the filtered atrakcja(atrakcje_list) it doesnt work and only images dont work, the rest of variables are ok def map_view(request, trasa_id): trasa = get_object_or_404(Trasa, id_trasy=trasa_id) trasa_atrakcje = Trasa_a_atrakcja.objects.filter(id_trasy=trasa_id) atrakcje = Atrakcja.objects.filter(id_atrakcji__in=[ta.id_atrakcji for ta in trasa_atrakcje]) atrakcje_list = list(atrakcje.values('id_atrakcji', 'nazwa', 'kategoria_id', 'latitude', 'longitude', 'czas_zwiedzania', 'opis', 'miasto_id', 'cena', 'zdjecie_jpeg')) atrakcje_json = json.dumps(atrakcje_list) atrakcjatest = Atrakcja.objects.all() return render(request, 'map.html', {'atrakcje': atrakcje_json, 'trasa': trasa, 'atrakcje_list': atrakcje_list, 'atrakcjatest': atrakcjatest}) I dont understand this bug because when I use objects.all() everything works and also It's kinda strange that the only thing which doesnt work is Image, I tested the url in a tag and there is an empty string -
I want to deploy my django project on render but it show not build wheels for dlib
I want to deploy my django project which is face recognition for online transaction on render but it show ERROR: Could not build wheels for dlib, which is required to install pyproject.toml-based projects how could i resolve this ? i try install dilib in local server according to latest python version but notable to deploy please give me insights to reslove this problem -
Django Graphene GraphQL customize Error messages
In my Django app with Graphene for GraphQL, how do I intercept the Graphene GraphQL messages so I can sanitize the content? I tried creating a custom graphql view and a custom_execute function and using that in the urlpatterns endpoint definition: class CustomGraphQLView(GraphQLView): def execute_graphql_request(self, request, data, query, variables, operation_name, show_graphiql=False): document = parse(query) result = custom_execute(self.schema, document, root_value=request, variable_values=variables, operation_name=operation_name) return result def custom_execute(schema, document, root_value=None, variable_values=None, operation_name=None, context_value=None): # Execute the query try: result = execute( schema=schema, document=document, root_value=root_value, context_value=context_value, variable_values=variable_values, operation_name=operation_name ) if isinstance(result, ExecutionResult): if result.errors: modified_errors = [GraphQLError("Custom error handling message") for error in result.errors] result.errors = modified_errors return result except Exception as e: return ExecutionResult(data=None, errors=[GraphQLError('test'), GraphQLError(str(e))]) urlpatterns = [ path('graphql', CustomGraphQLView.as_view(graphiql=not IS_PROD)), ] Inside the execute function in my custom_execute function, I get the error: "Expected <Schema instance> to be a GraphQL schema." I have verified that the schema object is of type <class 'graphene.types.schema.Schema'>. How do I fix this error. Is this even the recommended way to customize the error messages generated by graphql? -
Django View Not Returning 404 as Expected When Form is Submitted
I'm facing a strange issue with Django. I have set up a simple form in a template that submits to a view, but I'm not getting the expected 404 response. Instead, I'm being redirected to the URL http://localhost:8000/clear/ without seeing the 404 error. Here is my setup: Template: <form method="post" action="{% url 'clear_chat' %}"> {% csrf_token %} <button type="submit" class="btn btn-danger clear-button me-2"> Clear Chat </button> </form> View: from django.http import HttpResponse from django.contrib.auth.decorators import login_required @login_required def clear_chat(request): return HttpResponse("Invalid request method.", status=404) Urls: from django.urls import path from .views import clear_chat urlpatterns = [ path('clear/', clear_chat, name='clear_chat'), ] Instead of seeing the 404 response, I'm redirected to the URL http://localhost:8000/clear/ without any error message. I have no clue what is wrong with that code. -
Deploying Django AI on Heroku
I'm having trouble uploading my Django web app to Heroku due to the Slug Size limit. My web app includes an AI API that requires a torch dependency. This is the error: Compressing... remote: ! Compiled slug size: 700M is too large (max is 500M). remote: ! See: http://devcenter.heroku.com/articles/slug-size remote: remote: ! Push failed In the requirements.txt I have already forced to install only torch+cpu, but I can't reduce the Slug Size by 200M. How can I solve it? -
django bulk update with batch in multiple transactions
I've a certain code that updates bulk rows: from simple_history.utils import bulk_update_with_history from simple_history.tests.models import Poll from django.utils.timezone import now objs = Poll.objects.all() for obj in objs: obj.question = 'Duplicate Questions' bulk_update_with_history(objs, Poll, ['question'], batch_size=5000) Now data here can be very huge and sometimes thousands of rows to update. This caused the database in lock:relation state for about 2-3 minutes. On dissecting the bulk_update_with_history method which belonged to a simple-history package, the doc string states that: def bulk_update_with_history( objs, model, fields, batch_size=None, default_user=None, default_change_reason=None, default_date=None, manager=None, ): """ Bulk update the objects specified by objs while also bulk creating their history (all in one transaction). :param objs: List of objs of type model to be updated :param model: Model class that should be updated :param fields: The fields that are updated :param batch_size: Number of objects that should be updated in each batch So the theory is that this particular function wraps all batch updates in a single transaction which is what caused the db to lock state. I want to know how batch_size works in bulk_update. Django doc states that: The batch_size parameter controls how many objects are saved in a single query. The default is to update all … -
How to pass on the chopped details from URL in Django?
I have a project with the following urls.py. urlpatterns = [ path('category*/', include('student.urls')) // * could be replaced by a number ] In that project I then have an application student whose urls.py looks like this: urlpatterns = [ path('all/', views.all, name='all') ] So lets say when I type in the URL category1/all/ I get the list of all Category 1 students, but when I do category2/all/ I should be able to get the list of all Category 2 students. So by the time I reach all/ I have lost for which category I want to retrieve the list of all students. How can I still know in my students application which category students data should be retrieved? -
How to take data from HTML Inputs and use them in a form?
I am trying to get the user's login and password from the HTML template (from ) and use these inputs for processing. I want to use the inputs from the HTML template and not the usual Django forms, like: <label class="form-label">Username</label> {{ form.username }} <span>{{ form.errors.username }}</span> This is a part of HTML tamplate: <form method="post"> {% csrf_token %} <div class="mb-[22px]"> <input type="username" placeholder="Username" class="w-full px-5 py-3 text-base transition bg-transparent border rounded-md outline-none border-stroke dark:border-dark-3 text-body-color dark:text-dark-6 placeholder:text-dark-6 focus:border-primary dark:focus:border-primary focus-visible:shadow-none" /> </div> <div class="mb-[22px]"> <input type="password" placeholder="Password" class="w-full px-5 py-3 text-base transition bg-transparent border rounded-md outline-none border-stroke dark:border-dark-3 text-body-color dark:text-dark-6 placeholder:text-dark-6 focus:border-primary dark:focus:border-primary focus-visible:shadow-none" /> </div> This is the class from forms.py: class LoginForm(AuthenticationForm): username = CharField( max_length=50, min_length=3, required=True, widget=TextInput(attrs={"class": "form-control"}), ) password = CharField( required=True, widget=PasswordInput(attrs={"class": "form-control"}), ) class Meta: model = User fields = ("username", "password") How can I properly pair these code elements? -
Deleting resource of a django model with foreign key
I have following django models : class ModelA(models.Model) : # fld1, fld2 class ModelB(models.Model) : fld_a1 = models.ForeignKey(ModelA, related_name='modela_1') fld_a2 = models.ForeignKey(ModelA, related_name='modela_2') # other fields Now when I delete resource from ModelB, how to make sure that the corresponding foreignkey objects from ModelA are also deleted -
Celery executes tasks sequentially, one after another
I have a Django application that has large I/O-bound tasks. I use Celery to run these tasks in threads and manage the progress in the UI with a progress bar. Here's my configuration : Django version : 5.0.2 Celery version : 5.3.6 Redis version : Redis for Windows 5.0.14.1 (https://github.com/tporadowski/redis/releases) SERVER Windows Server 2016 (can't change that; I have data stored in an Access Database) Hosting app in IIS default AppPool Processor : 4 core RAM : 4 GB web.config configuration : <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python311\python.exe|C:\Python311\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <directoryBrowse enabled="true" /> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\Django-LIAL\WEBAPPLIAL" /> <add key="WSGI_HANDLER" value="WEBAPPLIAL.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="WEBAPPLIAL.settings" /> </appSettings> </configuration> Django wsgi configuration : from gevent import monkey monkey.patch_all() import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WEBAPPLIAL.settings') application = get_wsgi_application() Django celery configuration : #Celery setting CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' CELERY_TASK_ALWAYS_EAGER = False CELERY_TASK_TRACK_STARTED = True celery command line launched in git : $ celery -A WEBAPPLIAL worker -l info -P gevent *** what the celery command line do : *** -------------- celery@WIN-RHK2AHPNGJ1 v5.3.6 (emerald-rush) --- ***** ----- -- ******* ---- … -
How to fix CSRF TOKEN being overwritten with form data after submission failed in django?
I building a multitenants project using django-tenant and django-tenant-user but I am facing a weird issue where the CSRF TOKEN and email fields of my login form are being overwritten with the password data after a failed login attempt. Please view my relevate code snippets below: View def login_user(request): if request.user.is_authenticated: return redirect('core:index') if request.method != 'POST': form = LoginForm() return render(request, 'core/login.html', {'form': form}) form = LoginForm(request.POST) if not form.is_valid(): context = {"form": form} if not form.errors: messages.error(request, 'Invalid username or password') return render(request, 'core/login.html', context) user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password']) if user is None: messages.error(request, 'Invalid username or password.') return render(request, 'core/login.html', {'form': form}) messages.success(request, 'Login successful') login(request, user) return redirect('core:index') Form class LoginForm(forms.Form): username = forms.CharField(min_length=4, max_length=150) password = forms.CharField(min_length=4, max_length=128, widget=forms.PasswordInput) Template {% extends "_base.html" %} {% block title %} <title>TalwaPro HR Admin - Login </title> {% endblock title %} {% block content %} {% load tailwind_filters %} <div class="flex h-screen items-center justify-center"> <div class="card w-[90%] bg-base-200 shadow-xl justify-center md:w-[65%] lg:w-[40%]"> {% if messages %} <div class="toast toast-top toast-start"> <div class="alert alert-error"> {% for message in messages %} {{ message }} {% endfor %} </div> </div> {% endif %} <div class="card-body"> <h2 class="card-title text-accent justify-center">Sign In</h2> … -
Get User Information in Django
I have made a REST API using Django, and I have issues with retrieving a user's information by inserting a token. I am using the User model. So here is the view: `class getUserInfoView(APIView): #generics.RetrieveAPIView #authentication_classes = [authentication.TokenAuthentication] #authentication_classes = [jwt] #permission_classes = [permissions.IsAdminUser] #permission_classes = (AllowAny,) #queryset = User.objects.all() #serializer_class = UsersListSerializer#UserSerializer serializer_class = UserSerializer permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] def get(self, request): serializer = UserSerializer(data=request.user) user = request.user #return Response(UserSerializer(user).data) if serializer.is_valid(): user = jwt.get_user(token=serializer.validated_data['access_token']) if user: return Response({ 'id': user.id, 'username': user.username, 'email': user.email, }) return Response({'detail': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)` Here's the serializer: `class UserSerializer(serializers.Serializer): #username = serializers.CharField(required=True) acess_token = serializers.UUIDField() class Meta: model = User fields = ["id", "username", "email"]` Here's the url: path('api/me/', getUserInfoView.as_view(), name='Personal-Information') The problem here is that when I run the server, I get the following: enter image description here I understand that the issue is in the view, can anyone explain what I am doing wrong? Thank you. I tried various View objects as argument for the class, did not work. -
Custom view on admin main page
I want to show some information on the admin index.html, but I do not want to use context processors for this, but have my own view. So I tried like described in the docs and discussed here. My app is called virtual, so I did: in virtual/admin.py: class VirtualAdminSite(admin.AdminSite): index_template = "virtual/admin_index.html" def index(self, request, extra_context=None): extra_context = extra_context or {} return super().index(request, extra_context) admin_site = VirtualAdminSite(name="virtualAdminSite") in virtual/apps.py: class VirtualAdminConfig(AdminConfig): default_site = "virtual.admin.VirtualAdminSite" in project/settings.py INSTALLED_APPS = ["virtual.apps.VirtualConfig", "virtual.apps.VirtualAdminConfig", ...] I then run in to the error: ImportError: Module "virtual.admin" does not define a "VirtualAdminSite" attribute/class If I use "django.contrib.admin" instead of virtual.apps.VirtualAdminConfig everything works just fine. so two questions: why does this error happen, I feel I copied that straight from the docs? I assumed I could add some variables in the VirtualAdminSite extra_context and show them in the index template by using {{ variable_name }} - is this correct? -
Django View called by View won't render
I have 2 views: def matching(request: HttpRequest) -> HttpResponse: context = Transaction.objects.order_by("-transaction_date").all() if request.method == 'POST': evidence_data = to_json(request.body) return render(request, "evidence/matching.html", {"transactions": context, "evidence_data": evidence_data }) return render(request, "evidence/matching.html", {"transactions": context}) def evidence(request: HttpRequest) -> HttpResponse: if request.method == 'POST': data = to_json(request.body) if data: return matching(request) context = TransactionEvidence.objects.order_by("-uploaded_at").all() return render(request, "evidence/evidence.html", {"evidence": context}) After the first view gets a post request, I want the other view to render with the transaction data and the data from the evidence view. The view is called, and the data is there and what I would expect, but in the browser, nothing is happening. What am I missing? -
Why doesn't the django program keep an up-to-date log, but uwsgi does
I used uwsgi to start my project, and then I logged it in my uwsgi configuration, and then I logged it in my django project setup file, but I found out today that my django log only logged this morning from 9:00 to 10:00, and all subsequent logs were missing. But in it's in uwsgi log file, Why? my uwsgi.ini [uwsgi] socket=/root/ex/xjs/script/uwsgi.sock master=true chdir=/root/exam_new/xjy_data_analysis/ wsgi-file=/root/ex/xjs/xjs/wsgi.py home = /root/anaconda3/envs/xjs static-map = /static=/root/exam_new/xjy_data_analysis/static processes=6 worker=6 threads=2 max-requests=5000 thunder-lock=true enable-threads=true pidfile=/root/exam_new/xjy_data_analysis/script/uwsgi.pid vacuum = true auto-procname = true procname-prefix-spaced = xjy-data-new-analysis post-buffering=65536 touch-reload = /root/exam_new/xjy_data_analysis/examApp daemonize = /root/exam_new/xjy_data_analysis/script/uWSGI.log harakiri=3600 http-timeout=3600 socket-timeout=3600 chmod-socket = 660 buffer-size=220000000 ignore-sigpipe=true ignore-write-errors=true disable-write-exception=true uwsgi_send_timeout 1800; uwsgi_connect_timeout 1800; uwsgi_read_timeout 1800; my django settings.py INFO_LOG_DIR = os.path.join(BASE_DIR, 'dataAnalysisApp/logs/info') if not os.path.exists(INFO_LOG_DIR): os.makedirs(INFO_LOG_DIR) ERROR_LOG_DIR = os.path.join(BASE_DIR, 'dataAnalysisApp/logs/error') if not os.path.exists(ERROR_LOG_DIR): os.makedirs(ERROR_LOG_DIR) HOMEWORK_LOG_DIR = os.path.join(BASE_DIR, 'dataAnalysisApp/logs/homework') if not os.path.exists(HOMEWORK_LOG_DIR): os.makedirs(HOMEWORK_LOG_DIR) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s %(levelname)-8s [%(pathname)s:%(lineno)d] [%(funcName)s] [%(message)s]' } }, 'filters': { 'info_filter': { '()': MaxLevelFilter, 'level': logging.WARNING, } }, 'handlers': { 'console_handler': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'standard', }, 'info_handler': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'concurrent_log_handler.ConcurrentTimedRotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(INFO_LOG_DIR, 'info.log'), 'when': 'midnight', 'backupCount': 30, 'encoding': 'utf-8', 'filters': ['info_filter'], }, 'error_handler': … -
Saving instance of model prior to sending out response in Django
Is there a way to add a record to me DB BEFORE sending off a response? I just learned about Django Signals so I assume that might be a candidate. The reason why I'm asking this is because of an issue I am having using knox + drfpasswordless. This snippet is where the authentication token is returned. However, the token is not saved here. When I call AuthToken.create(), this will save the token to my database but it will cause .is_valid() to return False because my serializer (ModelSerializer) is based off of AuthToken which has digest has a primary key. class AuthTokenResponseSerializer(serializers.ModelSerializer): user_id = serializers.PrimaryKeyRelatedField( queryset=User.objects.all(), ) class Meta: model = AuthToken fields = ["digest", "token_key", "user_id", "created", "expiry"] The workaround I was thinking of is to create an instance of AuthToken and save if right before sending out a response. If it's not possible, I was considering forking the project ot modify the code -
Advice on using patch file in django for installed library
I am using rest_framework_simple_api_key in my production application on python version 3.9 . On running command python generate_fernet_keymanage.py as given in doc(djangorestframework-simple-apikey) i am getting File "C:\Users\DELL\anaconda3\lib\site-packages\rest_framework_simple_api_key\models.py", line 15, in <module> class AbstractAPIKeyManager(models.Manager): File "C:\Users\DELL\anaconda3\lib\site-packages\rest_framework_simple_api_key\models.py", line 16, in AbstractAPIKeyManager def get_api_key(self, pk: int | str): TypeError: unsupported operand type(s) for |: 'type' and 'type' On Searching I got reason is i am getting error is The error TypeError: unsupported operand type(s) for |: 'type' and 'type' is caused by the use of the int | str syntax for type hinting, which is only supported in Python 3.10 and later versions. I can't change my python version as it is in production so I came across solution monkey patching then i got this article https://medium.com/lemon-code/monkey-patch-f1de778d61d3 my monkey_patch.py file: def patch_get_api_key(): print("*********************************EXE****************************************") """ Monkey patch for AbstractAPIKeyManager.get_api_key method to replace the type hint. """ from typing import Union def patched_get_api_key(self, pk: Union[int, str]): try: print("Patched get_api_key method") return self.get(pk=pk) except self.model.DoesNotExist: return None print("Before import") import rest_framework_simple_api_key.models as models print("After import") models.AbstractAPIKeyManager.get_api_key = patched_get_api_key I added code in my apps.py file: # myapp/apps.py from django.apps import AppConfig class MyCustomAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'roomroot' def ready(self): """ Load monkey patching. """ … -
TypeError: 'class Meta' got invalid attribute(s): manager_inheritance_from_future in Django4.2
I got above error while running the makemiragtions command. So I delete/renamed the existing migration folder and rerun the makemirations command it's is migrated but when I run the migrate I got same error i.e., TypeError: 'class Meta' got invalid attribute(s): manager_inheritance_from_future. Here is my model class. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models class CountryList(models.Model): CHOICES =[(1, 'Active'), (0, 'Inactive')] id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=255) iso3_code = models.CharField(max_length=5, verbose_name="ISO Code 3", help_text="ISO code with 3 leaters") iso2_code = models.CharField(max_length=5, verbose_name="ISO Code 2", help_text="ISO code with 2 leaters") is_active = models.IntegerField(choices=CHOICES) def __str__(self) -> str: return self.name class Meta: managed = True db_table = 'Country_list' verbose_name = 'Country' verbose_name_plural = 'Countries' ordering = ['name','is_active'] Note: I migrated from Django2.2 to Django4.2 version. So please let me know any one have idea bout it. Here is my entire error Trackback: Operations to perform: Apply all migrations: admin, auth, careers, cms, contenttypes, emailsignup, fluent_contents, news, optionsquote, press, redirects, resource, retailfinder, sessions, sites Traceback (most recent call last): File "/Users/developemt/Documents/Repos/Djnago_axv/manage.py", line 10, in execute_from_command_line(sys.argv) File "/Users/developemt/Documents/Repos/Djnago_axv/.venv/lib/python3.9/site-packages/django/core/management/init.py", line 442, in execute_from_command_line utility.execute() File "/Users/developemt/Documents/Repos/Djnago_axv/.venv/lib/python3.9/site-packages/django/core/management/init.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/developemt/Documents/Repos/Djnago_axv/.venv/lib/python3.9/site-packages/django/core/management/base.py", line … -
Where to add css files within django project
I'm building a To Do list in Django by following a tutorial, I'm trying to make seperate CSS file instead of directly writing it within HTML file, However i'm recieving 404 error. Below is directory structure ├─ base/ │ ├─ templates/ │ │ └─ base/ │ │ ├─ login.html │ │ ├─ main.html │ │ ├─ register.html │ │ ├─ style.css │ │ ├─ task_confirm_delete.html │ │ ├─ task_form.html │ │ ├─ task_list.html │ │ └─ task.html │ ├─ __init__.py │ ├─ admin.py │ ├─ apps.py │ ├─ models.py │ ├─ tests.py │ ├─ urls.py │ └─ views.py ├─ simpletodo/ │ ├─ __init__.py │ ├─ asgi.py │ ├─ settings.py │ ├─ urls.py │ └─ wsgi.py ├─ venv/ ├─ db.sqlite3 └─ manage.py Below are files where I'm strying to include css file main.html <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>To Do List</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <!-- elements from other pages will go here --> {% block content %} {% endblock content %} </div> </body> task_list.html {% extends 'base/main.html' %} {% block content %} ** some code ** {% endblock content %} Only static i've declared is as below settings.py STATIC_URL = 'static/' Follow up - How … -
Django: how to create a unique instance of one model as a field in another model
I am trying to store an instance of an items model as a field in my users model using ForeignKey like so: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=255) items = models.ForeignKey('Item', on_delete=models.CASCADE) def __str__(self): return self.username class Item(models.Model): stats = models.JSONField(null=True) name = models.CharField(max_length=255) def __str__(self): return self.name However, it currently seems that every new user is sharing the same list of items when I check my Django admin panel (essentially, there currently exists only one Items instance that is shared by every user). Instead, my goal is to have each user have their own list of items, unrelated to other users' list. Is there a way to make each user have a field in their account that is a unique instance of the Items model? -
Why will my Django middleware redirect googlebot instead of directly allowing it?
class BlockDirectAPIAccessMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): protected_paths = ['/api/socialinfo', '/api/crypto-data'] if any(request.path.startswith(path) for path in protected_paths): googlebot_user_agents = [ "Googlebot", "Googlebot-Image", "Googlebot-News", "Googlebot-Video", "Storebot-Google", "Google-InspectionTool", "GoogleOther", "Google-Extended" ] # Check for Googlebot (allow access) user_agent = request.META.get('HTTP_USER_AGENT', '').lower() # Convert to lowercase for case-insensitive matching if any(ua.lower() in user_agent for ua in googlebot_user_agents): return self.get_response(request) # Allow requests from your own domain (optional, but good practice) referer = request.META.get('HTTP_REFERER', '') if 'mysite.com' in referer: return self.get_response(request) # Allow local development (if needed) if 'localhost' in referer or '127.0.0.1' in referer: return self.get_response(request) # Block other direct access return HttpResponseForbidden('Access denied.') # Allow access to non-protected paths return self.get_response(request) I am testing to let googlebot access the API but i get a 301 response HTTP/1.1 301 Moved Permanently Date: Thu, 16 May 2024 19:46:45 GMT Server: Apache/2.4.29 (Ubuntu) Strict-Transport-Security: max-age=63072000; includeSubdomains X-Frame-Options: DENY X-Content-Type-Options: nosniff Location: /api/socialinfo/?beginRange=0&endRange=19 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Content-Type: text/html; charset=utf-8 -
Issue connecting MySQL to Django
My Django project will not migrate the changes I have made to the settings.py I get this error (1045, "Access denied for user 'root'@'localhost' (using password: NO)") I installed and setup a MySQL created a database connected all the information to my settings.py quadruple-checked to ensure they were correct. I have tried refreshing the server, granting all privileges to localhost, changing localhost to 127.0.0.1, and ran "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mypassword'; FLUSH PRIVILEGES;". I am open to any ideas. Django version: 5.0.4 MySQL version: 8.4 DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "aquadexdb", "USER": "root", "Password":os.environ.get("MySqlPassword"), #tried the raw password as well "HOST": "localhost", "PORT": "3306", } } -
Django with nginx & uwsgi: incomplete file response
Hello i have a django app and i recently added nginx & uwsgi on it. I have an endpoint that response with a file (xlsx). Before doing the changes this endpoint worked fine, but after the changes, the endpoint only gave the first 74 characters bytes of my file, causing a corrupted excel error. This is my django code for the response: with NamedTemporaryFile(delete=True) as temp_file: temp_file.write(response.content) temp_file.flush() return StreamingHttpResponse( open(temp_file.name, "rb"), headers=response.headers, status=response.status_code, ) I tried using FileResponse also and the same happened. This is my nginx file: server { listen 8000; server_name localhost; charset utf-8; add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; client_body_buffer_size 32k; client_header_buffer_size 8k; large_client_header_buffers 8 64k; location / { include uwsgi_params; uwsgi_pass unix:///var/uwsgi/my_api.sock; uwsgi_buffer_size 32k; uwsgi_buffers 16 16k; uwsgi_busy_buffers_size 32k; uwsgi_read_timeout 300; uwsgi_send_timeout 300; uwsgi_connect_timeout 300; uwsgi_ignore_client_abort on; }} What configuration do i need to do to solve this problem?