Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload profile picture in Django using bootstrap modal
I am doing a web app project where users can update profile picture and their firstname, lastname, bio, url and username. I am using bootstrap 4 modal in the user_update.html for the profile picture update implementation. user_update.html {% extends 'users/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block maincss %} <link rel="stylesheet" type="text/css" href="{% static 'users/stylesheet/main.css' %}"> {% endblock maincss %} {% block updateprofilecontent %} <main role="main" class="container"> <div class="row"> <div class="col-md-8"> <div class="content-section"> <div class="media"> <a href="#" data-toggle="modal" data-target="#profilePicModal"> <img class="rounded-circle account-img" src="{{ user.profile_picture.url }}"> </a> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Edit Profile</legend> {{ u_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> </div> </div> </main> <!-- Modal --> <div class="modal fade" id="profilePicModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Choose Profile Picture</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ p_form|crispy }} </div> </div> </div> </div> {% endblock updateprofilecontent %} urls.py from django.contrib import admin from django.urls import path from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path('user/update/', user_views.userUpdate, name='user-update'), ] if settings.DEBUG: urlpatterns += … -
How to upload profile picture in Django using bootstrap modal
I am doing a web app project where users can update profile picture and their firstname, lastname, bio, url and username. I am using bootstrap 4 modal in the user_update.html for the profile picture update implementation. user_update.html {% extends 'users/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block maincss %} <link rel="stylesheet" type="text/css" href="{% static 'users/stylesheet/main.css' %}"> {% endblock maincss %} {% block updateprofilecontent %} <main role="main" class="container"> <div class="row"> <div class="col-md-8"> <div class="content-section"> <div class="media"> <a href="#" data-toggle="modal" data-target="#profilePicModal"> <img class="rounded-circle account-img" src="{{ user.profile_picture.url }}"> </a> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Edit Profile</legend> {{ u_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> </div> </div> </main> <!-- Modal --> <div class="modal fade" id="profilePicModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Choose Profile Picture</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ p_form|crispy }} </div> </div> </div> </div> {% endblock updateprofilecontent %} urls.py from django.contrib import admin from django.urls import path from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path('user/update/', user_views.userUpdate, name='user-update'), ] if settings.DEBUG: urlpatterns += … -
How to make case-insensitive serach to Cyrillic letters django
I tryid to create search in django and make it case-insensitive. I created it, but it doesn't work with cyrillic (russian) letters. # views.py class QuestionsAPIView(generics.ListCreateAPIView): search_fields = ['name_tm', 'name_ru', 'name_en'] filter_backends = (filters.SearchFilter,) queryset = Product.objects.all() serializer_class = ProductSerializer # urls.py urlpatterns = [ path('', views.QuestionsAPIView.as_view()), ] With latin letter it works: But with russian letter not works: -
Django Bad request error when trying to log in
I created a LoginAPIView in my django project and it works as intended but it says "Bad Request: /login/" and I'm worried since it may cause some problems in the future. views.py: class LoginAPIView(generics.CreateAPIView): permission_classes = (AllowAny,) serializer_class = LoginAPISerializer http_method_names = ['get', 'post'] def get(self, request, format=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) def post(self, request, format=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) serializer.py: class LoginAPISerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() http_method_names = ['get', 'post'] def validate(self, data): username = data.get('username') password = data.get('password') if not username or not password: raise serializers.ValidationError('Username and password are required') user = authenticate(username=username, password=password) if not user: raise serializers.ValidationError('Invalid credentials') data['user'] = user return data def create(self, validated_data): user = validated_data['user'] token, created = Token.objects.get_or_create(user=user) return {'token': token.key} I looked up for solutions but I couldn't find one. Please help, thanks. -
What is the name of Django application's default server(Built in server)?
I am writing a synopsis for one of the Academic Django project, which is going to run on localhost(no deployment). Now, in synopsis I want to mention server name. I know Django has built in server, what is the name of that server? can anyone sort it out? Thank you. -
OpenSearch connection times out with Django using docker containers
I'm trying to figure out why my docker container running Django times out when trying to communicate with a docker container running OpenSearch. I'm testing out DigitalOcean for containerising my web services. It's set to use 2x vCPUs and 4GB RAM. The Django app container is using gunicorn which is accessed via an nginx reverse proxy. The OpenSearch container is launched via the developer docker compose file provided on their website. If I launch all containers, all Django's pages that don't require any interaction with the django-opensearch-dsl package load and operate fine. I can also launch a Django shell and query the database etc. If I try to run an OpenSearch related command though, such as trying to create an index, it will timeout. For example, running docker exec -it myapplication-webapp python manage.py opensearch index create results in Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn conn = connection.create_connection( File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection raise err File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection sock.connect(sa) TimeoutError: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py", line 398, in _make_request conn.request(method, … -
How to let the users download JSON & CSV File in django?
On my Django project, I have scraped data in a JSON & CSV format. I want to let the users download the JSON and CSV files. The below code generates the files in my django project directory. views.py final = json.dumps(sorted_result, indent=2) with open("webscraping_dataset.json", "w") as outfile: outfile.write(final) df = pd.DataFrame({"Name": name, "Price": price, "URL":URL}) df.to_csv("data.csv") How should I implement it in my Django project so that the users can download those files? Thanks. -
When Django is started by uWSGI, it does not write logs to the log file
I started Django by the command python manage.py runserver. Django wrote logs to the file my_django_project/log/django.log. So far so good. I started Django by the command uwsgi --ini uwsgi.ini. I expected Django write logs to the file my_django_project/log/django.log. It created the file, but did not write any content to it. I have the following setup for my Django project named my_django_project. Project layout: - my_django_project/ - uwsgi.ini - manage.py - my_django_project/ - __init__.py - settings.py - wsgi.py - log/ - django.log settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "[{asctime}] [{name}] [{levelname}] [{filename}:{funcName}:{lineno}] {message}", 'datefmt': "%Y-%m-%d %H:%M:%S", "style": "{", }, }, "handlers": { "console": { 'level': 'DEBUG', "class": "logging.StreamHandler", "formatter": "verbose", }, "django_file": { "level": "DEBUG", "class": 'logging.handlers.RotatingFileHandler', "formatter": "verbose", "filename": "log/django.log", 'maxBytes': 10 * 1000 * 1000, # 10 MB 'backupCount': 3, }, }, "loggers": { "django": { "handlers": ["console", "django_file"], "level": "DEBUG", }, }, } wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_django_project.settings') application = get_wsgi_application() uwsgi.ini: # uwsgi.ini file [uwsgi] module=my_django_project.wsgi master=true processes=1 http=:8000 vacuum=true pidfile=/tmp/project-master.pid logto=./log/uwsgi.log log-maxsize=10000000 enable-threads=true thunder-lock=true uwsgi.log (replaced some private information with XXXX): *** Starting uWSGI 2.0.21 (64bit) on [Sun Apr 9 12:35:36 2023] *** compiled with … -
How do I create a specific version of Django Project in Pycharm( virtual environment)
such as My Python is 3.6.8,I want to create Django 1.11.8 project In virtual environment?How should I do? Used virtualenv 1、I create Django Project Under virtual environment in Pycharm,the Django version is auto latest 2、I try Create Django Project by Bash line,but when I open the Project by Pycharm,that is not in virtual environment -
Django User Panela as Django Admin?
Django has a powerfull Admin resource, its amazing and fast to create and teste the models. We have some similar resource that allow us to generate an User app fast like as in admin panela? I quanto know If haver a fazer way tô create our app as Django admin -
Railway app production isnt working: Csrf post error when i try to sign in when it works perfectly locally
On a local server, my webapp was working perfectly, but in production i get a csrf post error whenever I try to sign in or register. In settings i have 'django.middleware.csrf.CsrfViewMiddleware' in my settings.py file, and i have these: {% csrf_token %} In my HTMLs. I have tried pretty much every suggestion I have seen and cannot seem to get it working. Any thoughts? I tried adding all of these suggested by other posts i have seen : ALLOWED_HOSTS = ["*"] CSRF_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_DOMAIN = 'mydomainname' CSRF_COOKIE_NAME = "csrftoken_custom" SESSION_COOKIE_SAMESITE = 'Lax' CSRF_COOKIE_SAMESITE = 'Lax' CSRF_TRUSTED_ORIGINS = ['*'] and the same error kept coming. -
multiple models to one manytomanyfield table
I have two apps Levels, Classes with Many To Many Relationships, Levels can have many Classes, and Classes can have many Levels. How can I do that? I tried: levels/models.py class Level(models.Model): name = models.CharField(max_length=50) classes = models.ManyToManyField(ChildClass, related_name='childclass', blank=True,db_table='level_class', primary_key=False) child_class/models.py class ChildClass(models.Model): name = models.CharField(max_length=50) levels = models.ManyToManyField('level.Level', related_name='childclass',db_table='level_class') Returns (Error) child_class.ChildClass.levels: (fields.E340) The field's intermediary table 'level_class' clashes with the table name of 'level.Level.classes'. level.Level.classes: (fields.E340) The field's intermediary table 'level_class' clashes with the table name of 'child_class.ChildClass.levels'. -
White screen after installing django-unfold
I got a problem, it's with JS which we got with the package or with me, which made a mistake on django-side, i'm not sure. I have installed the django-unfold package using "pip install django-unfold" and added it to my INSTALLED_APPS list as follows: INSTALLED_APPS = [ "unfold", "unfold.contrib.filters", "unfold.contrib.forms", # "nested_admin", 'django.contrib.admin', # base 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # project apps 'work', # third-party-apps 'rest_framework', 'djoser', # 'corsheaders', 'django_filters', ] I have also made some changes to my admin.py as shown below: from unfold.admin import ModelAdmin @admin.register(Genre) class GenreAdmin(ModelAdmin): pass However, when I try to access the admin page at /admin/, I am presented with a white screen. Upon checking the console, I found the error message "Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" in the alpine.persist.js file. I am not proficient in JS but I find the code in this file difficult to understand. Therefore, I asked ChatGPT to make the code in alpine.persist.js more descriptive. The updated code is shown below: (() => { function persistPlugin(alpineInstance) { let createPersistInterceptor = () => { let key, storage = localStorage; return alpineInstance.interceptor( (componentState, getState, setState, propName, uid) => { let stateKey … -
Django unit testing imagefield error using SimpleUploadedFile
This is the tests.py class ArticleModelTestCase(TestCase): def setUp(self): self.article = Article.objects.create( title = 'Title test.', content = 'Content test.', date_posted = timezone.localtime(), image = SimpleUploadedFile( name = 'test_image.jpg', content = b'', content_type = 'image/jpeg' ) ) def test_title(self): self.assertEqual(self.article.title, 'Title test.') def test_content(self): self.assertEqual(self.article.content, 'Content test.') def test_image_field(self): self.assertEqual(self.article.image.name, 'test_image.jpg') and I got this error Creating test database for alias 'default'... System check identified no issues (0 silenced). .F. ====================================================================== FAIL: test_image_field (articles.tests.ArticleModelTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/xxx/projects/xxxx/backend/articles/tests.py", line 27, in test_image_field self.assertEqual(self.article.image.name, 'test_image.jpg') AssertionError: 'article_images/test_image_7U9qlax.jpg' != 'test_image.jpg' article_images/test_image_7U9qlax.jpg test_image.jpg ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=1) Destroying test database for alias 'default'... What happen is that the SimpleUploadedFile not only created a 'test_image.jpg' but it created 3 files of: test_image.jpg test_image_CWK5SDf.jpg test_image_7U9qlax Everytime I ran the test it will always created 3 image files with a random words and number as the suffix after 'test_image' Why does this happen? and how to fix this? Thanks -
How do I fix the return type of a Django model manager's method?
I'm using Django 4.1.7 with django-stubs 1.16.0, and mypy 1.1.1. I have code that looks like this: class ProductQuerySet(QuerySet): ... class ProductManager(Manager): def create_red_product(self, **kwargs) -> "Product": return self.model(color=Product.Color.RED, **kwargs) _product_manager = ProductManager.from_queryset(ProductQuerySet) class Product(Model): ... objects = _product_manager() When mypy looks at this, it says: models/product.py:46: error: Incompatible return value type (got "_T", expected "Product") [return-value] It seems like the type of self.model in a model manager method is _T, which from what I understand is a generic type bound to the model, which in my case should be "Product". Why isn't this working? How can I fix it? -
How do I type a custom User model manager for mypy in Django?
I'm using Django 4.1.7 with django-stubs 1.16.0. I created a custom user manager for my User model like this: from django.contrib.auth.models import UserManager class MyUserManager(UserManager): def delete_test_data(self): return self.filter(test_data=True).delete() class User(AbstractUser): test_data = models.BooleanField() ... objects = MyUserManager() Everything works as expected, but when I run mypy on this, it complains with: models.py:32: error: Incompatible types in assignment (expression has type "MyUserManager[User]", base class "AbstractUser" defined the type as "UserManager[AbstractUser]") [assignment] Am I doing something wrong? Is this a mypy bug? Bad types defined in django-stubs? Is there a way to type this without forcing mypy to ignore it? -
How to make bootstrap navlink active in dynamically generated for loop in django template
I am trying to make a tag navlink active in for loop django template. Every link is passing id, base on id matching i would like make nav-link active. This is my Template html page, this is for loop and here i am checking condition to make nav-link active. I am not able to highlight the nav-link. <ul class="nav nav-pills" role="tablist"> <li class="nav-item"> <a class="nav-link"href="{% url 'core_app:store' 'all' %}">All</a> </li> {% for type in store_type %} {% if type.id == typeid %} <li class="nav-item"> <a class="nav-link active" href="{% url 'core_app:store' type.id %}">{{type.name}}</a> </li> {% else %} <li class="nav-item"> <a class="nav-link"href="{% url 'core_app:store' type.id %}">{{type.name}}</a> </li> {% endif %} {% endfor %} </ul> This is my View code Here i am getting all store_type and base on link click and passing id and i am extracting type of store. Then i would like to highlight my nav-link active base on conditional matching def store(request, id): if id == "all": store_list = Store.objects.all().order_by('id') else: store_list = Store.objects.all().filter(store_type=int(id)).order_by('id') return render(request, 'core_app/store/all_store.html', {'stores': store_list, 'typeid': id, "store": "active", 'store_list': 'active', 'store_type': StoreType.objects.all()}) Model (Store has StoreType) class StoreType(models.Model): name = models.CharField(max_length=255, blank=True, null=True) ... def __str__(self): return self.name class Store(model.Model): store_type = models.ForeignKey(...) name … -
Failed to compute cache key
A error is showing in my code: [+] Building 10.0s (7/9) => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 518B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 218B 0.0s => [internal] load metadata for docker.io/library/python:3.9-alpine3.13 9.9s => CANCELED [1/5] FROM docker.io/library/python:3.9-alpine3.13@sha256:a7 0.0s => => resolve docker.io/library/python:3.9-alpine3.13@sha256:a7cbd1e7784 0.0s => => sha256:a7cbd1e7784a35a098cedbc8681b790d35ff6030a5e 1.65kB / 1.65kB 0.0s => => sha256:ec5c85c9adb18db9c7204b674ee8ec4ae5268a7996c 1.37kB / 1.37kB 0.0s => => sha256:77dca58f10dd82e74ddf80f3382c327a4b61c7dee3a 7.43kB / 7.43kB 0.0s => [internal] load build context 0.0s => => transferring context: 74B 0.0s => CACHED [2/5] COPY ./requirements.txt /tmp/requirements.txt 0.0s => ERROR [3/5] COPY ./app /app 0.0s ------ > [3/5] COPY ./app /app: ------ failed to solve: failed to compute cache key: "/app" not found: not found How to resolve this error while running docker-compose build on terminal on macOS? This is my Docker file: FROM python:3.9-alpine3.13 LABEL maintainer="DV" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user This is my docker-compose.yml file: version: "3.9" services: app: … -
Need recommendation Python stack for a web application
Here is a short description a web application: Users will be able to authorize to app through social media accounts. The web app will get users' posts from social media platforms by API. It will look like a table with users' posts with different data. Users will be able to choose posts and remove them in bulk. Features: search posts by keyword, filter by date and media type, and sort new and old. Happy to hear any suggestions. I don't know what stack is best for my web application. -
X.MultipleObjectsReturned: get() returned more than one X -- it returned X
I have a model, Chapter, linked to the Book model through a ForeignKey. One of it's fields, the integer field, number, is "slugified" to make the slug field, chapter_slug. The problem is my DetailView. When I call it the error "raise self.model.MultipleObjectsReturned(books.models.Chapter.MultipleObjectsReturned: get() returned more than one Chapter -- it returned 2!" That happens when I have more than one chapter 1, in this case, in two different books. class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.PROTECT) number = models.IntegerField(default=1) name = models.CharField(max_length=200, blank=True) chapter_slug = models.SlugField(null=True) ... def get_absolute_url(self): return reverse('chapter', kwargs={'book_slug': self.book.book_slug, 'chapter_slug': self.chapter_slug}) def save(self, *args, **kwargs): if not self.chapter_slug: self.chapter_slug = slugify(self.number) return super().save(*args, **kwargs) ... path('book/<slug:book_slug>/chapter/<slug:chapter_slug>/', views.ChapterView.as_view(), name='chapter'), class ChapterView(DetailView): model = Chapter template_name = books/chapter.html' context_object_name = 'chapter' slug_field = 'chapter_slug' slug_url_kwarg = 'chapter_slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) chapter = self.get_object() context['book_slug'] = chapter.book.book_slug context['chapter_slug'] = chapter.chapter_slug ... [08/Apr/2023 15:43:03] "GET / HTTP/1.1" 200 79 Not Found: /favicon.ico [08/Apr/2023 15:43:03] "GET /favicon.ico HTTP/1.1" 404 9214 [08/Apr/2023 15:43:14] "GET /book/example/chapter/1 HTTP/1.1" 301 0 Internal Server Error: /book/example/chapter/1/ Traceback (most recent call last): File "/home/user/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/user/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.local/lib/python3.10/site-packages/django/views/generic/base.py", line … -
How to increase the loading speed of database in django?
I've build this website https://hanjaba.com/ using django and supabase as the database. However the loading speed website seems to be very slow when it have to retrieve data from the database and loads the static pages quite fast. How can I increase the loading speed of the database? -
Why my code for displaying user profile in Django isn't working?
I'm learning Django and I'm making a website that includes registering and creating your own profile. When you're logged in you can view other users profiles and by clicking on their picture it redirects you to their profile site. The problem is: the picture redirects you to the right url but it shows base template rather than the one that I want I checked some websites and even chat gpt for help but it wasn't successful I'll only show important parts of my code but if sth missing just let me know and I'll add it. Here's the code for 'urls.py': from django.urls import path from . import views from django.views.generic.base import RedirectView from django.templatetags.static import static app_name = 'app' urlpatterns = [ path('', views.index, name='index'), path('profile/', views.profile, name='profile'), path('profile_list/', views.profile_list, name='profile_list'), path('user_profile/<int:user_id>/', views.user_profile, name='user_profile'), ] 'views.py' from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import login, logout, authenticate from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required from django.urls import reverse from django.contrib import messages from .forms import RegisterForm, UserProfileForm, MessageForm from .models import UserProfile, Message from django.contrib.auth.models import User def index(request): return render(request, 'base.html') @login_required def profile(request): user_profile = UserProfile.objects.get(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance=user_profile) … -
Django login - Preserve the 'next' parameter in the URL when the login form submission fails
I am using Django LoginView to render login form and handle the login action. Sometimes the login url has a next parameter. If the user enters wrong username and password, then it is again redirected to the login page but the url should preserve the next parameter. But I am not able to achieve it. class CustomLoginView(LoginView): ''' After successful login, django auth view should redirect the user to the next GET param Ref: python - Django built in login view not redirecting to next https://stackoverflow.com/questions/50542035/python-django-built-in-login-view-not-redirecting-to-next ''' def get_success_url(self): next_page = self.request.POST['next'] if next_page == '': next_page = '/' # if next param is not available, then redirect the user to the homepage after login. return next_page def form_invalid(self, form): response = super().form_invalid(form) next_url = self.request.GET.get('next') or self.request.POST.get('next') if next_url: response['Location'] = f"{self.request.path}?next={next_url}" return response I was expecting the form_invalid method to preserve the next param in the url but it's not happening. I think setting response['Location'] variable in the form_invalid method is not the right way. Looking forward towards some help. -
Django: How to create "Published" and "Last edited" fields?
I'm writing a blog for my portfolio and I wanna compare (in the Django template) the date I published an article with the date I edited it in order to display the "Edit date" only if it was edited before. The problem is: I don't wanna test for every single date field, like year, month, day, hour, minute, etc., but if I simply compare the two values, it'll always display both values, since the time precision goes beyond seconds, making the dates different even though I never edited that particular post. TL;DR How to compare dates when their values will always differ, given the precision Django takes time, without using an iffor every value (year, month, day, hour, minute, second)? What I tried: I successfully accomplished solving my main problem, but my code looks something like if this == that and if this == that etc.. It doesn't look pretty and I don't wanna code this for every website I build. It looks like there's a better way to solve it. -
custom domain from godaddy through cloudflare to ec2 instance
im trying to set up my first propper custom domain. heres what ive done. on godaddy i have deleted all of my dns records and pointed to cloudflares name servers on cloudflare i have set up an a record to my ec2 instance with my custom domain i bought on godaddy i still cant connect to my ec2 instance with my custom domain but can with my ec2's ip address all of the tutorials i find about this stuff involve route 53 rather than cloudflare. must i use route 53? what am i doing wrong/ what else should i try / investigate? how could i make this work? below is some evidence for what ive done.