Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReactDOM not rendering in Django template
I am trying to integrate a React frontend into my Django project. I'm using Babel (ver 7.22) and webpack to bundle everything into index-bundle.js Currently, the index-bundle.js file is being fetched (according to the GET requests in terminal), but nothing is being loaded into the actual Django template. When I inspect the page, there is nothing from the js file being loaded. Everything was working until I tried adding in react components, but now nothing is working at all. File structure: -myproject --frontend ---index.js ---App.js --static ---css ---js ---index-bundle.js --templates my idex.js is literally just ReactDOM.render(<h1>help</h1>, document.getElementById("root")) I've already ensured that the template is loading the index-bundle.js file and has <div id="root"></div> -
Django unable to load css and icons from nextjs project
The problem: django is unable to load css, svgs and other files from nextjs project here is the error: Not Found: /_next/static/css/app/layout.css Not Found: /vercel.svg [28/Jul/2023 16:31:55] "GET /_next/static/css/app/layout.css?v=1690542114858 HTTP/1.1" 404 2541 Not Found: /_next/static/css/app/page.css [28/Jul/2023 16:31:55] "GET /vercel.svg HTTP/1.1" 404 2462 [28/Jul/2023 16:31:55] "GET /_next/static/css/app/page.css?v=1690542114859 HTTP/1.1" 404 2535 Not Found: /_next/static/chunks/main-app.js [28/Jul/2023 16:31:55] "GET /_next/static/chunks/main-app.js HTTP/1.1" 404 2525 Not Found: /next.svg Not Found: /_next/static/chunks/webpack.js [28/Jul/2023 16:31:55] "GET /next.svg HTTP/1.1" 404 2456 [28/Jul/2023 16:31:55] "GET /_next/static/chunks/webpack.js HTTP/1.1" 404 2522 Not Found: /_next/static/chunks/webpack.js [28/Jul/2023 16:32:21] "GET /_next/static/chunks/webpack.js HTTP/1.1" 404 2522 So, i was trying to integrate django with nextjs, and after trying everything i could, there is one problem remaining. django being unable to load css, svgs and other files from nextjs project. here's the code: project.urls.py """ URL configuration for django_with_nextjs project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a … -
Where is my blocking code? I do not receive WebSocket message - Django Channels
So I have setup a simple web app with Django Channels, that handles some WebSocket connections. It works almost perfect, however it does not receive messages, after I send messages initiated by another connection. This is my consumers: class CPConsumer(AsyncWebsocketConsumer): async def connect(self): self.cp_id = self.scope["url_route"]["kwargs"]["cp_id"] self.cp = charge_point(self.cp_id, self) await self.channel_layer.group_add(self.cp_id, self.channel_name) await self.accept() async def disconnect(self, _): await self.channel_layer.group_discard(self.cp_id, self.channel_name) async def receive(self, text_data): print(f"CP {self.cp_id} sent: {text_data}") await self.cp.route_message(text_data) async def get_config(self, _): print(f"CP {self.cp_id} updates firmware") await self.cp.call(call.GetConfigurationPayload()) print(f"CP {self.cp_id} sent response") class CPUserConsumer(AsyncWebsocketConsumer): async def connect(self): self.cp_id = self.scope["url_route"]["kwargs"]["cp_id"] await self.accept() async def disconnect(self, _): pass async def receive(self, text_data): print(f"User {self.cp_id} sent: {text_data}") await self.channel_layer.group_send(self.cp_id, {"type": "get.config"}) The CPConsumer isolated works perfect. It receives the messages, and routes them through the charge_point class. The charge_point object returns a message (it calls the consumers send method), and it is received by the client. So far so good. Now I want the CPUserConsumer to initiate a message to the connection in the CPConsumer. The charge_point object needs to handle sending that messages. So when the CPUserConsumer client sends a message, I can se that it is forward to the get_config method in the CPConsumer. The first … -
FullResultSet error during migration with mssql (sql server)
I am trying to connect a SQL Server database with Django. But when I do "migration", I have this error : File "...\Python311\Lib\site-packages\django\db\models\sql\where.py", line 174, in as_sql raise FullResultSet django.core.exceptions.FullResultSet My tables are created in database but when I want to do another migration or make migration, I have this error. I am using pyodbc and mssql-django packages settings.py : DATABASES = { 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_HEALTH_CHECKS': False, 'CONN_MAX_AGE': 0, 'ENGINE': 'sql_server.pyodbc', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': '***', 'PORT': '***', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', "setdecoding": [ {"sqltype": pyodbc.SQL_CHAR, "encoding": 'utf-8'}, {"sqltype": pyodbc.SQL_WCHAR, "encoding": 'utf-8'}], "setencoding": [ {"encoding": "utf-8"}], }, 'TIME_ZONE': None, } When I drop django.migrations table in the database, I no longer have the error for 'makemigration' but there is the "table already exists" error. This recreates the 'django.migrations' table and the error appears again. -
TemplateDoesNotExist at /post/3
I have a template that should show the details of a post when you request it, but when you request it, there is a TemplateDoesNotExist error in /post/3. It shows me, but the rest of the templates are working correctly except for this one I feel that somewhere I should have used ., but instead I used / or vice versa models.py: from django.db import models from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ManyToManyField(Category) title = models.CharField(max_length=100) body = models.TextField() img = models.ImageField(upload_to='img/post') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.title} - {self.body[:30]}..." urls.py: from django.urls import path from . import views urlpatterns = [ path('post/<int:pk>', views.detalis, name='post') ] urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('home_app.urls')), path('',include('account.urls')), path('',include('blog.urls')), ] urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_URL) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_URL) views.py: from django.shortcuts import render from .models import Post def detalis(request, pk): post = Post.objects.get(id=pk) return render(request, 'blog/post-detalis.html', {'post': post}) setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], … -
Django: GET request is working correctly, but sending the data in the POST request is not working
I sent a POST to this url http://127.0.0.1:8000/user_ques_management/add_favorite_question/ again with this JSON body: { "idname": "aallen", "question_id": 201 } Got response: { "error": "User not found." } And also got this in the terminal: Received POST data: <QueryDict: {}> Received idname: None Not Found: /user_ques_management/add_favorite_question/ But when I sent a GET request with the same users user id to this url http://127.0.0.1:8000/user_ques_management/favorite_read_questions/3486/: I got successful response: { "user_id": 3486, "display_name": "Dustin Rodriguez", "favorite_questions": [], "read_questions": [] } I see the user information is there in the Database too. Here is my model for UserProfile: class UserProfile(models.Model): idname = models.CharField(max_length=250, unique=True) display_name = models.CharField(max_length=250) email = models.EmailField() phone = models.CharField(max_length=20) def __str__(self): return self.display_name Views.py for both of the urls: View to Insert Favorite Question for a User @csrf_exempt def add_favorite_question(request): if request.method == 'POST': print("Received POST data:", request.POST) idname = request.POST.get('idname') # Use 'idname' instead of 'user_id' question_id = request.POST.get('question_id') print("Received idname:", idname) # Print the received idname try: user = UserProfile.objects.get(idname=idname) question = Question.objects.get(id=question_id) FavoriteQuestion.objects.create(user_id=user, question_id=question) return JsonResponse({'message': 'Favorite question added successfully.'}) except UserProfile.DoesNotExist: return JsonResponse({'error': 'User not found.'}, status=404) except Question.DoesNotExist: return JsonResponse({'error': 'Question not found.'}, status=404) View to Retrieve Favorite and Read Questions for a User def … -
How add to ajax request additional GET params in django-ajax-select?
I need sent parametr region with ajax request in select. Select sending ajax without additional parameter `@register('address') class TagsLookup(LookupChannel): model = Address def get_query(self, q, request): **region = request.GET.get('region')** region_null = '__'.join([region, 'isnull']) return list(self.model.objects .filter(**{region_null: False}) .exclude(**{f'{region}': ''}) .exclude(**{f'{region}': ' '}) .order_by(f'{region}') .values_list(f'{region}', flat=True).distinct()) def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.city` Send region GET parametw with django-ajax-select request. Their documentation says the following: django-ajax-select documentation -
Django GraphQL subscription returns 400 Bad Request
I have a django v4.2.3 backend. Since graphene doesn't natively support subscriptions, I am using DjangoChannelsGraphqlWs (1.0.0rc6 pre-release version, since I need it to support my version of graphene). I have copy-pasted the default subscription given in the tutorial: class MySubscription(channels_graphql_ws.Subscription): notification_queue_limit = 64 event = graphene.String() class Arguments: arg1 = graphene.String() arg2 = graphene.String() @staticmethod def subscribe(root, info, arg1, arg2): return ["group42"] @staticmethod def publish(payload, info, arg1, arg2): """Called to notify the client.""" return MySubscription(event="Something has happened!") class Subscription(graphene.ObjectType): my_subscription = MySubscription.Field() defining the schema, like usual: schema = graphene.Schema(query=Queries, mutation=Mutations, subscription=Subscription) with a default consumer given in the tutorial class MyGraphqlWsConsumer(channels_graphql_ws.GraphqlWsConsumer): schema = schema async def on_connect(self, payload): print("New client connected!") This is the routing I used: urls.py urlpatterns = [ path("graphql/", csrf_exempt(GraphQLView.as_view(schema=schema, pretty=True, graphiql=True))) ] asgi.py application = channels.routing.ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": channels.routing.URLRouter([ django.urls.path("graphql/", MyGraphqlWsConsumer.as_asgi()), ]) }) I then tried to test my subscription using Apollo, Graphql Playground, etc. and always run into a similar error message: "Could not connect to websocket endpoint wss://paris2022.fr/graphql. Please check if the endpoint url is correct." Anyone has any idea what this can be? -
How to increase max redis channel layer load?
My websocket keeps disconnecting if I run a more resource heavy process. The websocket consumer processes a file and checks if it is in the correct format and returns and a status update, eg "Correct format", "Missing columns", etc. If I delete 20% of the rows from a file that caused the websocket to disconnect it works. I managed to narrow it down to around 500Kb is where the limit is. And also other consumers work too. CHANNELS: The issue occured when I changed from the dev InMemoryChannelLayer to RedisChannelLayer so thats why I think that the error is somewhere in that area and not with the specific consumer or process. The channel layers config is pretty simple, just the basic Redis example fromt the docs: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(os.environ.get("REDIS_HOST"), 6379)], }, }, } I tried setting stuff like capacity, expiry, group_expiry, channel_capacity but nothing worked.\ REDIS: The redis server is running, if i do redis-cli ping it returns PONG. Configs: maxmemory: 0 tcp-keepalive: 300 maxclients: 10000 timeout: 0 ERROR: There isn't too much information in the daphne logs. I get this message: Jul 28 07:31:29 googleds-server daphne[734093]: File "/home/atti/googleds/ds/lib/python3.8/site-packages/redis/asyncio/client.py", line 539, in … -
Packaged django apps installed from Pypi on new django project doesnt show the apps folders and files
In a former django project i have packaged an app for reusing it later in another django project. The app was packaged in both formats, source (tar.gz) and wheel and uploaded to Test Pypi. Then I have installed this app in a new project. Though the functionality of the app works... tested in the dev server, its files and folders are not shown in the VS Code editor, I would like to have them for editing purposes. Thanks in advance for help Everything is already explained -
in ajax get a value upon clicking a button but it is in a loop
$(document).ready(function() { $(".actdeact").on({ click: function() { var id = $('.getfromhere').text(); alert(id); {% for x in mylist %} <span class="getfromhere">{{x.id}}</span> <span class="btn btn-info actdeact">Deactivate</span> {% endfor %}` ` If I write .text() I get the whole series of values of id. If I write .html() I only get the first one I want that upon clicking the button, only the value that corresponds to the row clicked is sent to var id in the ajax code I want to get just the value that corresponds to the row clicked, not the whole of the values of the loop. -
The current path, **/POST, didn’t match any of these
I have a login page that has an auth form, 2 values, after validation, redirect it with these 2 parameters, but i get an error, what did i miss? The Views def LoginPage(request): if request.method == "POST": ordernr = request.POST.get('bestellnummer') email = request.POST.get('email') try: ...."validation shopify api" else: return redirect(f'login/{ordernr}/{email}/') the urls app urlpatterns = [ path('login/', views.LoginPage, name="login"), path('login/<str:pk>/<str:dk>/', views.OrderPage, name="order"), ] the from {% extends 'main.html' %} {% block content %} <div> <form action="POST" action="">{% csrf_token %} <div> <label for="bestellnummer">Ihre Bestellnummer</label> <input type="text" name="bestellnummer" id="bestellnummer" placeholder="Ihre Bestellnummer..."> </div> <div> <label for="email">Ihre Bestell E-Mail</label> <input type="email" name="email" id="email" placeholder="Ihre E-Mail..."> </div> <input type="submit" value="Login"> </form> </div> {% endblock content %} Page not found (404) your text Request Method: GET Request URL: http://127.0.0.1:8000/login/POST?csrfmiddlewaretoken=token123&bestellnummer=1337&email=somefiller@mail.com Using the URLconf defined in retourenportal.urls, Django tried these URL patterns, in this order: admin/ login/ [name='login'] login/str:pk/str:email/ [name='order'] The current path, login/POST, didn’t match any of these. -
Create HTTP response errors and timeouts for testing? [closed]
I suspect a counter outside scope could be used to do this. Does anyone know if there is a particular convention or interceptor to do the same? I’ll be using Flask or Django frameworks. -
Test a model property in django using Pytest
I want to test the output of a model property in django using pytest[pytest-django]. models.py: class TravelFriend(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="travel_friends") name = models.CharField(max_length=100) birthdate = models.DateField() def __str__(self): return self.name @property def age(self): days_in_year = 365.2425 age = int((date.today() - self.birthdate).days / days_in_year) if age >= 18: return "18+" else: return age basically the property return the age in years or the string '18+' if the age is more than 18 test_models.py: class TestTravelFriend: def test_travelfriend(self): """The family member is connected to a user and have valid attributes""" travel_friend = TravelFriendFactory() assert travel_friend is not None assert str(travel_friend) == travel_friend.name assert travel_friend.user is not None assert travel_friend.name is not None assert travel_friend.birthdate is not None assert travel_friend.age is not None factories.py: class TravelFriendFactory(factory.django.DjangoModelFactory): class Meta: model = "accounts.TravelFriend" user = factory.SubFactory("accounts.tests.factories.CustomUserFactory") birthdate = factory.Faker( "date_of_birth", maximum_age=25, ) I want to test that the output of the property is correct but if i put an if statement in the test like this year = -int(travel_friend.birthdate.year - date.today().year) if year < 18: assert travel_friend.age == year else: assert travel_friend.age == "18+" but in order to have 100% coverage I need to test this last part of code which I don't … -
how to create a server-side datatable that displays my data from by database
i need the views and the url and the js i tried alot but didnt work the data is displayed but the datatable stops working this is for my views def get_data_for_datatable(request): employees = Users.objects.all() data = [] for employee in employees: data.append({ "Name": employee.Name, "Gender": employee.Gender, "Email": employee.Email, "Department": employee.Department, "Salary": employee.Salary, }) return JsonResponse({ "data": data, }) this is for my js what s the problem $(document).ready(function() { $("#example").DataTable({ "ajax": "json/", "columns": [ {"data": "Name"}, {"data": "Gender"}, {"data": "Email"}, {"data": "Department"}, {"data": "Salary"}, ], processing: true, serverSide:true, paging: true, pageLength: 10, lengthChange: true, autoWidth: true, searching: true, bInfo: true, bSort: true, }) }) -
Adding fields to ModelForm programatically not showing in django admin
I have a usecase where I want to add fields to a modelform in django admin, but when trying to add them in the __init__function like this: class PackageFileInlineForm(forms.ModelForm): class Meta: model = File fields = '__all__' def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.fields['test'] = forms.CharField(max_length=100) Nothing shows up in the form. However if I do the form like this: class PackageFileInlineForm(forms.ModelForm): test = forms.CharField(max_length=100) class Meta: model = File fields = '__all__' Why does the init version not work? -
Django Multiple User's Authentication, SignUp Serializer and Views
I'm practicing creating multiple user types of authentication (in this scenario, Client and Driver like Uber) along with JWT. Currently, I am trying to write the SignUp Serializer for each corresponding user type (or if there is any more elegant way to do this), after signing up, I would love the user to have a Token. Please have a look at my code and teach me how or what could I do. This is my models from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): email = models.EmailField(unique=True) # vars to check whether user is client or driver is_client = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) class Client(models.Model): is_staff = False user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username class Driver(models.Model): is_staff = False user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username My serializers.py (kinda messy) from rest_framework import serializers from base.models import User, Customer, Technician from rest_framework_simplejwt.tokens import RefreshToken # Serialize data from db class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'username', 'email', 'name', 'isAdmin'] def get__id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def … -
KeyError 'django' occured after adding "rest_framework" to settings.py
I'm working on a django project and trying to use rest_framework. I'm running the project through docker desktop engine. Everything is fine until I add "rest_framework" to my project's settings.py in INSTALLED_APPS. I'm getting errors as below: 2023-07-28 15:08:59 Traceback (most recent call last): 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/template/utils.py", line 66, in __getitem__ 2023-07-28 15:08:59 return self._engines[alias] 2023-07-28 15:08:59 ~~~~~~~~~~~~~^^^^^^^ 2023-07-28 15:08:59 KeyError: 'django' 2023-07-28 15:08:59 2023-07-28 15:08:59 During handling of the above exception, another exception occurred: 2023-07-28 15:08:59 2023-07-28 15:08:59 Traceback (most recent call last): 2023-07-28 15:08:59 File "/code/manage.py", line 15, in <module> 2023-07-28 15:08:59 execute_from_command_line(sys.argv) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line 2023-07-28 15:08:59 utility.execute() 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 413, in execute 2023-07-28 15:08:59 self.fetch_command(subcommand).run_from_argv(self.argv) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 354, in run_from_argv 2023-07-28 15:08:59 self.execute(*args, **cmd_options) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 61, in execute 2023-07-28 15:08:59 super().execute(*args, **options) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 398, in execute 2023-07-28 15:08:59 output = self.handle(*args, **options) 2023-07-28 15:08:59 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 96, in handle 2023-07-28 15:08:59 self.run(**options) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 103, in run 2023-07-28 15:08:59 autoreload.run_with_reloader(self.inner_run, **options) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 637, in run_with_reloader 2023-07-28 15:08:59 start_django(reloader, main_func, *args, **kwargs) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", … -
Django IntegrityError: duplicate key value violates unique constraint ... DETAIL: Key ... already exists
In a Django app with Postgres db i have a model named Block. It is used in other models as ForeignKey class Block(models.Model): name = TranslatedField(models.CharField(max_length=200),) color = models.IntegerField(choices=BLOCKCOLOR_CHOICES, null=True, blank=True) blocktype = models.CharField(max_length=20, choices=BLOCKTYPE_CHOICES, default="break") def save(self, *args, **kwargs): self.name = self.name.capitalize() return super().save(self, *args, **kwargs) def __str__(self): return f"{self.name} ({self.blocktype})" I use django-translated-fields to translate the name in 4 languages. These are the relevant lines in admin: class BlockAdmin(TranslatedFieldAdmin, admin.ModelAdmin): pass admin.site.register(Block, BlockAdmin) I can create a new instance of Block in the admin interface and also in the view. When I edit the model and try to save I get the above mentioned error. It happens in the admin interface and in the view as well. I can manually delete the model and create a new one, it gets a new id. It doesn't matter if the model is already bound via ForeignKey to another model or if it's standalone. Can somebody give me an advice? Thank you in advance! I have tried manipulating the id in the database, as a final solution I have also deleted the database completely. It happens again. I have a feeling that it has something to do with the django-translated-fields package. … -
ORA-00955 error with django migrate but no tables in Oracle database
I'm trying to deploy a Django application on an Apache webserver and Oracle DB. When I get to trying to create the database tables using manage.py migrate I get an error ORA-00955: name is already used by an existing object. It doesn't tell me what the object is (which is frustrating). Looking at the database I don't have any tables in my schema. I have run migrate more than once due to an earlier failure, but there's nothing there that I can see (I'm looking at the database in DBeaver). I've tried SELECT table_name FROM all_tables WHERE owner = 'MYUSERNAME'; but that doesn't return anything. Is there some way to find out what the blocking object is? Is there some way to make migrate force its way through? What am I missing that means I can't see the tables that the database sees? -
Dynamic class selection before object detection
I have a set of predefined classes to be detected in my object detection code. I want to choose the classes dynamically before the detection starts. Is this possible? I am selecting only the classes that I have trained the model for I have to detect only the selected classes -
Nginx is showing the default page instead of Django application (Ubuntu 22.04)
I am trying to host django project with ubuntu, gunicorn and postgresql, also I use docker for development. As I don't have an IP-address for server I am just trying to host to standard django localhost in order to practise with Nginx (I used the guidline on DigitalOcean) as I am new to it. I've already tried a lot, but my problem persists. Here is my Dockerfile: FROM python:3.11.1 SHELL ["/bin/bash", "-c"] ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONBUFFERED=1 EXPOSE 8000 WORKDIR /cycle_proj RUN pip install --upgrade pip RUN mkdir /cycle_proj/static && mkdir /cycle_proj/media RUN apt update && apt -qy install gcc libjpeg-dev libxslt-dev \ libpq-dev libmariadb-dev libmariadb-dev-compat gettext cron \ openssh-client flake8 python3-venv python3-dev locales \ postgresql postgresql-contrib nginx curl COPY . . COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt CMD ["gunicorn","-b","0.0.0.0:8001","core.wsgi:application"] Here is docker-compose: version: "3.9" services: # Django web: build: . volumes: - .:/cycle_proj - static_volume:/cycle_proj/static - media_volume:/cycle_proj/media ports: - '8000:8000' env_file: - web.env image: cycle_proj container_name: django_cycle_api command: > bash -c "./manage.py collectstatic --noinput && ./manage.py migrate && gunicorn -b 0.0.0.0:8000 core.wsgi:application" depends_on: - db # PostgreSQL db: image: postgres:14.1-alpine restart: always env_file: - web.env ports: - '5432:5432' volumes: - db:/var/lib/postgresql/data nginx: image: nginx depends_on: - web ports: … -
Django Python not redirecting to login page after clicking sign up button
This is my first Django project and I am trying to get users to be redirected to a login page after they fill out a sign up form and click on the sign up button; however, instead my sign up form just reloads and I am still in my signup.html page. I am not sure why this is happening and any help would be greatly appreciated.(note -idk whether this will be relevant or not- that my html files are in a templates folder, .js and .css files are in a static folder, both separate and at the same level as my app folder) (relevant) signup.html: <form class="form" action="{% url 'signup' %}" method="POST"> {% csrf_token %} <div class="form_button_container"> <button class ="form_button" type="submit">Sign Up</button> </div> <p class="form_text"> <a href="{% url 'login' %}">Already have an account? Log in</a> </p> views.py: def login(request): if request.method == "POST": email = request.POST["email"] password = request.POST["password1"] user = authenticate(email=email, password=password) if user is not None: login(request, user) return redirect('mainpg') else: return render(request, 'login.html', {"error": "Invalid username or password."}) return render(request, 'login.html') def signup(request): if request.method == "POST": try: username = request.POST['username'] except MultiValueDictKeyError as e: messages.error(request, 'Please enter a username.') return redirect('signup') name = request.POST['name'] email = … -
Django - How to improve performance when model contains a large JSONField?
I am working on trying to figure out how to enhance performance when filtering on a queryset that has a JSONField with large data (thousands of lines). Even when querying and returning an estimated 100 objects, the return is extremely slow. 10-20 seconds. I have come to realize that the issue is the JSONfield, and the fact that large datasets are being stored in this field. I was reading about Djangos .only() and .defer() methods, because I don't need any data in this JSONField, but the performance seems to be the exact same without using these methods. I am just looking for some guidance on how to improve some performance here. -
Getting NaN from pandas DataFrame to go into PostgreSQL via Django
Parsing CSV files that have lots of blanks in float fields which pandas is treating as NaN. Using Django as the backend, I'm trying to import these CSV files into PostgreSQL. The error I get when it goes to do this import is: [celery] The above exception was the direct cause of the following exception: [celery] [celery] Traceback (most recent call last): [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task [celery] R = retval = fun(*args, **kwargs) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ [celery] return self.run(*args, **kwargs) [celery] File "/app/src/surveys/tasks.py", line 156, in create_model [celery] create_db_table(model, df, db ) [celery] File "/app/src/surveys/tasks.py", line 132, in create_db_table [celery] cursor.execute(statement) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute [celery] return super().execute(sql, params) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute [celery] return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers [celery] return executor(sql, params, many, context) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute [celery] return self.cursor.execute(sql, params) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ [celery] raise dj_exc_value.with_traceback(traceback) from exc_value [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 83, in _execute [celery] return self.cursor.execute(sql) [celery] django.db.utils.ProgrammingError: column "nan" does not exist [celery] LINE 1: ...609000.0,609000.0,750000.0,750000.0,1200000.0,0.0,nan,nan,na... [celery] ^ I can resolve the error by doing something like …