Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to design my Django app database to accommodate multiple level information of an item?
I am trying to create an app on Django. Struggling on how to proceed on Database schema. There are the following tables: 1), table customer: cust_name cust_addr cust_phone created_date ... 2), table customer_assets customer (foreign key pointed to table customer) asset_type asset asset_update_time asset_creation_time ... The major issue is on asset, asset_type, sample data like below: asset_type asset domain aaa.bb.example.com domain *.corp.example.com ip 10.1.2.3 ip 10.8.0.0/16 url http://aaaa url http://bbbbb url http://aaa.bb.example.com/app1/login email xxx@example.com there are some assets like *.corp.example.com, 10.8.0.0/16. The app is supposed to do a discovery and find more assets under them, for example: aaa.corp.example.com bbb.corp.example.com ccc.corp.example.com 10.8.2.2 10.8.2.3 ... The app is then going to scan the open ports on each of them, like: aaa.corp.example.com. (22, 80, 1080) 10.8.2.2 (21, 139, 3306) the app may then scan every ports on the assets to find urls, like: aaa.corp.example.com 80 /home.html aaa.corp.example.com 80 /admin.html bbb.corp.example.com 443 /console Note that: data in customer_assets is basically provided by customer data in customer_assets contains data of various types, for example, 1), wildcard sub domains (.corp.example.com) and exact subdomains (aaa.bb.example.com). 2), exact subdomains in wildcard sub domains (.corp.example.com) will later be discovered what's the best way to organise the database schema? 1), … -
Warrning from unittest on models.DateTimeField with auto_now=True
I got model in Django 4.2.1 that has an autofield updated each time anytching is changed in record. Implemented only by this one line: last_modification = models.DateTimeField(auto_now=True, editable=True) In PGAdmin I see correct created records. And in standard usage I got no warnings inside container terminal. But whent I run tests by command inside container "python manage.py test" I recieve warnings like: warnings.warn( /usr/local/lib/python3.11/site-packages/django/db/models/fields/init.py:1595: RuntimeWarning: DateTimeField SMSNotification.last_modification received a naive datetime (2024-02-02 13:46:49.356514) while time zone support is active./bin/sh: 3: Syntax error: newline unexpected (expecting ")") warnings.warn( /usr/local/lib/python3.11/site-packages/django/db/models/fields/init.py:1595: RuntimeWarning: DateTimeField SMSNotification.last_modification received a naive datetime (2024-02-02 13:46:49.356514) while time zone support is active. Is this a common unittest problem or my implementation of model? If should be ignored, can I configure test framework to avoid printing the warning? -
Trying to lay out a variable number of cards per row with Django and Bootstrap
I have a variable number of items on Bootstrap cards that I will be laying out (maybe 100). I want to lay this out to put as many per row as will fit (let's assume fixed width). On a larger screen, I should get | 1 2 3 4 | On a smaller one: | 1 2 | | 3 4 | I'm looping through the item with a for loop in a Django template. Every method I've found assumes that the server will have a preset number of columns in the row. This makes no sense to me, as I want to set the with for readability (like 20em), and then put as many items per row that fit. This is what I have, it doesn't work. <div class="container-fluid"> <div class="row"> {% for person in people %} <div class="row"> <div class="card width=25%"> <img class="teacher-pic card-img-top" style="float:left; margin: 0 15px 0 0;" src="{{ person.person_photo_url }}"/> <div class="card-body"> <h5 class="card-title">{{ person.person_name }}</h5> <p class="card-text">{{ person.person_description }}</p> </div> </div> </div> {% endfor %} </div> </div> -
Django Busy GPIOs Raspberry Pi 5
When trying to interface with the GPIO of the RPi 5 using gpiozero, I am running into an error stating that the GPIO is busy. The context is that I am running this code in a Celery task in Django. The issue is similar to this, but the fix provided did not work in this context. -
Triggering Python Function on Django + React
I am attempting to send data from my React frontend to a Django backend and trigger a function. I'm developing a Django REST API using Django Rest Framework, and I've set up a view in the calculator app to handle POST requests. The objective of the calculator view is simply concatenate text from frontend: #app/calculator/views.py from django.http import JsonResponse def concat_text(request): if request.method == 'POST': received_text = request.POST.get('text', '') result = received_text + ' =)' print(result) return JsonResponse({'result': result}) else: return JsonResponse({'error': 'Only POST requests are allowed'}) However, when I make a request from my React frontend, I'm receiving a 403 error (Forbidden). I am sending the text value via frontend by: const handleButtonClick = async (e) => { e.preventDefault(); try { const response = await fetch(`${URL}/calculator/calculator/`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ text }), }); The URL is simply the "http://localhost:8000". I have also defined the calculator urls: #app/calculator/urls.py from django.urls import path from .views import concat_text urlpatterns = [ path('calculator/', concat_text), ] My app urls: #app/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView from core import views as core_views … -
Unable to Store data in order placed table and deleting data from cart table after completion of payment
4 i am using razorpay payment gateway web integration for my learning eccomerce project everyhing work fine payment can be done all i want is to store my cart data in OrderPlaced table and delete the cart data from Carts table and redirect the page on home after payment done in my order model using test mode. but in this code something is wrong after payment completion Nothing happen no changes nor in Carts table neither in OrderPlaced table. This is my Checkout View for the payment initiation class checkout(View): def get(self, request): user = request.user add = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) famount = 0 for p in cart_items: value = p.quantity*p.product.discounted_price famount = famount+value totalamount = famount+30 razoramount = int(totalamount * 100) client = razorpay.Client( auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) data = {"amount": razoramount, "currency": "INR", "receipt": "order_rcptid_12"} payment_response = client.order.create(data=data) print(payment_response) order_id = payment_response['id'] order_status = payment_response['status'] if order_status == 'created': payment = Payment( user=user, amount=totalamount, razorpay_order_id=order_id, razorpay_payment_status=order_status ) payment.save() return render(request, 'app/checkout.html', locals()) And this is my paymentDone View here i try to store all cart items in OrderPlace table and delete item from the Cart table.. def payment_done(request): order_id = request.GET.get('order_id') payment_id = request.GET.get('payment_id') cust_id = request.GET.get('cust_id') user = … -
Handling Multiple dependent drop down lists in a form using Django and jquery
I want to create a form with 4 drop down list in which two of them are dependent on the other two, example i have a country and city drop list in which the city is dependent on the country i.e. when a country is selected only cities in that country will show in the city drop down and its working perfectly but my department and unit are not working as expected. I wand same for my department and units, if a department is selected only units in that department should show. I want to implement this in one form. <form method="post" enctype="multipart/form-data" autocomplete='off' class="mt-3" novalidate id="personForm" data-cities-url="{% url 'ajax_load_cities' %}" data-units-url="{% url 'ajax_load_units' %}"> <div class="row"> <div class="col-3">{{ form.country|as_crispy_field}}</div> <div class="col-3">{{ form.city|as_crispy_field}}</div> <div class="col-3">{{ form.department|as_crispy_field}}</div> <div class="col-3">{{ form.unit|as_crispy_field}}</div> </div> <script> $("#id_country").change(function () { const url = $("#personForm").attr("data-cities-url"); const countryId = $(this).val(); $.ajax({ url: url, data: { 'country_id': countryId }, success: function (data) { console.log(data); $("#id_city").html(data); }); } }); }); $("#id_department").change(function () { const url = $("#personForm").attr("data-units-url"); const departmentId = $(this).val(); $.ajax({ url: url, data: { 'department_id': departmentId }, success: function (data) { console.log(data); $("#id_unit").html(data); } }); }); </script> -
htmx: hx-target-error fails when hx-target defined (django python)
I am using the htmx extension "response-targets" via "hx-ext" in a python django project. The Problem "hx-target-error" will not work when "hx-target" is also defined, but works when it is the only target. Environment htmx 1.9.10, response-targets 1.9.10, python 3.12, django 5.0.1 Example html: <div hx-ext="response-targets"> <button hx-get={% ur "appname:endpoint" %} hx-target-error="#id-fail" hx-target="#id-success" type="submit" > Press Me! </button> </div> hx-target Have tried with various other type of targets such as "next td", "next span", etc. All of them produce value "request.htmx.target" values in the endpoint defined in views.py. hx-target-error Have also tried various alternatives supported in response-targets such as "hx-target-*", "hx-target-404", etc with no change in results. I verified that "response-targets" is installed correctly and being used correctly because when "hx-target" is removed from the "button", then "hx-target-error" works. Error generation in views.ph @login_required def endpoint(request) return HttpResponseNotFound("Not found 404") Logs Bad Request: /testbed/endpoint/ 127.0.0.1 - [27/Feb/2024] "GET /testbed/endpoint/ HTTP/1.1" 400 response-targets extension https://htmx.org/extensions/response-targets/ -
Could anyone tell me the step by step process to implement this project?
𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 : Language translator tool to convert English to Hindi (official Language) which can be used by all the government organizations websites officially. 𝗗𝗲𝘀𝗰𝗿𝗶𝗽𝘁𝗶𝗼𝗻 : The objective is to develop a language translator tool specifically designed for government organizations in India. The tool should provide the capability to translate English content into Hindi, the official language of the country. This will enable government websites to cater to a wider audience, including Hindi-speaking citizens who may have difficulty understanding English. The language translator tool should possess the following key features: Translation Accuracy: The tool should offer accurate translations, maintaining the context and meaning of the original English content. It should handle various language intricacies, idiomatic expressions, and technical terms commonly used in government-related documents. User-Friendly Interface: The tool should have a simple and intuitive interface, ensuring ease of use for both website administrators and end-users. It should seamlessly integrate into government websites, allowing users to translate content with minimal effort. Website Integration: The language translator tool should be compatible with different website architectures and frameworks commonly used by government organizations. It should provide developers with an API or plugin that can be easily integrated into existing websites without significant code … -
Joining Tables in Django ORM with Left Outer Join and Additional Condition
I'm trying to perform a left outer join between two models in Django using the ORM. I need to include an additional condition within the ON clause of the join to filter the results based on specific criteria. from django.db import models class Author(models.Model): id = models.BigIntField(primary_key=True) name = models.CharField(max_length=50) book_title = model.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, db_column='author') Is there a way to retrieve all the book objects along with the name of the author where the title and book_title are equal. The sql will look like: select title, author, name as author_name from book left outer join author on (book.author = author.id AND book.title = author.book_title) Since the table is very large ( 13m ) I cannot resort to raw query because I will lose the ability to use PageNumberPagination. I don't want to use extra because this may lead to problems in future. Is there any other way I can achieve the above sql using django orm?? -
Django project deployment on Vercel got me an error
I have created a simple blog application using django and postgres database. While I wants to deploy to vercel it throws a different errors like this error error How can i solve this error? build_files.sh pip install -r requirements.txt python3.10 manage.py collectstatic vercel.json { "version": 2, "builds": [ { "src": "blog/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.10" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "blog/wsgi.py" } ] }``` I have build_files.sh and vercel.json. I think there is no problem. I also have requirements.txt file. Pushed to github and tried deployment but no progress at all. -
django.core.exceptions.FieldDoesNotExist: Document has no field named 'header'
So, i am trying to add parler to my models in order to translate them. models.py from django.db import models from django.utils.translation import gettext_lazy as _ from ckeditor.fields import RichTextField from parler.models import TranslatableModel, TranslatedFields from simple_history.models import HistoricalRecords class Document(TranslatableModel): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' translations = TranslatedFields( header=models.CharField(_("Header"),max_length = 32), body=RichTextField() ) category = models.ForeignKey(Category, on_delete = models.CASCADE) timestamp = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE) history = HistoricalRecords() def __str__(self): return self.header so basically it says that it has no header field, but when i add it outside of the translations it says that it ALREADY HAS header field. How do i fix it? -
Some example schemas on swagger not displaying
New over here.. Has anyone encountered a problem that occurs in swagger where it shows some specific number of urls with their properties and example schemas. While for the rest it just gives the default value "string". E.g If I have a total of 70 urls for the first 30 urls it gives the accurate example schemas while for others it just gives "string" as the example schema My swagger UI The "string" Example value then shows up for all urls after the api/user/verify I have tested both drf_yasg and drf-spectacular but got the same result -
Django order by number of related objects in class Meta
In Django, i want to set the default model ordering to be by the number of related objects. In my case i would like to order the objects by the number of likes, where likes is a ManyToManyField of users that have liked the post: class Post(models.Model): likes = models.ManyToManyField(User) class Meta: ordering = [] # What can i put here? The common solution seems to be django aggregation: from django.db.models import Count top_posts = Post.objects.annotate(num_likes=Count('likes')).order_by('-num_likes') But this is called on the queryset, and doesn't seem like an option when defining the model. -
How do I resolve "Serverless Function has exceeded the unzipped maximum size of 250 MB" error on Vercel?
I have a personal project that I am building in Python using Django. When deploying it to Vercel, it worked fine until eventually the amount of libraries that I imported (included in my requirements.txt file) became too large, I assume, and now I face the "Serverless Function has exceeded the unzipped maximum size of 250 MB" error. The library that takes up the most space is Wordcloud (and botocore / boto3). Surely there must be a way around this? As far as I'm aware, paying for a higher tier of Vercel will not resolve this issue. Is there any workaround to this issue, or is the best option to just use a different service other than Vercel? This is my requirements.txt: Django==4.2.8 psycopg2-binary==2.9.8 Pillow==8.2.0 django-storages==1.14.2 boto3==1.34.4 botocore==1.34.4 Pyrebase4==4.7.1 regex==2020.11.13 python-dateutil==2.8.2 textblob==0.17.1 nltk==3.6.3 json5==0.9.14 jsonpath-ng==1.5.3 jsonpointer==2.4 jsonschema==4.19.0 jsonschema-specifications==2023.7.1 wordcloud==1.9.2 matplotlib==3.7.2 matplotlib-inline==0.1.6 Obviously when I remove the libraries from my project that takes up the most space, it does build successfully. So the problem is not with my code itself, and it does build and start up successfully when I open a local instance. I'm still relatively new with Python, so I would appreciate any help, even if it is "basic" - … -
hello I’ve got big problem when I open my site I’ve got “SyntaxError at / invalid syntax (views.py, line 78)” for review
It does not tell me which of my views has this problem. It is strange that there is no problem in http://127.0.0.1:8000/, but there is a problem in the host I bought. I have also talked to the support and they said that it is a python problem and you have to solve this problem with a python programmer here is my project, accounts and blog app views: `from django.shortcuts import render,get_object_or_404,redirect from blog.models import Post from django.utils import timezone from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from blog.models import Comment from blog.forms import CommentForm from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect def blog_view(request,kwargs): posts=Post.objects.filter(status=1,published_date__lte=timezone.now()) if kwargs.get('cat_name')!=None: posts=posts.filter(category__name=kwargs['cat_name']) if kwargs.get('author_username')!=None: posts=posts.filter(author__username=kwargs['author_username']) if kwargs.get('tag_name')!=None: posts=posts.filter(tags__name__in=[kwargs['tag_name']]) posts=Paginator(posts,4) try: page_number=request.GET.get('page') posts=posts.get_page(page_number) except PageNotAnInteger: posts=posts.get_page(1) except EmptyPage : posts=posts.get_page(1) # return render(request, 'blog/post_detail.html', {'post': post}) # posts=Post.objects.filter(status=0) context={'posts':posts} return render(request,'blog/blog-home.html',context) def blog_single(request,pid): if request.method=='POST': form =CommentForm(request.POST) if form.is_valid(): form.save() messages.add_message(request,messages.SUCCESS,"your comment submited") else: messages.add_message(request,messages.ERROR,"your comment didnt submited") post = get_object_or_404(Post,pk=pid,status=1,published_date__lte=timezone.now()) post.counted_views += 1 post.save() previous_post = Post.objects.filter(id__lt=pid,status=1,published_date__lte=timezone.now()).order_by('-id').first() next_post = Post.objects.filter(id__gt=pid,status=1,published_date__lte=timezone.now()).order_by('id').first() if not post.login_require: comments=Comment.objects.filter(post=post.id,approved=True).order_by('-created_date') form=CommentForm() context={'post':post,'previous_post': previous_post,'next_post': next_post,'comments':comments,'form':form} return render(request,'blog/blog-single.html',context) else: return HttpResponseRedirect(reverse('accounts:login')) def blog_category(request,cat_name): posts=Post.objects.filter(status=1) posts=posts.filter(category__name=cat_name) context={'posts':posts} return render(request,'blog/blog-home.html',context) def blog_search(request): posts=Post.objects.filter(status=1,published_date__lte=timezone.now()) # print(request.__dict__) if request.method=='GET': # print(request.GET.get('s')) if s:=request.GET.get('s'): **that's … -
How to make an ajax jquery request to get data from a Django ListView?
I have a base template in which I have a header and in that header, there are some link buttons that I would like to change the appearance of when clicked, for this it would be necessary to use ajax to avoid reloading the page. The request must be a GET to display the updated page data. That is, the ajax script must be done in my base.html at the button click event, to load the template that extends the base. Right? The view: class HomeListView(ListView): model = Cars template_name = 'cars.html' context_object_name = 'cars' def get_queryset(self): cars = super().get_queryset().order_by('model') return cars The data in the template cars.html (which extends base.html) is processed in this way: <div class="car-grid"> {% if cars %} {% for car in cars %} <div class="car-card"> <img src="{{ car.photo.url }}" alt="{{ car.model }} - {{ car.brand }}"> <h2> {{ car.brand }} {{ car.model }} </h2> <p> {{ car.factory_year }} - $ {{ car.value }} </p> </div> {% endfor %} {% else %} <p class="no-results">No results found. </p> {% endif %} </div> What is the smartest way to make this ajax request to get the updated cars context variable? Is there any way to pass it to … -
How to create a Django queryset based on values of recursive ManyToManyField?
I have a dictionary app where words (Lemma) can be optionally composed of other words. In my models.py, this looks like: cf = models.CharField(max_length=200) #citation form pos = models.ForeignKey(Pos, on_delete=models.CASCADE) #part of speech components = models.ManyToManyField("self", symmetrical=False, blank=True) #component Lemma I want to return two query sets: All compound verbs: Lemma that have values in self.components and where self.pos.term="verb" All unique components of compound verbs that are nouns: Lemmas that are values of some other Lemma's self.component_set() and which themselves have self.pos.term="noun". I want to use views to pass these two lists to a template. I'm able to get queryset 1 pretty easily, but my solutions for queryset 2 are all quite convoluted. The relevant class in my views.py looks like this: model = Lemma queryset = Lemma.objects.filter( Q(pos__term="verb") & ~Q(components=None) ).order_by("cf") #queryset 1, compound verbs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) nouns = self.queryset.values_list("components") nouns = set([Lemma.objects.get(pk=l[0]) for l in nouns]) nouns= [l for l in nouns if l.pos.term == "noun"] context["nouns"] = nouns #queryset 2, nouns that are components of compound verbs return context This also leaves me with a regular list for my verbs variable rather than a proper queryset where I can use the .order_by() method … -
when creating zoom i am getting invalid access token error when my keys are valid
import requests import json API_KEY = 'API KEY' API_SEC = 'SECRET KEY' zoom_api_url = 'https://api.zoom.us/v2/users/me/meetings' meeting_details = { "topic": "The title of your Zoom meeting", "type": 2, "start_time": "2024-02-27T10:00:00", "duration": "45", "timezone": "Europe/Madrid", "agenda": "Test Meeting", "settings": { "host_video": "true", "participant_video": "true", "join_before_host": "False", "mute_upon_entry": "False", "watermark": "true", "audio": "voip", "auto_recording": "cloud" } } headers = { 'Content-Type': 'application/json', } auth = (API_KEY, API_SEC) response = requests.post(zoom_api_url, headers=headers, auth=auth, data=json.dumps(meeting_details)) print(response.json()) after I am getting access token but its saying invalid access token i have added keys and allowed authentication on zoom i have tested it with postman as well as through my django app From every platform i am getting same error ** Invalid Access Token** I tried to create access with jwt.io too but still its not working if anyone can help what is wrong? -
How can I assign a url to a button that redirect users to an external website when the data is split up into two data frames?
I have function in my view that fetches data from multiple spreadsheets and normalizes said data into one single data frame via Pandas. This df1 is eventually rendered and displayed in a webapp in the form of a bootstrap table using Django. For the sake of simplicity, let’s say this table has two columns: “Games” and “Link”. “Games" shows all the soccer matches for today and “link” simply has a button for each of the games. This button does nothing for now. Now, I have another function that fetches data from a different source and again, normalizes the data using Pandas creating a df2 with three columns: “Games”: shows some soccer matches for today (this column has some but not all the games in df1 with exactly the same format). “Id”: a 4-digit identifier that is unique to each of the games above. “Url”: a url that contains the “id” and redirects the user to an external website that provides the user with extra information about that particular match. I’m trying to figure out a way where the users can click on the buttons available in the webapp (which are linked to the games in df1) and get redirected to … -
Django display DateFormat as dd/mm/yyyy
I have a form in Django where the user needs to select the date. When the user selects the date the date is displayed in the following format mm/dd/yyyy (eg. 02/29/2024). I want the date in the form to be displayed as dd/mm/yyyy (eg. 29/02/2024 ). This is the date field in my form: date = forms.DateField( widget=forms.DateInput(format='%d/%m/%Y', attrs={'type': 'date', 'min': str(timezone.now().date()), 'max': str((timezone.now() + timedelta(days=365)).date())}), help_text='Select a date', input_formats=['%d/%m/%Y'], validators=[validate_future_date], ) I also tried: In settings.py: DATE_INPUT_FORMATS = ('%d-%m-%Y',) USE_I18N = True USE_L10N = True In the form: input_formats=settings.DATE_INPUT_FORMATS, After both of these approaches the format was still displayed as dd/mm/yyyy. -
Django View to return template with refreshed modal window
I'm using Django form in modal window where core content (in container) generated by JS. On submit django model instance saved without any issues if form.is_valid() == True a modal window closes with switching focus on current background page. However if form.is_valid() == False the modal content just opens in separate URL instead and takes all browser screen as View renders just a short code fragment in .html file. The goal is to refresh the modal window on current condition in case if form_is_valid() == False with form errors. Template "accounts/profile_settings.html" contains a form and submit button which renders inside <div class="preferences_content"> {% comment %} JS generated dynamic content depends on tab pressed. {% endcomment %} </div> My JS knowldge is very basic so I appreciate any suggestion on this topic. The View : def profile_update_view(request): """ Updates current Profile instance.""" if request.method == "POST": current_profile = request.user.profile profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=current_profile) if profile_form.is_valid(): profile_form.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', "/")) else: profile_form = ProfileUpdateForm() return render(request, "accounts/profile_settings.html", {'profile_form': profile_form}) else: profile_form = ProfileUpdateForm() return render(request, "accounts/profile_settings.html", {'profile_form': profile_form}) document.addEventListener("DOMContentLoaded", function() { var openModalLink = document.getElementById("openPreferencesModal"); var modal = document.getElementById("preferencesModal"); var span = modal.querySelector(".close"); var preferencesContent = modal.querySelector(".preferences_content"); var tabs = modal.querySelectorAll(".tab"); … -
Django losing session state?
I have a VPS running apache. Apache is serving two domains, my homepage (django, django-cms, zinnia) and a prod site (django, oscar). I use falkon browser. When I change the items in site's admin (I change values in a row, it's list_editable, and then click Save), sometimes (quite often), the response returned is a redirect to login, as if the session cookie is not passed. What is interesting, if I save the POST request as curl and retry it, it succeeds. Since there are several redirects after I hit save, I've seen it failing on the first one (so the item is not saved), or the second one (the item is therefore saved, but I find myself not on the list page, but on the main admin page). How do I debug it? I suspect it may be a browser issue, I'll try mitmproxy now to see what's really hitting the network. But maybe someone has seen this behaviour before. -
Migrate project from Django 1.8 to 1.11 and TemplateDoesNotExist at /accounts/login/
i am beginner in Python and Django. I must update project from Django 1.8 to 1.11 (and in past to 2,3,4). I make update my requirements file and pip. When I write in WSL: ./.venvs/bin/python3 manage.py runserver I have error i browser: TemplateDoesNotExist at /accounts/login/ _accounts/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 1.11 Exception Type: TemplateDoesNotExist Exception Value: _accounts/login.html my urls.py: from django.conf import settings from django.views.generic.base import TemplateView from django.conf.urls import include, url from django.contrib.auth.views import login from go.accounts.decorators import check_login_abuse from go.accounts.forms import AuthenticationForm, PasswordResetForm from go.insurance.views import index urlpatterns = [ url(r'^$', index), url(r'^accounts/login/$', check_login_abuse(login), {'template_name': 'accounts/login.html', 'authentication_form': AuthenticationForm}), url(r'^accounts/logout/$', logout, {'template_name': 'accounts/logout.html'}), ] How can i repair this problem? I use Python 3.8 -
Static files on EC2 instance, AWS
I recently deployed my project to an Ubuntu EC2 instance and I noticed that the static files (css) don't seem to be loading(same with the images from sqLite3-database). For my website I use django: What I'm getting: When I enter my website, my css and media doesn't load. What's more I can't access one of my slug-pages, because I always get 500 bad request: [27/Feb/2024 09:53:36] "GET /about-me/ HTTP/1.1" 500 145 [27/Feb/2024 09:53:58] "GET / HTTP/1.1" 200 12343 [27/Feb/2024 09:53:58] "GET /static/css/home.css?%201709027638 HTTP/1.1" 404 179 [27/Feb/2024 09:53:58] "GET /media/images/Crawler_Post_Picture.png HTTP/1.1" 404 179 *my setup: ├── core ├── db.sqlite3 ├── home ├── manage.py ├── media ├── requirements.txt ├── static ├── staticfiles ├── templates └── venv What I've already tried: collectstatic migrate change my settings.py into: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' 5)urls.py: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) add this in my homepage.html template <head>: <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}?{% now " U" %}" /> I'm a newbie, so thanks in advance!