Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting an error when serializing a list of values [AttributeError: 'list' object has no attribute 'user_project']
I have two models Project and Shift with a Many-to-one relationship. And I want to collect statistics for all Shift objects. How this should happen: The User sends a GET request with a parameter that specifies which Project to calculate statistics for all its Shift, the function is called which calculates statistics and puts it all into the list and returns it, the list should be serialized and sent to the User. But I get an error when I send it. [AttributeError: 'list' object has no attribute 'user_project'] If I needed to serialize a model or QuerySet I probably wouldn't have any problems, but here I have a regular list. I wrote a separate serializer specifically for values from this list, but nothing works. Most likely I wrote it wrong. If there is a better way to do it, please advise me. models.py class Project(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) task = models.CharField(max_length=128) technical_requirement = models.TextField() customer = models.CharField(max_length=64, blank=True) customer_email = models.EmailField(blank=True) start_of_the_project = models.DateField() salary_per_hour = models.FloatField() project_cost = models.FloatField(blank=True, default=0) project_duration = models.DurationField(blank=True, default=datetime.timedelta(0)) class Shift(models.Model): user_project = models.ForeignKey('Project', on_delete=models.CASCADE) shift_start_time = models.DateTimeField() shift_end_time = models.DateTimeField() shift_duration_time = models.DurationField(blank=True, null=True) salary_per_shift = models.FloatField(blank=True, null=True) serializers.py class ShiftStatisticSerializer(serializers.Serializer): user_project … -
Deploying Django project with custom apps to heroku: remote: ERROR: /path/to/myapp/django-myapp is not a valid editable requirement
I am using Django 3.2 I have written a number of standalone apps, which I am using in my project. In my requirements file, I have included them at the bottom of the requirements.txt file like this: requirements.txt asgiref==3.5.0 Babel==2.9.1 certifi==2021.10.8 charset-normalizer==2.0.12 coverage==6.4.1 dj-database-url==0.5.0 Django==3.2 django-appconf==1.0.5 django-crispy-forms==1.14.0 django-js-asset==2.0.0 gunicorn==20.1.0 idna==3.3 psycopg2-binary==2.9.3 python-decouple==3.6 pytz==2022.1 requests==2.27.1 six==1.16.0 sqlparse==0.4.2 urllib3==1.26.9 webencodings==0.5.1 whitenoise==6.0.0 -e /path/to/django-apps/moderation/django-moderation -e /path/to/django-apps/social/django-social -e /path/to/django-apps/user/django-userprofile -e /path/to/django-apps/event/django-events -e /path/to/django-apps/contactus/django-contactus On my local machine, I type: pip install -r requirements.txt and everything is installed correctly. However, when I try to deploy to heroku by typing: git push heroku main I get the following error message: remote: -----> Installing requirements with pip remote: ERROR: /path/to/django-apps/moderation/django-moderation is not a valid editable requirement. It should either be a path to a local project or a VCS URL (beginning with bzr+http, bzr+https, bzr+ssh, bzr+sftp, bzr+ftp, bzr+lp, bzr+file, git+http, git+https, git+ssh, git+git, git+file, hg+file, hg+http, hg+https, hg+ssh, hg+static-http, svn+ssh, svn+http, svn+https, svn+svn, svn+file). remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... How do I fix this, so I can push local changes to heroku? -
Django Loading up Class based model data on a template
I am new to django before this only made 1 project and that was just a follow along video so obviously the fix is probably very easy, but I am trying to make a restaurant reservation page, and later on there will be user authentication to only show the reservation that particular user made, but right now I want to display all of the reservations in my modal and trying to learn how to actually display the data. here's the modal: https://gyazo.com/066e3e060492990008d608a012f588f3 here's the view: https://gyazo.com/6947ed97d84b38f1e73680e28f3a0a9a Here's the template: https://gyazo.com/966c4810b3c7f4dd8dad2e5b71c2179c I am spent about 3 hours watching other videos on people loading there modal data in there website and when they do it I understand everything but for some reason I can't apply that to my own project, my guess is my for loop is wrong since I have a hard time with writing them and seem to always mess up, so any help so I can at least start looking in the right direction would be appreciated -
Why Django admin Shows Invalid string value for specific table?
I use Mysql database where i set database and database column are utf8mb4 and collate utf8mb4_general_ci. When i want to change any data value then given this error Incorrect string value: '\xE0\xA6\xB8\xE0\xA7\x8D...' for column This error only happen those table whose Foreign key uses in other table. But single table which is not related to other tables then no error occured. I search the solution in google almost everyone says to change column charset, i change this but given same error those table which table is associated with other table..! Please help me!!! -
Best framework to learn in 2022? [closed]
I am web developer beginner working on WordPress right now, I just want to learn one framework amoung this? Django, React, or Laravel Plz suggest… -
Django : smtplib.SMTPAuthenticationError: 535, b'5.7.8 Username and Password not accepted
I was trying to send mail using the gmail smtp in DJango. I know about this option Less secured apps. But this option has been disabled by google now. Also I don't have any 2 factor authentication on my account. Here is my setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' # put your gmail address here EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True But I am getting error [2022-06-15 10:28:10,688: ERROR/ForkPoolWorker-1] Task app.tasks.send_email_task[9068931b-a457-415e-b910-d7c631596fce] raised unexpected: SMTPAuthenticationError(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o16-20020a056a00215000b0051b97828505sm9333570pfk.166 - gsmtp') Traceback (most recent call last): File "/etc/myprojectenv/lib/python3.8/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/etc/myprojectenv/lib/python3.8/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/etc/myproject/app/tasks.py", line 12, in send_email_task return send_mail( File "/etc/myprojectenv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 87, in send_mail return mail.send() File "/etc/myprojectenv/lib/python3.8/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/etc/myprojectenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/etc/myprojectenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 91, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.8/smtplib.py", line 743, in login raise last_exception File "/usr/lib/python3.8/smtplib.py", line 732, in login (code, resp) = self.auth( File "/usr/lib/python3.8/smtplib.py", line 655, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials … -
Can't establish a WebRTC connection between browser and server with Django and aiortc: WinError 10051
I have created a simple WebRTC conference where multiple peers on the same network can open a web page and see each other/talk to each other. Each peer keeps track of its own pool of RTCPeerConnections, while Django handles authorization and django-channels handle signaling through WebSockets. I also need to stream audio data to the server for analysis. I decided to add the server as another WebRTC peer. In order to do that, I used aiortc module and created a class RTCPeer that handles RTCPeerConnections and a class RTCRoom that spawns RTCPeers and keeps track of them. Both are connected to signaling: they can send messages through channel layer; any messages received by WebSockets consumer are forwarded to RTCRoom.receive. When I try to connect a client to the server, I run into error 10051 multiple times. It looks like none of the pairs of gathered ICECandidates can provide connection. What could be wrong here? INFO:aioice.ice:Connection(0) Check CandidatePair(('172.18.108.97', 58214) -> ('109.120.16.131', 63420)) State.FROZEN -> State.IN_PROGRESS DEBUG:aioice.ice:Connection(0) protocol(1) > ('109.120.16.131', 63420) Message(message_method=Method.BINDING, message_class=Class.REQUEST, transaction_id=b'\xcc)\xfb\x9c\xba\xc4!\xc0\x85P\x8fs') DEBUG:aioice.ice:Connection(0) protocol(1) error_received([WinError 10051] Сделана попытка выполнить операцию на сокете при отключенной сети) ... INFO:aioice.ice:Connection(0) Check CandidatePair(('172.18.108.97', 58214) -> ('192.168.1.149', 63420)) State.IN_PROGRESS -> State.FAILED Full log: https://drive.google.com/file/d/1v70SwZS2332sAoAfEbVHAJDRVJ0FVovg/view?usp=sharing RTCRoom … -
How i can make this filter
I wanna create filter for cars by marks, and idk why, i get empty template with list of objects I have this model with Foreignkey mark model for getiing mark for specify car class Product(models.Model): ENGINE_CHOICES = ( ('Бензин', 'Бензин'), ('Дизель', 'Дизель'), ) code = models.AutoField(primary_key=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) mark = models.ForeignKey(Mark, on_delete=models.CASCADE, related_name='mark') model = models.CharField(max_length=45) color = models.CharField(max_length=45) availability = models.BooleanField() price = models.PositiveIntegerField() image = models.CharField(max_length=64, null=True) slug = models.SlugField(blank=True) year = models.PositiveSmallIntegerField("Дата выхода", default=2019, null=True) draft = models.BooleanField('Черновик', default=False) cat = models.ForeignKey(Category, verbose_name='Категории', on_delete=models.PROTECT, null=True) description = models.TextField(max_length=500, null=True) engine = models.CharField(choices=ENGINE_CHOICES, max_length=20, blank=True, null=True) And this model class Mark(models.Model): code = models.AutoField(primary_key=True) title = models.CharField(max_length=45) def __str__(self): return self.title i have this component in html for getiing mark in vews <div id="myDropdown7" class="dropdown-content"> {% for mark in marks %} <form action="{% url 'filtration_marks' %}" method="GET"> <label class='dropdown-content-menu'> <input id='checkbox1' type="checkbox" class='checkbox' name="id" value="{{ mark.id }}"> <label for='checkbox1'></label> <button type="submit" style="border: 0; background-color: white; font-size: 16px;">{{ mark.title }}</button> </label> </form> {% endfor %} And this method in views that handle request def filtration_marks(request): products = Product.objects.filter(mark__in=request.GET.getlist('mark')) categories = Category.objects.all() marks = Mark.objects.all() context = { 'products': products, 'categories': categories, 'marks': marks, } return render(request, 'filtration.html', … -
django.db.utils.IntegrityError: CHECK constraint failed
when I am migrating I am getting the error django.db.utils.IntegrityError: CHECK constraint failed. I am using django-cms. this error popped up after trying to add editor.js to the project full Error: Applying advita.0003_auto_20220615_1506...Traceback (most recent call last): File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: CHECK constraint failed: (JSON_VALID("sub_title") OR "sub_title" IS NULL) The above exception was the direct cause of the following exception: Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\operations\fields.py", line 236, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) … -
Django call a class based view from another class based view
I have two classes corresponding to two different forms. When one is submitted, i need to call the other one. class FormsPreInput(CreateView): template_name = "form_preinput.html" def get(self, request, *args, **kwargs): form = preinput_form() return render(request, self.template_name, {"form": form}) def post(self, request, *args, **kwargs): form = preinput_form(request.POST) if form.is_valid(): return FormsInput.as_view()(request=self.request) class FormsInput(CreateView): template_name = "input_form.html" def get(self, request, *args, **kwargs): print("inside input get") def post(self, request, *args, **kwargs): print("inside post ") So the problem is the code is FormsInput is being called using the POST request object, so the code goes to FormsInput.post() without going to FormsInput.get() -
Joining two filtered objects two produce a single data object
I have two filtered objects based on months in a year. I wanted to return a single object based on the same months, but with the different summed values. I thought of a way I could do this, and at the moment, I have the setup running. I intend to cache the result and update it upon any database changes. I just can't help but feel like there could be a better way to do this. @permission_classes([IsAuthenticated]) @api_view(["GET"]) def refBonus(request): user = request.user referralBonus = AddToWallet.objects.filter(user=user, type="Referral").annotate(month=TruncMonth('date') ).values('month').annotate(Sum('amount')) aggregatedProfit = Profit.objects.filter(user=user).annotate(month=TruncMonth('date')).values( 'month').annotate(Sum('amount')) newList = [] for i in aggregatedProfit: for e in referralBonus: if i["month"] == e["month"]: h = {'month': i["month"], "profit": i["amount__sum"], "bonus": e["amount__sum"]} newList.append(h) months = [] for i in newList: # Append all months in newList to months variable months.append(i["month"]) # Check if a month present in aggregatedProfit is not present in months already, add it to the months variable along # with bonus being 0 as it means bonus does have data for that month for i in aggregatedProfit: if i["month"] not in months: h = {'month': i["month"], "profit": i["amount__sum"], "bonus": 0} months.append(i["month"]) # Append the month the months variable newList.append(h) # Check if a month … -
How to set permissions for a group automatically?
When creating the Django model, Django will automatically create permissions for CRUD operations. Provided that user groups have been created earlier, the question arises: how to add the necessary permissions for a group automatically? At the moment, I create data migrations in which I add the necessary permissions for the group "manually". Maybe there is a way to do this without data migration? -
Populate Related Field Based on Query Parameter
I'm trying to implement a way to show full details of a related field, rather than just the ID or a specific field, when it is specified in a query parameter, e.g http://api_url/courses?populate="author" I can currently show full details of the field by using a nested serializer, like so, or show just the UUID (or any other field) using a SlugRelatedField. class CourseSerializer(serializers.ModelSerializer): author = UserSerializer() class Meta: model = Course fields = "__all__" Any help is much appreciated. -
django-csp -- Why I am getting CSP violation error even if nonce is set up?
I am getting error in my browser as Refused to execute inline script because it violates the following Content Security Policy directive: "script-src-elem 'self' 'self' https://cdn.jsdelivr.net/". Either the 'unsafe-inline' keyword, a hash ('sha256-lcRjLlr3aCdbAn5uZatA01Jri58xjpKG86fd61W4h9Y='), or a nonce ('nonce-...') is required to enable inline execution. I am using django-csp to set up Content Security Policy. In my settings.py, I have included the following. MIDDLEWARE = [ # added middleware 'csp.middleware.CSPMiddleware', ... ] CSP_DEFAULT_SRC = ["'self'", ] CSP_INCLUDE_NONCE_IN = ['script-src'] I have written the JavaScript as - <script nonce="{{ request.csp_nonce }}"> do_something() </script> Please help me to resolve the issue. -
Dynamically prevent opening a page if someone else is actively using it
I am using Django for backend, and normal HTML/CSS/JavaScript for frontend without any interactive UI libraries like React. Current Approach: I have a page that contains a form to edit instance X as an example. If someone opens this page for editing, I am adding a value in my database that this instance is locked by this editor. After he finalizes editing, he should press "save" or "close" button to unlock it for others. Problem: If the editor didn't save and forgot to "close", the instance will remain locked till he come back and close it. Required Approach: But, I want to dynamically prevent the others to open it because someone is actively editing X now. By "actively" word, I mean that this user is using the page now, and the page tab is active in his browser. So, if he just closes the tab or browser, or leaves the tab inactive for maybe 5 minutes, I want to unlock the instance for editing. -
Download files as stream without downloading complete files into memory
I want to download files as stream from a remote server and make them zip stream and return it to frontend as stream without waiting all files to complete downloads. Is it possible in python and framework of python ?? I tried as below but its not working i am using Django framework: zip_buffer = io.BytesIO() with zipstream.ZipFile(zip_buffer,"w", zipfile.ZIP_DEFLATED, False) as zf: url = "https://download-file/zy" r = requests.get(url, stream=True) zip_inf = zipstream.ZipInfo(file_name) zf.write_iter(zip_inf, r.content) response = StreamingHttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=zip-files.zip' return response -
Problem with connect local postgres to docker container
I have docker.compose.yml file: version: '3.8' services: web: build: ./kazarm command: python manage.py runserver 0.0.0.0:8000 volumes: - ./kazarm/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:13.0-alpine ports: - 127.0.0.1:5432:5432 environment: - POSTGRES_USER=kazarma - POSTGRES_PASSWORD=kazarma - POSTGRES_DB=kazarma networks: outside: external: true In Django DB setting.py SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=kazarma SQL_USER=kazarma SQL_PASSWORD=kazarma SQL_HOST=127.0.0.1 SQL_PORT=5432 In pg_hba.conf file # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. local replication all trust host replication all 127.0.0.1/32 trust host replication all ::1/128 trust and in postgres.cong also listen_addresses = '*' And I try to use the different SQL_HOST like localhost, 127.0.0.1 all don't work. But when I get SQL_HOST=db then it works. docker-compose log file django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "127.0.0.1" and accepting web_1 | TCP/IP connections on port 5432? I want to use the local Postgres because the data is very important and when I down my docker I … -
microsoft django authentication
I want to authenticate my Django base website users by Microsoft authentication, I have followed a multiple solutions but not getting the results so can you please tell me that how can I integrate Microsoft authentication as a third party with my Django project. -
login(request, user) not working in python django
urls.py this is my url page path('login/',views.login_view, name="login"), views.py this is my views if request.method == "POST": user_name = request.POST.get("username") pass_word = request.POST.get("password") user = authenticate(request, username=user_name, password=pass_word) # print("user1 -->", user) if user is not None: # print("user-->",user) login(request, user) return render(request, "index.html") else: return render(request,"http://127.0.0.1:8000/login") else: #return render(request, "order.html") return render(request, "login.html") error I am getting is TypeError at /login/logincheck/ login() missing 1 required positional argument: 'user' -
How to identify Oracle instantClient in a Django project?
I try to link an external Oracle database on which I have read-only privileges to my Django project and then only send it raw SQL queries. So I first created a second table in my project settings (because I still need the default database) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'oracleDB':{ 'ENGINE': 'django.db.backends.oracle', 'NAME': 'my_dsn', 'USER': 'my_user', 'PASSWORD': 'my_password', 'HOST': 'my_host', 'PORT': 'my_port', 'OPTIONS':{ 'threaded':True } } Then in my view I call it this way (seen on a forum): views.py from django.db import connections def my_function(request): with connections['oracleDB'].cursor() as cur: cur.execute( "SOME SQL QUERY") print(cur.fetchall()) And I get this error DPI-1047: Cannot locate a 64-bit Oracle Client library: “C: ProgramData Oracle12c product 12.1.0 client_1 bin oci.dll is not the correct architecture”. See cx_Oracle 8 Installation — cx_Oracle 8.3.0 documentation for help I know that I need the Oracle instantclient to connect, I used to use it in connection with the cx_Oracle package and it worked well (so i'm certain the version is good). Except that now I connect with Django and its settings where I can’t specify the path to my Oracle instantclient. Do you have any idea how to enable Django … -
Repeating record using for loop in database
in this code am trying to add the student record in the attendance database whenever the student image is captured by the webcam so name = image name stored adding that the image name is the same as the studentid stored in Student entity, whenever the detected face name exist in Name = the list of images name then it will add the student info to the attendance database. The code just works fine but it keeps repeating the records how can I limit it to add the record just once and not repeating it. def markattendance(name): for n in Names: if name in Names: # print(name, "Exist") # fitches the information related to the detected name attend = Student.objects.filter(student_id=name).values('student_id', 'student_fname', 'student_lname','fk_course_id_id') #print(attend) # filter returns a queryset. A queryset isn't a single object, it's a group of objects so it doesn't make sense # to call save() on a queryset. Instead you save each individual object IN the queryset: for object in attend: #print(object) if object.get('student_id') not in attend: # INSERT SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call save(). reg = Attendance(student_id=object.get('student_id'), student_fname=object.get('student_fname'), student_lname=object.get('student_lname'), course_id=object.get('fk_course_id_id')) # print(reg) reg.save() else: pass -
Create a folder with models,views and urls inside an app.How to import these models in the main app model?
I have created an App using the startapp command and inside that i have created other files.But when i try to import that model in the init file of main app it get this as an error:: from subapp1.models.models import TodoList ModuleNotFoundError: No module named 'subapp1' How can i import this? I am written this in the main app init file-->> from subapp1.models.models import TodoList all = ['TodoList',] -
How to customize field representation in django drf AutoSchema?
I am new to using Django drf schema generation. I installed and configured the schema according to the documentation. It generates the OpenAPI schema. Now I want to customize the choice field representation and add some description in front of each field. Current schema is like below: condition: enum: - used - new - like new type: string nullable: true I want the following: condition: enum: - used: "for used items" - new: "for new items" - like: new " brand new items" type: string nullable: true In the documentation I could find little on how to customize the AutoSchema class but that was above my knowledge. I would be grateful if someone can help me on how can I override the schema methods to represent customize fields? -
Issue with circular import in Django tutorials?
I am getting a circular import error with a basic Django page setup and I have no idea why. Am following the guides of at least 4 or 5 different tutorials with the same result. I have varied the syntax in the webapps urls.py to no avail. Any ideas ? mainproject urls.py file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('members/', include('members.urls')), path('admin/', admin.site.urls), ] webapp Views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello world!") urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Error "/Users/Desktop/website/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 706, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'members.urls' from '/Users/Desktop/website/main/members/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. -
extra query after logging in to the site (django3.2)
Why after logging in to the site, an extra query is taken on all pages to get that user information? Is this related to Django it self? Or can this extra query be deleted and optimized? What the Django-debug-toolbar shows on all pages: SELECT ••• FROM "accounts_user" WHERE "accounts_user"."id" = '1' LIMIT 21 And the user with the id=1 is the user I logged in with.