Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot add author field in django
but when i'm making python manage.py makemigrations, it says that nothing has changed and in admin panel i only have title and body fields, but not author, can you please tell me where i did some mistakes? i have that django code in blog/models.py: from django.db import models from django.urls import reverse from django.contrib.auth.models import User # Blog Models class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE), body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("post_details", kwargs={"pk": self.pk}) -
How to model biderection relation with a django model?
I have three simple models : Country, state, cities A country has several states A states has severals cities, and only one country A cities has one state I'd like to model this using django class Country(models.Model): name = models.CharField() ... States ??? class State(models.Model): name = models.CharField() country = models.ForeignKey(City, on_delete=models.CASCADE) ... Cities ??? class City(models.Model): name = models.CharField() State = models.ForeignKey(State, on_delete=models.CASCADE) I'm am not very clear about how to represent the links between state and country, as well as the link between state and cities, since there is no "OneToMany" class. Additionnaly, I'd like it to be biderectionnal (I'd like to be able to access the state from the cities, as well as the cities from the states and so on..) How to to that ? -
django-comments-xtd clashing with wagtail-localize
I am following the official tutorial for wagtail-localize, and I am at the step to set up a second locale. When I hit save, I get: DoesNotExist at /admin/locales/new/ XtdComment matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/admin/locales/new/ Django Version: 4.2.2 Exception Type: DoesNotExist Exception Value: XtdComment matching query does not exist. How can I prevent django-comments-xtd to get involved here at all? I am using the latest versions of both packages: Django>=4.2,<4.3 wagtail>=5.0.2,<5.1 django-comments-xtd==2.9.10 wagtail-localize==1.5.1 Thank you! EDIT: I CAN actually create a new locale if I do not synchronize it from my default one. When I then try to edit the new locale to enable synchronization, I get the same error again. -
Djangocms-blog Reverse for 'post-detail' not found in another languages
I wrote a cms plugin that show a blog details and link. it work's on the EN language but in FA post.get_absolute_url() has a error, that says: Reverse for 'post-detail' not found. 'post-detail' is not a valid view function or pattern name. I'm using djangocms-blog==1.2.3, django==3.2.20 and djangocms==3.11.3 My models.py: class ArticleView(CMSPlugin): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="article_view")` My cms_plugins.py: @plugin_pool.register_plugin class ArticleViewPlugin(CMSPluginBase): model = ArticleView name = _("Article View Plugin") render_template = "article_view.html" cache = False In my article_view.html: <a class="fusion-link-wrapper" href="{{ instance.post.get_absolute_url }}"aria-label="{{ instance.post.title }}"></a> My urls.py: from cms.sitemaps import CMSSitemap from django.conf import settings from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.urls import include, path admin.autodiscover() urlpatterns = [path('sitemap.xml', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), path('', include('djangocms_blog.taggit_urls')),] urlpatterns += i18n_patterns(path('admin/', admin.site.urls), path('', include('cms.urls')), path('taggit_autosuggest/', include('taggit_autosuggest.urls'))) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) urlpatterns += static(settings.STATIC_URL, document_root=settings. STATIC_ROOT) error image: I tried to change languages in settings and rebuild the FA page but nothing happened -
Module not found in django
I have a django project with the following structure: game_app lobby_app __init__.py lobby_serializers.py user_app __init__.py user_serializers.py manage.py When I try to import user_serializers/UserSerializer into lobby_serializers.py with from game_app.user_app.user_serializers import UserSerializer I receive module not found from Python. Why is that? I've tried all kinds of import statements, relative, absolute, etc. and I always receive module not found or relative import beyond top level package error. -
How to properly manage CSRF with a React frontend and a Django backend
Ive found that, using Django, CSRF tokens are required under scenarios (and should in general be): For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error. I have found a great deal of documentation and examples relevant only when Django is rendering the page templates. In this case, your templates can use special {% csrf_token %} token to add a hidden field that, when submitted, allows the backend to effectively validate the form's origin. So how does this generally work when Django is not rendering the pages? I can contrive a simple example where the frontend just uses React and the backend is strictly an API. I've found other documentation that claim you can decorate your backend API methods with such things as @csrf_protect or @ensure_csrf_cookie. However, the decorators instruct Django to set CSRF tokens on backed replies for some view/API request. Imagine a simple "login" type of scenario: React frontend renders Login page with form React frontend submits form with PUT to backend for auth According to any docs or … -
Django project: Failed to load resource: the server responded with a status of 404 (Not Found) error for media files
My website was working fine in both development and production, until I tried to add a google analytics tag to the website which I did incorrectly at first (accidentally put it outside of the head element). After doing this, my site started throwing the above 404 error for every media file it tried to load in production, even though the media files are all in the location that the site seems to be trying to access. The site also works perfectly fine in development with the exact same setup. Here is the full error I am receiving for every media file on my site: media_file.ext Failed to load resource: the server responded with a status of 404 (Not Found) Below are the relevant parts of my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and in my urls.py of my project I have included: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I tried both putting the google analytics tag in the head element, which did not work, and then taking the google analytics tag out, which also did not work. I have also tried re-adding the media files to my database by changing the images associated with each django object, … -
error: expected an identifier. expected a valid attribute name
{% for product in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{ product.get("image") }}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.get("product_name") }}</h5> <p class="card-text">{{ product.get("desc") }}</p> <button id="pr{{product.get("id")}}" class="btn btn-primary cart">Add To Cart</button> </div> </div> </div> I was building a Django e-com platform and now I am getting this error for the image src tag ERROR: Expected an identifier. |Expected a valid attribute name, but instead found " ' ", Which is not part of a valid attribute name. How to fix this error? -
How to get hotels near a location using Google places api in a django framework?
I am working on a project using django framework. I want to use google places api to get hotels near a location(location as an input from the user). How to do that? I am new to django framework and integrating different APIs and there is not much information about this anywhere. -
How to use django.shortcuts.redirect outside the view function?
I am making a STT app on my website which uses openai-whisper. repo in need https://github.com/AkioKiyota/arge-test General Purpose Giving users a display/feedback about the process, and running a process without intervening the page. Working steps are like this: You upload your mp4-mp3 file throught form, You click the STT button next to your audio-clip-name, It downloads the whisper model(small), which happens once, Whisper transcribes the mp3 throught its path, Returns the result. Just ignore the div says 'last speech to text' its normaly where it should be showing it. Current script views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import AudioStoreForm from .models import AudioStore import whisper def index(request): audios = AudioStore.objects.all() if request.method == 'POST': form = AudioStoreForm(request.POST, request.FILES) print(form.is_valid()) if form.is_valid(): form.save() return HttpResponseRedirect('') else: form = AudioStoreForm() return render(request, 'index.html', {'form': form, 'audios': audios}) def stt(request, audio_name): module = whisper.load_model('small') audio = AudioStore.objects.get(name=audio_name) result = module.transcribe(audio.audio_file.path, verbose=False) return HttpResponse(result['text']) The Issue The problem is, page just keep loading while the transribe on the process. But i atleast want to add a reloading icon to show user that its actualy working and he should wait. I have tried using Threads like this: views.py def … -
How to get installed package from broken virtual environment python
I had venv that installed Django and python version3.8. After upgrading my ubuntu my virtual environment doesn't work anymore and it doesn't recognize the pip command and it returns: ModuleNotFoundError: No module named 'pip' After searching I found out the virtual environment is broken after upgrading and the best way is to remove venv directory and create again and install your packages again but I don't have my installed package list (using pip freeze > list.txt) so now how can I get installed package list from the broken virtual environment? I can see the list of directories here: $ ls venv/lib/python3.8/site-packages/ but I don't have it -
Timezone in JavaScript(Frontend) and Python(Backend) in Django
I could get the timezone Asia/Tokyo with Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) as shown below: {% "templates/index.html" %} <script> console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) // Asia/Tokyo </script> And, I could get the timezone Asia/Tokyo with tzlocal.get_localzone_name() in Python in test Django View (Backend) as shown below: # "views.py" from django.http import HttpResponse import tzlocal def test(request): print(tzlocal.get_localzone_name()) # Asia/Tokyo return HttpResponse("Test") Now, I set San Francisco to Location in my browser Google Chrome: Then, I could get the timezone America/Los_Angeles with Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) as shown below: {% "templates/index.html" %} <script> console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) // America/Los_Angeles </script> But, I could still get the timezone Asia/Tokyo with tzlocal.get_localzone_name() in Python in test Django View (Backend) as shown below: # "views.py" from django.http import HttpResponse import tzlocal def test(request): print(tzlocal.get_localzone_name()) # Asia/Tokyo return HttpResponse("Test") My questions: Why does tzlocal.get_localzone_name() in Python in test Django View (Backend) still get the timezone Asia/Tokyo? Which timezone does Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) get, my browser timezone or my computer timezone? Which timezone does tzlocal.get_localzone_name() in Python in test Django View (Backend) get, my browser timezone or my computer timezone? -
why does it show "No installed app with label 'learning_logs' " when i try to migrate while I have it in the list of installed apps in settings.py?
i have made an app for a project in django and wrote a class in models.py . i have also included the name of app in the list of INSTALLED_APPS in settings.py . after it, when i try to migrate this change, it says "No installed app with label 'learning_logs'" the relevent screenshots: please help. i tried to do the same thing many times and it didn't work. i expected to get a success message but it showed other( as seen in screenshot) -
How to pass a variable from template to a view
My page has two models into it. They all inherit from one base model: Entry. class Entry(models.Model): author_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) author_id = models.PositiveIntegerField() author = GenericForeignKey("author_type", "author_id") text = models.TextField() class Meta: abstract=True ordering = ["date_created", "date_updated"] class Post(Entry): comments = GenericRelation(Comment, related_query_name="post") def __str__(self): return f"POST(ID{self.id})" class Discussion(Entry): head = models.CharField(max_length=60) comments = GenericRelation(Comment, related_query_name="discussion") def __str__(self): return f"DISCUSSION(ID{self.id})" Template: {% block main %} {% for entry in entries %} <div class="card" style="width: 18rem;"> <img src="{{entry.image}}" class="card-img-top" alt="..."> <div class="card-body"> {% if entry.head %} <h5 class="card-title">{{ entry.head }}</h5> {% else %} <p class="card-text">{{entry.text|slice:"0:20"}}</p> {% endif %} <a href="{% url 'posts:comments' entry.id %}" class="btn btn-primary">Comments</a> </div> </div> {% endfor %} {% endblock %} How can I pass a variable that will distinguish them in a corresponding view, or are there any better ways of doing it? <a href="{% url 'posts:comments' entry.id %}" class="btn btn-primary">Comments</a> My guess is that I need to pass a variable in a URL tag, that will be passed in a view, but I don't know how to do it. Is it the way? Or can I implement it in some better way? -
How do I resolve the Django error "object of type 'int' has no len()" when creating an object in the admin site?
I'm aware of what the error means, the length function is being called on an integer, whereas it only takes a string. However, the tracelog is not particularly helpful and I'm struggling to identify where this error is happening. C:\Users\callu\PycharmProjects\DjangoTests\venv\Lib\site-packages\django\forms\boundfield.py, line 162, in _has_changed return field.has_changed(initial_value, self.data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … Local vars C:\Users\callu\PycharmProjects\DjangoTests\venv\Lib\site-packages\django\forms\models.py, line 1650, in has_changed if len(initial) != len(data): ^^^^^^^^^^^^ It happens when I try and create a new Post object in the admin site so I'm assuming there's an error somewhere in my Post Model, have I created one of the wrongs as the wrong type? class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, default=None, null=True) title = models.CharField(max_length=100) slug = models.SlugField(blank=True) description = models.TextField(max_length=500) date = models.DateTimeField(auto_now_add=True) url_link = models.URLField(default=None, blank=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_support", default=0, blank=True) tags = models.ManyToManyField(Tag, blank=True) class Meta: ordering = ('-date',) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:post_detail", args=(str(self.id),)) Weirdly I can create a Post object fine from my front end, it's just when I try to use the admin site that it throws the error. -
Django register error not fully translated
Standard error massage during registration is: "user account with this email already exists." After I changed LANGUAGE_CODE to 'pl' in settings.py I get: "Istnieje już user account z tą wartością pola email." Instead of "user account" should be "konto użytkownika". Translation mistake is so obvious that I thought that "user account" is somewhere in my project files so I searched my django project and there is no single string in any of my files. How to fix this translation? In django I use 'rest_framework' and 'rest_framework_simplejwt' -
Django Rest framework
I have getting a error 400 bad request when registration. How can I fix it? Suggest something to fix it. I have done authentication in views, sent mail class to sending mail for otp verification to user I'm expecting a suggestion to fix it -
When I click to reserve, I can't save the reservation
I have received the value from the search page and shown in the booking page but also want to record that value as room, details, booking date, booking end and total price of the booking. but cannot save the value view.py def booking_cat_hotel(request, room_number, check_in_date, check_out_date): one_room = Room.objects.get(room_number=room_number) num_days = (datetime.strptime(check_out_date, '%Y-%m-%d').date() - datetime.strptime(check_in_date, '%Y-%m-%d').date()).days total_price = num_days * one_room.price if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.room = one_room booking.start_date = datetime.strptime(check_in_date, '%Y-%m-%d').date() booking.end_date = datetime.strptime(check_out_date, '%Y-%m-%d').date() booking.total_price = total_price booking.save() return redirect('completed', booking_id=booking.id) else: form = BookingForm(initial={ 'room': one_room, 'room_number': one_room.room_number, 'start_date': check_in_date, 'end_date': check_out_date, }) context = { "one_room": one_room, "check_in_date": check_in_date, "check_out_date": check_out_date, "form": form, "total_price": total_price, } return render(request, 'cat_hotel/cat_hotel.html', context=context) html <form action="{% url 'booking_cat_hotel' room_number=one_room.room_number check_in_date=check_in_date check_out_date=check_out_date %}" method="POST"> {% csrf_token %} <div class="container"> <div class="card p-4 mt-5"> <div class="row g-3"> <div class="col-12 mb-4"> <div class="col-12 mb-4"> <h4>Room {{ one_room.room_number }}</h4> <span class="text-muted">{{ one_room.description }}</span> <input type="hidden" name="room_number" value="{{ one_room.room_number }}"> <input type="hidden" name="room_description" value="{{ one_room.description }}"> </div> </div> <div class="col-lg-2 col-md-6 ml-3"> <h5>Check-in Date</h5> <p class="text-primary">{{ check_in_date }}</p> <input type="hidden" name="check_in_date" value="{{ check_in_date }}"> </div> <div class="col-lg-6 col-md-12"> <h5>Check-out Date</h5> <p class="text-primary">{{ check_out_date }}</p> <input type="hidden" … -
Instance deployment failed to install Django application dependencies
I'm trying to deploy my Django app with MySql database into AWS Elastic Beanstalk. Following the official AWS tutorial, after running the command eb deploy I receive the following: Creating application version archive "app-a676-230715_151203074474". Uploading training_centre/app-a676-230715_151203074474.zip to S3. This may take a while. Upload Complete. 2023-07-15 07:12:36 INFO Environment update is starting. 2023-07-15 07:12:39 INFO Deploying new version to instance(s). 2023-07-15 07:12:45 ERROR Instance deployment failed to install application dependencies. The deployment failed. 2023-07-15 07:12:45 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2023-07-15 07:12:49 ERROR [Instance: i-0cd43d89a29ebb953] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2023-07-15 07:12:50 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2023-07-15 07:12:50 ERROR Unsuccessful command execution on instance id(s) 'i-0cd43d89a29ebb953'. Aborting the operation. 2023-07-15 07:12:50 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. Here is the output of eb logs: ============= i-0cd43d89a29ebb953 ============== ---------------------------------------- /var/log/eb-engine.log ---------------------------------------- Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.p y", line 351, in <module> main() File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.p y", line 333, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.p y", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-098fsfb8/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", … -
Who renders a django TemplateResponse if I don't?
Suppose I return a TemplateResponse object from a view in Django. Even if I don't manually call response.render() anywhere in my code, what is returned is a rendered object. Which middleware or other part of Django automatically renders TemplateResponses? I tried going through the code but couldn't find it. -
How to use django asynhronous programming with drf API views?
I am trying to implement asynchronous programming with django rest framework and I am using api_view decorators for my function based API views. So I was trying to convert my synchronous method to asynchronous with asgiref.sync.sync_to_async decorator but seems like using this django is not able to route to my API view. Here is my function based api view. from rest_framework.decorators import permission_classes, api_view, authentication_classes from rest_framework.permissions import AllowAny, IsAuthenticated from asgiref.sync import sync_to_async from ..customauth import CustomAuthBackend from ..utils.auth_utils import AuthUtils @api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([]) @sync_to_async def login(request): email = request.data.get('email') if email is None or email == '': return Response(data={'success': False, 'message': 'Invalid credentials'}) user = User.get_by_email(email=email) if user is not None and user.is_active and user.check_password(raw_password=request.data.get('password')): serializer = UserSerializer(user) tokens_map = AuthUtils.generate_token(request=request, user=user) return Response({'success': True, 'user': serializer.data, 'tokens': tokens_map}) return Response(data={'success': False, 'message': 'Invalid login credentials'}, status=status.HTTP_403_FORBIDDEN) If I use async def that is also not working with django rest framework. How do I make the use of event loop here efficiently ? -
In Django how can I use string concatenation (||"-"||) for fields in a database and display them in the form?
I would like to use this ||"-"|| SQL string concatenation between x = models.CharField(max_length=30) and y = models.CharField(max_length=30). Next in the combobox on the form, I would like to display all x and y fields of the database, like this: x-y Being new to Django, I don't know how to pass the parameter in views.py in this line: object_voyage = form.cleaned_data['voyage'], considering that 'voyage' is not a database field because there are x and y in the database. voyage is the name of the containment. I tried using CharField and Concat, but I don't know if it's the right solution. Maybe I've completely got the wrong approach and need a different way, I don't know.The error is that the combobox of the form is not displayed at all The SQL code, to make you understand better, would be this: SELECT x||"-"||y FROM Table1 Here is my code: models.py from django.db import models class MyVoyage(models.Model): x = models.CharField(max_length=30) y = models.CharField(max_length=30) def __str__(self): return self.x, self.y forms.py from django import forms from .models import MyVoyage from django.db.models import CharField, Value from django.db.models.functions import Concat class Form_MyVoyage(forms.Form): voyage = forms.ModelChoiceField(queryset=MyVoyage.objects.annotate(match=Concat('x', Value('-'), 'y', output_field=CharField()))) views.py def View_MyVoyage(request): object_voyage = None if request.method == … -
How to set up header and footer in every page of a pdf without overlapping them with inner contents using python weasyprint?
as you can see i have header and footer and in between them there is a order item table which is kind of overlapping with the footer I have tried this way there is a header , a main section then a footer the header is set to fix and main is set to relative and the footer is set to fixed here is the html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> @page { size: A4; margin: 10mm 15mm; padding: 0; @top-center{ content: element(header); } @bottom-center{ content: element(footer); } } header { position: fixed; top: 0; width: 100%; } footer { position: fixed; bottom: 0; font-size: 10px; text-align: center; width: 100%; padding: 5px; margin: -10mm; } main { position: relative; top: 250px; width: 100%; } *{ font-family: Verdana, Geneva, Tahoma, sans-serif; } .logo{ height: 70px; width: 80px; } .qr_img { height: 80px; width: 80px; } .flex{ display: flex; flex-wrap: nowrap; flex-direction: row; align-items: center; justify-content: space-between; } .vertical { border-left: 3px solid gray; height: 70px; position:absolute; } .invoice-word{ font-size: 45px; font-weight: bolder; } .order-info{ font-size: 12px; } .order-info p{ margin: 0; } .py-2{ padding: 2px 2px 2px 2px; } … -
Django error: 'tuple' object has no attribute 'get'
So, I started to make my first Django project, everything was okay but when I make my second site and Runserver this message popped up: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.3 Python Version: 3.10.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home'] Installed 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'] Traceback (most recent call last): File "C:\Users\hungp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\hungp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\hungp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: Exception Type: AttributeError at / Exception Value: 'tuple' object has no attribute 'get' Here is my code: views.py: from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home/home.html'), def product(request): return render(request, 'home/product.html'), def register(request): return render(request, 'home/register.html'), I have try looking in my views.py file, my urls.py and even setting.py but I couldn't find any tuple as mentioned in the error. I have also tried reinstalling Django but it didn't work. The last thing that I did was check my views.py as suggested on some previous error posts on StackOverflow but it didn't work either. Edit 1: I found the solution. The error is … -
Sql Field Recursive Limit Exceeded: Model with a parent reference to another of itself
So far. I can understand that there is a sql/database querying issue related to this. The symptoms of the bug is also a long wait time, typical of a recursive method. Although, imo it shouldnt be recursive, it should just list categories that match the parent category. I am doing this all from the admin part at the moment, and I am not quite sure how to work with django enough to know how to solve this issue correctly, at the moment. So the rundown: Slow response to an error (recursive function behaviour within database?) Occurs when accessing the admin/category/create page (GET request) Something to do with having a parent 'category' in itself *edit: I think it may have to do with looking into itself, when it shouldnt. Here is the code, all in the same module: # models.py class Category(models.Model): title = models.CharField(max_length=32, unique=True) parent_category = models.ForeignKey( "self", related_name="sub_categories", on_delete=models.SET_NULL, null=True, blank=True, ) featured_product = models.ForeignKey( "Product", on_delete=models.SET_NULL, null=True, blank=True, related_name="+" ) def __str__(self) -> str: if self.parent_category: return f"{self.parent_category} - {self.title}" return self.title class Meta: ordering = ["title"] # admin.py @admin.register(models.Category) class CategoryAdmin(admin.ModelAdmin): autocomplete_fields = ["featured_product"] list_display = ["title", "products_count"] search_fields = ["title"] @admin.display(ordering="products_count") def products_count(self, category): url …