Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError at /createad/ (1048, "Column 'user_id' cannot be null") in Django
I'm making a comic book resale site in django. There is an Ad model that allows you to create an ad for the sale. It has a user (Django User) foreign key. models.py class Ad(models.Model): ad_id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=False, blank=False) description = models.TextField(null=True, blank=True) forms.py class AdForm(forms.ModelForm): class Meta: model = Ad fields = ('title', 'description', 'publisher', 'author', 'pub_year', 'pub_type', 'price') views.py def create_ad(request): if request.method == 'POST': form = AdForm(request.POST) if form.is_valid(): form.save(commit=False) current_user = request.user form.user = current_user form.save() else: form = AdForm() return render(request, 'create_ad.html', {'form': form}) When I try to save the ad I get the following error: **IntegrityError at /createad/ (1048, "Column 'user_id' cannot be null")** I tried inserting via request.user and request.user.id, but it doesn't help. Please help me to solve this problem. -
Trouble Integrating `django-simple-history` with `django-modeltranslation` in Abstract Model
I'm working on a Django project where I'm trying to create an abstract model that provides subclassed models with history tracking using the django-simple-history package. Additionally, I need to integrate django-modeltranslation for translating certain fields. However, I'm encountering issues with the integration. Here's my BaseModel code: from uuid import uuid4 from django.db import models from simple_history.models import HistoricalRecords class BaseModel(models.Model): class Meta: abstract = True history = HistoricalRecords(inherit=True) id = models.UUIDField(primary_key=True, default=uuid4, editable=False) created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True) updated_at = models.DateTimeField(null=True, blank=True, auto_now=True) Now, I have a model TestModel that inherits from BaseModel: models.py class TestModel(BaseModel): text = models.CharField(max_length=100) un = models.IntegerField() new_text = models.CharField(max_length=100) And for translating fields in TestModel, I have the following translation setup: translation.py from modeltranslation.translator import register, TranslationOptions from test_app.models import TestDeleteModel @register(TestModel) class TestModelTranslationOptions(TranslationOptions): fields = ( 'text', 'new_text', ) However, the issue arises when django-simple-history doesn't recognize the translated fields like text_en, resulting in them not being added to the history model. It seems that this occurs because the translation fields are added after the simple history package registers the model and creates the history model. I attempted to register TestModel again with simple_history after the translation registration to address this: translation.py from … -
How to iterate a dict within a template that contains a key named items?
I have some fairly simple django template and part of it is iterating through some dict ( that originates from some parsed json files ) like: {% for k, v in d.items %} However my dict now contains an item called items, which because for the syntax of a.b django first tries to resolve it as a[b] before trying getattr(a,b) (and calling the result if its callable), will try to iterate through the value under that key instead of the dict. What would be a good way to resolve that? I know already I could write a filter that simply returns list(d.items()) but that seems wrong/wasteful to me. Are there some other possibilities to solve this problem? -
How to use websockets in drf project with react-frontend?
How to work with websockets in a split (backend/frontend) project? In a full Django project, I did it like this (1st answer): Dynamic updates in real time to a django template Now, the frontend is separate on React and the backend is on DRF. The frontend will be using socketio. How, in this case, should websockets be properly implemented in DRF? Should I still use channels? I thought that it could be done similar to the answer on Stack Overflow, where now the frontend is done in React instead of Django templates. But the frontend mentioned that endpoints are not needed, just events: For example, he will have something like socket.on("getTasks") and socket.on("addTask", task: {"new task"}). And I have no idea how to work with this All I've tried is the way from stackoverflow. -
Patch or update by search query axios
I have django restframework and control from javascript axios What I am doing is like this, axios.get(`http://localhost:8010/api/myusers/?my_id=${my_id}`).then((res)=>{ var id = res['data']['results'][0]['id']; axios.patch(`http://localhost:8010/api/myusers/${id}/`, { phone: 'nice phone', }).then((res)=>{ console.log("patch finish"); }) }) Fetch the id by my_id and patch the data. However I think it is a bit clumsy, it uses twice request. At first get the id by my_id and change data by id So, I would like to do this by one request. How can I make it ? I tried like this but 405 Method not allowd error axios.patch(`http://localhost:8010/api/myusers/?my_id=${my_id}`, { phone: 'nice phone2', }).then((res)=>{ console.log("patch finish"); }) -
Django RawSQL annotate field
How can i annotate field with RawSQL? sql_query = """ SELECT c.id, COALESCE(SUM((cm.temp_min + cm.temp_max) / 2 - %s), 0) AS gdd FROM agriculture_commune c LEFT JOIN agriculture_communemeteo cm ON c.id = cm.commune_id WHERE cm.date BETWEEN %s AND %s GROUP BY c.id """ communes = communes.raw(sql_query, [TBASE, start_date, end_date]) it working , if i try do like this communes.annotate(gdd=RawSQL(sql_query, [TBASE, start_date, end_date])) i got error "subquery must return only one column\nLINE 1: ...mmune" -
django-admin: The term 'django-admin' i
django-admin: The term 'django-admin' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. PS C:\Users\Sanskar\Desktop\django> i want to initialize django -
How can I persist Django session after a POST request?
I want to be upfront with you the project I'm working with is kind of a mess, so I'm just looking for solutions. I have a Django app (no DRF) and a CI4 app. I want authentication to persist across the two apps. Basically, the CI4 app is the main, and that's where the user authenticates. I want to use request. Session in the Django app to handle the authentication state. I made the CI4 app sends a POST request to the Django app, and create a request. Session upon a successful authentication. @csrf_exempt def login_view_endpoint(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = Utilisateur.checkuser(username, password) if user: if 'utilisateur' not in request.session: request.session['utilisateur'] = user.id print(request.session['utilisateur']) return HttpResponse('true') else: return HttpResponse('false') else: # If the request method is not POST, redirect to the login page return HttpResponse('false') But the issue is when I test the flow of what I had in mind, I get redirected to the "login_page" of my Django app (which I'm trying to remove), which means the session doesn't exist, but the authentication was a success because I got a true response in my CI4 app. Maybe my understanding of session is … -
Python Execution Script manager with Web Interface?
So I have a Python Django project which uses Celery as well as Flower To launch all the three processes I need to start them on three different terminals with the commands: python manage.py runserver 0.0.0.0:8080 celery -A Lab worker -l info --concurrency 3 celery --broker=redis://172.20.1.2:6379/0 flower --port=5566 I was looking for a simpler solution, some sort of graphic interface where I have all these three commands already registered and I have just to click "launch". If I want to kill the process, maybe a "stop" button would be cool as well I'm looking something like Portainer is for Docker I've seen Spotify has created something for amnage Python scripts called Luigi, but I'm not sure if it fits my needs -
Implementing Internationalization (i18n) in Django
How can I effectively utilize internationalization (i18n) in Django Metronic to make my web application accessible in multiple languages? I'm struggling to implement i18n in my Django project with the Metronic theme. Despite configuring settings and marking strings for translation, I'm facing issues with translations not reflecting correctly and language switching not working as expected. -
when ever i try to login using phone number,password and otp its keep rendering the ph number page or it throws an error
``from django.shortcuts import render, redirect from django.contrib.auth import authenticate ,login from .models import Profile from django.contrib.auth.models import User from .mixins import MessageHandler import random def Signup_page(request): if request.method == "POST": username = request.POST.get('username') email = request.POST.get('email') phone_number = request.POST.get('phone_number') password = request.POST.get('password') if User.objects.filter(email=email).exists(): return render(request, "sign_up.html", {'error': 'Email already in use'}) if Profile.objects.filter(phone_number=phone_number).exists(): return render(request, "sign_up.html", {'error': 'Phone number already in use'}) user = User.objects.create_user(username=username, email=email) user.set_password( password) user.save() profile = Profile.objects.create(user=user, phone_number=phone_number) profile.save() return redirect('/login/') return render(request, "sign_up.html") def Login_page(request): if request.method == "POST": phone_number = request.POST.get('phone_number') try: profile = Profile.objects.get(phone_number=phone_number) return redirect('/password/') except Profile.DoesNotExist: return render(request, "login.html", {'error': 'Phone number not found'}) return render(request, "login.html") def password_page(request): if request.method == "POST": password = request.POST.get('password') phone_number = request.POST.get('phone_number') user = Profile. objects.get(phone_number = phone_number, password = password) profile = Profile.objeects(user=user) if user is not None: profile.otp = random.randint(100000, 999999) profile.save() messagehandler = MessageHandler(profile.phone_number, profile.otp).send_otp_on_phone() return redirect(f'/otp/<uid>/{profile.uid}') else: print('password check failed') print("Rendering password.html") return render(request, 'password.html') def Otp_page(request , uid): if request.method == "POST": otp = request.POST.get('otp') profile = Profile.objects.get(uid=uid) if otp == profile.otp: login(request,profile.user) return redirect('/dashboard/') def Dashboard_page(request): return render(request, "dashboard.html") ` i want it can go the otp page and send the otp` -
Efficient way to process data for number of views with dates
I am looking for a more efficient way to implement the provided code, which retrieves the number of views for object within a date range (start_date and end_date). The current code achieves the expected result, transforming data into a dictionary structure with names and corresponding daily view counts. However, I believe there might be a more optimized approach. Here's the code snippet for reference: models.py class Ad(models.Model): ad_type = models.ForeignKey(to=AdType, on_delete=models.CASCADE, related_name="ad") name = models.CharField(max_length=256) image = models.ImageField(upload_to="ads") is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) class AdStat(models.Model): class StatType(models.TextChoices): VIEWS = "views", _("Views") CLICKS = "clicks", _("Clicks") ad = models.ForeignKey(to=Ad, on_delete=models.CASCADE, related_name="ad_stat") stat_type = models.CharField(max_length=10, choices=StatType.choices) created_at = models.DateTimeField(auto_now_add=True) views.py @staff_member_required def ads_number_of_views(request): start_date = request.GET.get("start_date") end_date = request.GET.get("end_date") ads = ( AdStat.objects.filter(ad__is_active=True, ad__ad_type__slug="desktop-hader") .select_related("ad") .values("ad__name", "created_at__date") .annotate(view_count=Count("id")) .order_by("created_at__date") ) if start_date and end_date: ads = ads.filter(created_at__gte=start_date, created_at__lte=end_date) elif start_date: ads = ads.filter(created_at__gte=start_date) elif end_date: ads = ads.filter(created_at__lte=end_date) ads_data = [] for item in ads: ad_name = item["ad__name"] date_str = str(item["created_at__date"]) count = item["view_count"] found = False for entry in ads_data: if entry["name"] == ad_name: entry["number_of_views"].append({"created_at": date_str, "count": count}) found = True break if not found: ads_data.append({"name": ad_name, "number_of_views": [{"created_at": date_str, "count": count}]}) return JsonResponse(ads, safe=False) Expected Output. The code successfully … -
cannot find django module
so im watching a tutorial in django, on my end i created a virtual environment but the python file cant seem to find the django modules, steps i did: open folder Django created virtual environment djangocrudenv activated the environment then pip installed the requirements.txt then followed the tutorial but as you can see in the attached picture it cant find the django module -
Hello folks. i am a fresher ..Currently learning Django basics . i got a error like this .Could you please resolve this 'template loader postmortem
i got a error like this .Could you please resolve this 'template loader postmortem', I also double checked the path for template in settings.py also . but still i could not able to resolve this ..?enter image description here Could you please anyone solve this issue.. -
Caching issue in Celery
I have a scheduled task that runs every 2 days to send reminders to people who haven't read and acknowledged documents on the system. The function works fine when I run it on the shell and all the results are correct. But when celery runs the task it gives (what I believe) cahced results. Meaning that a user has acknowledged the document but the system still sends him reminders about the document. below is my task: @shared_task(bind=True, autoretry_for=(Exception,), retry_backoff=5, retry_kwargs={'max_retries': 5}) def acknowledgment_reminder(self): customers = Customer.objects.filter(is_deleted=False) for customer in customers: log.info(customer.full_name) not_accepted = customer.not_accepted.filter(document__is_deleted=False, document__section__isnull=False) log.info(not_accepted.count()) if not not_accepted: continue customer.send_email(email_type='not_accepted', not_accepted=not_accepted) -
Overriding template name in Django
I'm sorry, I can't understand why template_name won't override default value. It was my understanding that it combines the app name with the model or view name to form the template filename, unless overriden by template_name: class TaskList(ListView): model = Task template_name='test.html' context_object_name='tasks' It still shows the default template (task_list), despite I've tried to override it. I tried clearing cache (by deleting pychache folder), but it didn't work. Thank you for any suggestions! -
Troubleshooting Django Logout Error: Despite Correct Implementation, Logout Button Still Generates Error
I get this error every time I press the logout button, which is weird because I did all the right steps and still have the same result. The error Method Not Allowed: /accounts/logout/ [03/Apr/2024 02:37:45] "GET /accounts/logout/ HTTP/1.1" 405 0 forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms attrs = {'class': 'form-control'} class UserLoginForm(AuthenticationForm): def __init__(self,*args,**kwargs): super(UserLoginForm,self).__init__(*args,**kwargs) username = forms.CharField( label='Username', widget=forms.TextInput(attrs=attrs) ) password = forms.CharField( label='Password', widget=forms.PasswordInput(attrs=attrs) ) # accounts/urls.py from django.contrib.auth.views import LoginView, LogoutView from django.urls import path,include from accounts.forms import UserLoginForm urlpatterns = [ path('login/', LoginView.as_view(authentication_form=UserLoginForm),name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('', include('django.contrib.auth.urls')) ] settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/accounts/login' project/urls.py urlpatterns = [ path('__debug__/',include(debug_toolbar.urls)), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('', include('projects.urls')), ] logout.html {% extends 'base.html' %} {% load i18n %} {% block content %} <form method="post" action="{% url 'logout' %}"> {% csrf_token %} <div class="card text-center"> <div class="card-header"> Log Out </div> <div class="card-body"> <h5 class="card-title">Are You Sure You Want To Log Out Of YOur Account? {{ user.username|title}} </h5> {{ form.as_p }} <input class="btn btn-danger" type="submit" value="logout"> </div> </div> </form> {% endblock %} I try to log out, but I can't. I've tried everything and … -
como hacer un proyecto multi usuario en django [closed]
Necesito un proyecto con multiples usuarios para diferentes apps y sobre todo una validación para que en el login cada usuario sea redirigido a la vista con los permisos correctos, inicialmente pensé que lo podría hacer desde el panel administrador pero no me ha sido posible, si alguien puede ayudar indicandome de que forma lo podría hacer sería una gran ayuda, este es un arbol visual similar a lo que necesito:Multiple user He investigado varias opciones pero ya me he llenado de mucha información y no me queda claro cuál pueda usar para tener roles como admin, editor y viewer en ambas apps y hacer validaciones al momento del login para una correcta redirección -
Websocket Error: Exception inside application: 'set' object has no attribute 'decode'
I'm learning Django for a school project and I'm trying to create a websocket server using Django Channels with Daphne and Redis, but I receive the error "AttributeError: 'set' object has no attribute 'decode'" When loading the app, the websocket handshake happens and a connection is created, however right after this I'm disconnected from the server with the following error and traceback. HTTP POST /chat/signin/ 200 [0.61, 127.0.0.1:54147] WebSocket HANDSHAKING /chat/ [127.0.0.1:54149] username True WebSocket CONNECT /chat/ [127.0.0.1:54149] Exception inside application: 'set' object has no attribute 'decode' Traceback (most recent call last): File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__ return await self.application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/channels/security/websocket.py", line 37, in __call__ return await self.application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/django_channels_jwt_auth_middleware/auth.py", line 36, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/channels/middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/User/folder/projectFolder/env/lib/python3.12/site-packages/channels/routing.py", line 116, in __call__ return await application( ^^^^^^^^^^^^^^^^^^ File … -
Unable to render static files in my Aws elasticbeanstalk after pushing from Cloud9 for my python web application
I have been unable to render my static files in AWS EB for my python application. it renders well on Cloud9 however when I deploy to AWS ElasticBeanstalk, it does not render the files. I have static folder in my base dir and I have referenced this way in my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = 'barterproj/static' #"barterproj" is the name of my main app in my base directory. it has the settings.py MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' Cloud9 reads the static files When deployed to ElasticBeanstalk -
Formatting not being applied to Django form in iOS Safari
This the html code which is producing a 'search bar' for the user to input text: <form id="searchForm" method="GET" action="{% url 'search_mountains' %}#search-and-grid"> {{ form.as_p }} </form> The formatting is declared in the associated CSS: #searchForm input[type="text"] { background-color: rgb(255, 255, 255); color: #303030; display: inline-block; border: #07A3B2 solid 1.75px; padding-left: 7px; font-size: 0.65em; border-radius: 8px; margin-left: 0px; cursor: pointer; opacity: 0.9; width: 150px; -webkit-appearance: none; -webkit-user-select: text; /* Chrome, Opera, Safari */ -moz-user-select: text; /* Firefox 2+ */ -ms-user-select: text; /* IE 10+ */ user-select: text; /* Standard syntax */ -moz-appearance: none; appearance: none; } Which produces the expected result: This formatting is being applied on desktop versions both locally and when deployed in AWS elastic beanstalk and works fine when working locally, even for iOS safari, however when accessing the deployed website in iOS safari the formatting is not being applied: This is only happening when loading the website in 'production' in iOS Safari, it works fine in Google Chrome for iOS for instance. I've tried changing the html syntax to a direct tag rather than a Django input but the same result persists. -
Problem with running a python code with NLTK on Render platform
I have my django project running on Render just fine, and i've been considering on implementing a chatbot using nltk. The problem occurs the moment the project itself is about to run. For some reason, it keeps trying to access stopwords multiple times and then saying that it is already updated. It keeps going without stopping whatsoever. [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Unzipping corpora/stopwords.zip. [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Package stopwords is already up-to-date! [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Package stopwords is already up-to-date! These are the messages that keeps repeating. [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Package stopwords is already up-to-date! [2024-04-02 16:53:45 -0400] [59] [CRITICAL] WORKER TIMEOUT (pid:60) [2024-04-02 16:53:45 -0400] [60] [INFO] Worker exiting (pid: 60) [2024-04-02 16:53:47 -0400] [59] [ERROR] Worker (pid:60) was sent SIGKILL! Perhaps out of memory? [2024-04-02 16:53:47 -0400] [68] [INFO] Booting worker with pid: 68 [nltk_data] Downloading package stopwords to /opt/render/nltk_data... [nltk_data] Package stopwords is already up-to-date! Ant this is what causes it to go in a loop again. import nltk import re import os import csv from nltk.stem.snowball import SnowballStemmer import random from nltk.classify import SklearnClassifier from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords … -
libgeos.py MemoryError on GeoDjango project
I'm developing a GeoDjango project on Rocky Linux 9 and deploying using Apache. The application ran fine before when I used the standard Postgres database engine: "ENGINE": "django.db.backends.postgresql", but as soon as I swap to the PostGIS backend engine: 'ENGINE': 'django.contrib.gis.db.backends.postgis', I get the following error: File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 7, in from .adapter import PostGISAdapter File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/db/backends/postgis/adapter.py", line 5, in from django.contrib.gis.geos import GEOSGeometry File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/init.py", line 5, in from .collections import ( # NOQA File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/collections.py", line 5, in from django.contrib.gis.geos import prototypes as capi File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/prototypes/init.py", line 7, in from django.contrib.gis.geos.prototypes.coordseq import ( # NOQA File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/prototypes/coordseq.py", line 3, in from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR, GEOSFuncFactory File "/home/centurion/centurion_web/.venv/lib/python3.12/site-packages/django/contrib/gis/geos/libgeos.py", line 88, in notice_h = NOTICEFUNC(notice_h) ^^^^^^^^^^^^^^^^^^^^ MemoryError I hadn't even implemented any geospatial code in the application yet. I have a development server on windows that the application runs normally on with that engine using the runserver command. I've tried directly setting the GEOS_LIBRARY_PATH and GDAL_LIBRARY_PATH with no success. I downgraded from django 5.0 to 4.2 with no success. -
CORS headers not allowed in Django
I am developing an API in Django and using next js as the frontend. But each time I try to call the back end to the next js fronend I get on the console Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'http://0.0.0.0:3000' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local` I also get this Login error: AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} code : "ERR_NETWORK" I did the following I added to the first line of the middleware section 'corsheaders.middleware.CorsMiddleware', to my settings.py after install django cors headers Stopped and restarted the server I also ``` CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:3000', 'http://0.0.0.0:3000', ] and yet i still get the problem -
Tables-2 django features for the implementation of my project
I need help with the idea of implementing the project. Initially, the task was to create a custom desktop application for several people to work simultaneously with the database on the server (editing, filtering). The database consists of several main tables, the rows of these tables should be linked to pages with more detailed information (for example, links to products in an online store). There should be such a link for each line. I decided to use django with the django-tables2 module, but I can't figure out if it's possible to use it to implement everything I need? Or will I need something else? Before that, I tried the django-dynamic-datatb module, but could not find a solution that allows you to link each row of the table to a separate page. There is also no html code, so it was not possible to create a menu to navigate from one table to another. It's worth clarifying, I need to use sql express.