Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images not displaying on my Website and PostgreSQL database that is hosted on Railway in Django app
I have a Django app with a PostgreSQL database hosted on Railway. I am able to retrieve and display all data from the database on my website except for images. Here is my relevant code: # views.py @csrf_exempt def addpost(request): if request.method == "POST": title = request.POST['title'] content = request.POST['content'] author = request.POST['author'] date = request.POST['date'] categories = request.POST['categories'] upload = request.FILES.get('image') newpost = NewPost( title=title, content=content, author=author, publication_time=date, categories=categories, image=upload ) newpost.save() return render(request, "addpost.html") # models.py class NewPost(models.Model): title = models.CharField() content = models.TextField() author = models.ForeignKey(User) publication_time = models.DateTimeField() categories = models.TextField() image = models.ImageField(upload_to="images/") The image field is saving to the database correctly, but not displaying on the front end. All other data displays fine. I have confirmed that: The images are saving to the database All other data displays correctly It seems to be an issue displaying the images only. Any ideas what I'm missing in order to get the images to display from the PostgreSQL database? -
Use jquery to detect changes in django-bootstrap-datepicker-plus
I am using django_bootstrap5 and django-bootstrap-datepicker-plus in my project. I have two datetime fields, I want to populate second field when first field is populated and I'm trying to detect this change using jquery, I tried following this question which is almost identical as mine, but it still does not work for me text here is my form widgets = {'date': DateTimePickerInput(attrs={'id': 'start-date'}), "end_date": DateTimePickerInput(attrs={'id': 'end-date'},range_from="date")} template form <div class="col-md-3"> <form method="post"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-primary">Save</button> </form> </div> jquery $(document).ready(function () { $('#start-date').on('dp.change', function (ev) { // function logic }); }); -
Multiple values for one key in drf APIClient GET request
I want to pass multiple values for a single key inside a drf APIClient GET request but only the first value gets sent. I am writing a unit test for my django application using drf's APIClient. I need to pass multiple values for a single key inside the query parameters. An example url would look like this: /api/v1/example/1/?tag=1&tag=tag2 Now I am trying to recreate this behavior in a test using the APIClient but I only ever get the first value. I tried: response = APIClient.get( url, params={"tag": [1, 2]} ) or response = APIClient.get( url, params={"tag": 1, "tag": 2]} ) or response = APIClient.get( url, params=[('tag', 1), ('tag', 2)] ) or payload = {'tag[]': [1, 2]} response = APIClient.get( url, params=payload ) Always the same result. If I check response.request["params"] the result is always {'tag': 1} -
TypeError: fromisoformat: argument must be str in django
hi i want migrate my code and use 5 laste created product but i see TypeError: fromisoformat: argument must be str i want use 5 product in template from django.db import models from django.core.validators import MaxValueValidator # Create your models here. class Product(models.Model): title = models.CharField(max_length=255, verbose_name="نام محصول") description = models.TextField(verbose_name="توضیحات محصول") little_title = models.CharField(max_length=255, verbose_name="توضیحات کوتاه") price = models.IntegerField(verbose_name="قیمت محصول به تومان") discount = models.IntegerField(blank=True, null=True, verbose_name="تخفیف (به تومان)") discount2 = models.IntegerField(blank=True, null=True, verbose_name="تخفیف (به درصد)", validators=[MaxValueValidator(100)]) image = models.ImageField(upload_to="Product", verbose_name="عکس محصول", default="Product/def.png") image1 = models.ImageField(upload_to="Product", verbose_name="عکس محصول 1", default="Product/def.png") image2 = models.ImageField(upload_to="Product", verbose_name="عکس محصول 2", default="Product/def.png") image3 = models.ImageField(upload_to="Product", verbose_name="عکس محصول 3", default="Product/def.png") image4 = models.ImageField(upload_to="Product", verbose_name="عکس محصول 4", default="Product/def.png") size = models.DecimalField(max_digits=3, decimal_places=1, verbose_name="قد محصول (به متر)") water = models.BooleanField(verbose_name="نیاز به آب زیاد؟") earth = models.BooleanField(verbose_name="تیاز به خاک خاص؟") earth2 = models.CharField(max_length=55, null=True, blank=True, verbose_name="درصورتی که به خاک خاص نیاز دارد " "اینجا نام خاک را قرار دهید در غیر " "اینصورت خالی بگذارید") light = models.BooleanField(verbose_name="نیاز به نور زیاد؟") created = models.DateTimeField(auto_now_add=True, verbose_name="تاریخ و زمان ایجاد") class Meta: verbose_name = "محصول" verbose_name_plural = "محصولات" def __str__(self): return self.title class Pot(models.Model): title = models.CharField(max_length=255, verbose_name="نام محصول") description = models.TextField(verbose_name="توضیحات محصول") little_title = models.CharField(max_length=255, verbose_name="توضیحات کوتاه") price = … -
Docker overlay2 directory growing with each build (zero downtime docker compose deployment)
Problem: The host machine's /var/lib/docker/overlay2 directory keeps growing with each build until I'm forced to stop the containers and run docker system prune -af to free up space. Here's the ncdu of the overlay2 directory after just 2 or 3 deployments/builds (there are many additional directories, but they're cut off): My deployment script for zero downtime keeps a set of containers always running. Here's the script: # sources: # https://www.atlantic.net/vps-hosting/how-to-update-docker-container-with-zero-downtime/ old_container=$(docker container ls --filter name=shipaware-django-* --filter status=running --latest | grep -o shipaware-django-[0-9].*) old_listener=$(docker container ls --filter name=shipaware-listener-* --filter status=running --latest | grep -o shipaware-listener-[0-9].*) # need to restart celery in case of new tasks old_celeryworker=$(docker container ls --filter name=shipaware-celeryworker-* --filter status=running --latest | grep -o shipaware-celeryworker-[0-9].*) old_celerybeat=$(docker container ls --filter name=shipaware-celerybeat-* --filter status=running --latest | grep -o shipaware-celerybeat-[0-9].*) echo "old_container: $old_container" docker compose -f production.yml up -d --scale django=2 --scale listener=2 --scale celeryworker=2 --scale celerybeat=2 --no-recreate --build #docker compose -f production.yml up -d --scale django=2 --scale listener=2 --no-recreate --build echo "scaled up django and listener to 2 containers" echo "sleeping 60s" sleep 60 docker container stop $old_container docker container stop $old_listener docker container stop $old_celeryworker docker container stop $old_celerybeat echo "stopped $old_container" docker container rm $old_container docker container rm $old_listener … -
Django annotate() optimization
Supposing a ManyToMany relationship between A and B. The following request is taking too much time to execute when some A instances have > 500 b. def get_queryset(self): qs = A.objects.all() qs = qs.annotate( not_confirmed=Count('b', filter=Q(b__removed__isnull=True, b__confirmed__isnull=True)), confirmed=Count('b', filter=Q(b__removed__isnull=True, b__confirmed__isnull=False)), ) return qs Do you have an idea how to optimize this ? I tried prefetch_related, or using b = B.objects.filter(removed__isnull=True) to do the request only once but not relevent... I would like my request time < 30 sec -
1024 worker_connections are not enough, reusing connections
2023/11/08 12:59:30 [warn] 1125#1125: 1024 worker_connections are not enough, reusing connections 2023/11/08 12:59:30 [alert] 1125#1125: *2978743 1024 worker_connections are not enough while connecting to upstream, client: 197.210.55.148, server: signals.sentinel.vip, request: "GET /api/token/968/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/token/968/", host: "here is my domin (im hiding it)" server { listen 80; server_name IP; client_max_body_size 2G; error_log /var/log/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/signals; } location / { if ($http_user_agent ~* (Googlebot|bingbot|Applebot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Sogou|facebot|ia_archiver) ) { return 403; } include proxy_params; proxy_pass http://127.0.0.1:8000; proxy_connect_timeout 300s; proxy_read_timeout 300s; proxy_send_timeout 300s; proxy_buffering on; proxy_buffer_size 16k; # proxy_buffers 6 16k; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_next_upstream error timeout http_502 http_503 http_504; } } This is my nginx.conf Any suggestion how i can fix this issue? Im using django pytho, have 21 workers. -
How to change date format in html input type=date, from 11/22/2023 to like this November22, 2023
I am using Django framework in my project. Tried different things with input type date tag like format, scripts and jquery scripts but didnt worked. <input type="date" class="form-control-green form-control date_style" id="training_date" onclick="this.showPicker()" name="training_date" value="{{listing_details.training_date}}" aria-describedby="titleHelp" onchange="changeEndDate(1,'')"> -
Keep Deep Learning Model Loaded in Memory in Django Project
I have a deep learning model and I have added it in my django web REST API. I want model to be always loaded in memory. Curretly when user request , model loads in memory and then released after some time. I want it to constantly loaded in ram so that the response time of my api got better. I have deployed API on Windows Server 2019. -
Deploying a Django App to 1and1 (ionos) shared hosting Servers
Good Day, I created a Django website and I deployed to the shared hosting servers of 1 and 1 (Ionos). If anyone could assist me with this your assistance would be greatly appreciated. I followed this guide on Stack Overflow specifically the second comment relating to the question as following the first comment errors out (SSL Error) at step 4 and no further guidance is given to resolve this. After following the steps outlined by the 2nd comment successfully (The only step I did not do was to create a "work" folder) the following error is returned when navigating to the sites URL (Please see attached image). I contacted Ionos Technical department who advised me that the issue is with the .htaccess file but could not point out exactly what the issue is. -
Django discovers language preference by domain
I want to use the sites framework in Django: https://docs.djangoproject.com/en/4.2/ref/contrib/sites/ I have currently a multilinguale website with several domains for each language: www.example.com (only English) www.example.de (only German) www.example.it (only Italien) Currently I run for each website a new gunicorn process with a different settings.py to set the SITE_ID and the LANGUAGE. Because we started to translate to several languages, this approach is creating a lot of duplication code and eats a lot of ram we decided to find a more efficient way. (more than 20 languages at the moment) As I can see, I could automatically setup the SITE_ID with the sites framework but how can I tell Django to change the language according to the domain? (For example example.it/foo/bar content should be always Italien) Or is my current approach already the only and correct way? -
Get Specified Roles from IIS windows auth in Django
I have a django app hosted on IIS with Windows Authentication and wfastcgi. In .Net authorization rules, only a specified users/roles can access the app. I am setting up users by django.contrib.auth.middleware.RemoteUserMiddleware and django.contrib.auth.backends.RemoteUserBackend with a custom backend. I want to get user's "Specified Roles" and assign Group in Django. I was able to get the username by request.META['REMOTE_USER'], but how to get the "Specified Roles" of a user if they have any in Django?Auth Rules Specified RolesWeb.comfig backends.py class CustomRemoteUserBackend(RemoteUserBackend): def configure_user(self, request, user): username = self.clean_username(user.get_username()) user.username = username # Modify the user's username in the database # Extract the user's role from request.META or a custom header. user_role = request.META.get('HTTP_ROLES') # Replace with the correct header name. # Define a mapping of roles to group names. role_group_mapping = { 'Sales': 'Sales', 'Admin': 'Admin', # Add more role-to-group mappings as needed. } # Check if the user's role is in the mapping and assign them to the corresponding group. if user_role in role_group_mapping: group_name = role_group_mapping[user_role] else: # If no role is specified, assign the user to the "unregistered" group. group_name = 'unregistered' group, _ = Group.objects.get_or_create(name=group_name) user.groups.add(group) user.save() return user -
manage.py migrate failure on docker-compose file
i have issue, i have dockerfile with django configuration: FROM python:3.11 WORKDIR /app ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE=server.settings COPY requirements/prod.txt requirements/prod.txt RUN pip install --no-cache-dir -r requirements/prod.txt COPY . . EXPOSE 8000 # RUN python3 manage.py makemigrations RUN python3 manage.py migrate CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] and docker-compose for django and postgres: services: django: image: auralab-django:latest container_name: auralab-django build: context: ./auralab dockerfile: Dockerfile volumes: - ./auralab:/app ports: - "8000:8000" command: ["python3", "manage.py", "runserver", "0.0.0.0:8000"] depends_on: - db environment: - DATABASE_URL=postgres://example_user:example_password@db:5432/auralab db: image: postgres:13 container_name: auralab-db environment: POSTGRES_DB: auralab POSTGRES_USER: admin POSTGRES_PASSWORD: admin ports: - "5432:5432" then i try sudo docker-compose build without makemigrations and migrate, it build successfuly, but after there is no relations: relation "learning_student" does not exist LINE 1: ...t"."description", "learning_student"."image" FROM "learning_... so for this i added makemigratons and migrate in my docker file but have an error during sudo docker-compose build : File "/usr/local/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known here is my settings.py: DATABASES = { 'default': … -
Images are not showing on Django backend server
this is my Django project tree when i upload my image on Django form after that images are not visibal plz help me to solve this : project/ backend/ app/ __init__.py admin.py models.py urls.py view.py backend/ __init__.py settings.py urls.py views.py wsgi.py static/ AWS.png Inside settings.py I have: STATIC_URL = '/static/' STATIC_ROOT= os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my urls.py file : from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('app.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django bulk_create with conditional update
I've been having a problem on a large database that I need to update by reading data from a csv. I have a model like this: class MyModel(models.Model): ... external_id: models.CharField valid_from: models.DateField ... After reading and validating the values of a large csv file, I wish to bulk_create new entries, but on the condition that if for an external_id the date of valid_from is newer than in the database, update the field, otherwise skip it. What is the most efficient way to go about doing this? My workflow is this: I read the csv, and pass each line to a validator/data cleaner function which returns a pydantic model instance which matches my django_db model, use the dict representation of the pydantic model to create the django model instance, add it to a list and pass the list to the bulk_create function. Adding a polling of the db for each row to check whether a value exists and if it does and the date is outdated, then keep going, makes the parser run really slow. An idea that I had was to make a dict of all the existing external_ids and their respective dates by making a {item.external_id: item.valid_date for … -
problem to deploy docker-compose with multiple services using github action and github register
I am using GitHub Actions to trigger the building of my dockerfile,it is uploading the container to GitHub Container Registry. In the last step i am connecting via SSH to my remote server and executing a script to pull and install the new image from GHCR. This workflow is good but in docker-compose file there is 4 services: a Django and Postgresql service with Pegdmin. the ports will be opened on the server, but the service will not run and not respond to requests. docker-compose.yml version: '3.11' services: # the different images that will be running as containers web: build: context: ./ environment: - DEBUG =False - PRODUCTION =True - SECRET_KEY =django-insecure-7@^sc)4+m*=bvhkz++%#$l(db74h)u-4l4=7$v&c8bp%d2b-64 restart: always command: gunicorn backend.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - ./.env.prod nginx: build: ./nginx volumes: - static_volume:/home/app/web/static expose: - 80 depends_on: - web db: container_name: pg_container image: postgres restart: always environment: POSTGRES_USER: root POSTGRES_PASSWORD: root POSTGRES_DB: test_db expose: - 5432 pgadmin: container_name: pgadmin4_container image: dpage/pgadmin4 restart: always environment: PGADMIN_DEFAULT_EMAIL: admin@admin.com PGADMIN_DEFAULT_PASSWORD: root ports: - "5050:80" volumes: static_volume: Dockerfile: # The first instruction is what image we want to base our container on # We Use an official Python runtime as a parent image FROM python:3.11 # … -
Exposing a Django Application Inside Docker to a Public IP Address
I would like to ensure that I'm taking the right steps to expose my Django application running inside a Docker container to a public IP address. Here's the current setup: The Django application is running within a Docker container. Docker is installed on a Linux server, which also has a public IP address. The following command is used in the entrypoint.sh file, which will be invoked by the Docker Compose file to start the application: exec gunicorn --bind 0.0.0.0:${PORT:-8000} --timeout 120 wtools2.wsgi:application If there are any missing pieces I should consider, please provide your guidance. Thank you in advance for your assistance! -
Django contrib backend authentication error: User matching query does not exist despite user presence in custom user table
I have a Django project with a custom user model called CustomUser which extends AbstractBaseUser, which uses the phone number as the unique identifier. However, I'm encountering an authentication error when trying to authenticate a user using the phone number and password. The error message states "User matching query does not exist," even though the user with the provided phone number and password exists in the phone_number_custom_user table. The issue seems to arise when the get_by_natural_key method is called in the ModelBackend, specifically at the line user = UserModel._default_manager.get_by_natural_key(username). Despite the user existing in the phone_number_custom_user table, the User.DoesNotExist exception is raised. I get the error in this django contrib auth backend.py file - class ModelBackend(BaseBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user Model Code - class CustomUser(AbstractBaseUser): phone_number = models.CharField(max_length=20,unique=True, primary_key=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) #refresh_token = models.CharField(max_length=255, default=None) #access_token = models.CharField(max_length=255, default=None) USERNAME_FIELD = 'phone_number' objects … -
why django give an error when user wans to create a comment?
I am developing a blog website with Django. I am getting an error in the create_comment view when an unauthorized user tries to submit a comment. My view code is as follows: Python def comment_create(request, slug, pk): pk = str(pk) try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: # handle the case where the post does not exist return JsonResponse({'success': False, 'errors': {'post': ['Post with this ID not found.']}}) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post # check if the user has the necessary permissions to comment on the post if request.user.is_authenticated: if request.user.has_perm('blog.change_post'): comment.save() return JsonResponse({'success': True, 'comment': comment.to_dict()}) else: return JsonResponse({'success': False, 'errors': {'post': ['You are not authorized to comment on this post.']}}) else: return JsonResponse({'success': False, 'errors': {'user': ['Please log in.']}}) else: return JsonResponse({'success': False, 'errors': form.errors}) else: return render(request, 'blog/post_details.html', {'post': post}) My error is as follows: {"success": false, "errors": {"post": ["Post with this ID not found."]}} I think the problem is that I am not checking in my code whether the user is logged in or not. Currently, even if the user is not logged in, they can submit a comment. Please help me to resolve this issue. Code … -
How to make Class Based View mixin's dispatch method fire first?
I have a Django Class Based View that overrides the dispatch method. I want to add a mixin to this Class Based View. The mixin also overrides the dispatch method. Is it possible to have the mixins dispatch method execute before the Class Based Views custom dispatch method? If so, how would I implement this ? Currently, when I implement my solution, as in the following example, the CustomerCreateView's custom dispatch method fires first, which is not what I need. class MyMixin(LoginRequiredMixin): def dispatch(self, request, *args, **kwargs): .... return super().dispatch(request, *args, **kwargs) class CustomerCreateView(MyMixin, CreateView): model = Customer form_class = CreateCustomerForm title = "Add a New Customer" def dispatch(self, request, *args, **kwargs): ... return super().dispatch(request, *args, **kwargs) -
not authorized to perform: ecr-public:GetAuthorizationToken in docker
aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/u3q0l6u5 While trying to push my Docker container onto EC2, I get the error in the title. I successfully entered the access key via AWS configure and gave the necessary permissions to the user, but the same error continues, please help. enter image description here I was trying to push my docker container onto Amazon EC2, but it gave me this error and I couldn't solve it in any way. -
Django Channels async_to_sync(channel_layer.group_send()) not working
class AllEventConsumer(WebsocketConsumer): def connect(self): self.room_name = str(self.scope['url_route']['kwargs']['user_id']) self.room_group_name = 'all_event_'+self.room_name print('connect') print(self.room_group_name) async_to_sync(self.channel_layer.group_add( self.room_group_name, self.room_name )) async_to_sync(self.channel_layer.group_send( self.room_group_name , { 'type': 'update.list', 'value': 'Value' } )) self.accept() event = Synopsis_Event.give_all_events(self.room_name) self.send(text_data=json.dumps({ 'room_id': self.room_group_name, 'payload': event })) def update_list(self, event): print('inside update_list') print(event) data = json.loads(event['value']) self.send(text_data=json.dumps({ 'payload': data })) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_name, self.room_group_name ) self.disconnect(close_code) def receive(self, text_data=None, bytes_data = None): print('DEF') print(type(json.loads(text_data))) async_to_sync(self.channel_layer.group_send)( self.room_group_name , { "type": "update.list", "value": text_data } ) Here is my code i wrote group_send out of consumers it was not working so i added it to connect just for testing is it triggered. but it's not working Tried with Django channels documentation no changes in code. -
Remove password field from Django
I want to register in Django with a phone number and only get a phone number from the user I don't even want to get a password from the user That's why I decided to remove the password field from the custom user model(password=None) But with this method, I cannot enter the admin panel in Django with created super user It asks me for a password to enter the admin panel in Django How can I enter the admin panel? Code: class CustomUserManager(UserManager): def _create_user(self, name, phone_number, **extra_fields): if not phone_number: raise ValueError("You have not provided a valid phone number") user = self.model(phone_number=phone_number, name=name, **extra_fields) user.set_unusable_password() user.save(using=self._db) return user def create_user(self, name=None, phone_number=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(name, phone_number, **extra_fields) def create_superuser(self, name=None, phone_number=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self._create_user(name, phone_number, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): password = None phone_number = models.CharField(max_length = 25,blank=True, null=True, unique=True) email = models.EmailField(blank=True, null=True, unique=True) name = models.CharField(max_length=255, blank=True, null=True) objects = CustomUserManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] -
My problem with getting the current month as default in django
I have 2 models. AyModel == MonthModel and OdemelerModel == PaymentModel first model is: class AyModel(models.Model): AYLAR = ( ("Ocak", "Ocak"), ("Şubat", "Şubat"), ("Mart", "Mart"), ("Nisan", "Nisan"), ("Mayıs","Mayıs"), ("Haziran","Haziran"), ("Temmuz","Temmuz"), ("Ağustos", "Ağustos"), ("Eylül", "Eylül"), ("Ekim", "Ekim"), ("Kasım", "Kasım"), ("Aralık","Aralık"), ) ay = models.CharField(max_length=10,choices=AYLAR) def __str__(self): return self.ay class Meta: verbose_name = 'Ay' verbose_name_plural = 'Aylar' and second model is: class OdemelerModel(models.Model): odeme_ay = models.ForeignKey(AyModel,default=datetime.now().strftime('%B'), on_delete=models.DO_NOTHING) Whatever record I enter into the database first for AyModel, that record appears by default in OdemelerModel. How Can I Solve This? Thanks.. I want this month to have odeme_ay by default. The same problem occurs in my other model called YearModel. -
Site shows data after logout when clicks back button (Django)
Whenever i logout from my Django site , when i press browser's back button browser shows previous cached data .I need to clear all site data when logging out. Is there a way using JavaScript or something? I've tried @cache_control(no_cache=True, must_revalidate=True, max_age=0) but i only need to clear when user logs out . is there any solution except i provided above one?