Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django channels fetch data from db and send over websocket
error: File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. WebSocket DISCONNECT /ws/test/ [127.0.0.1:63954] comsumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer from random import randint from api.models import Asset class WSConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() res = list(Asset.objects.filter(id=56).values('token_id')) await self.send(json.dumps(res)) here is the code i am using for websocket. here i am fetching data from database but getting above error please take a look what will be the error ? -
How to write API test case for generic views in DRF?
Here I'm writing some TestCase for some queryset to view in api and getting error not a valid function or pattern name. I didn't get any idea what missing here! Is there any solution for this? views.py class StudentView(generics.ListAPIView): queryset = StudentDetails.objects.raw('SELECT * FROM collegedetails.college_studentdetails LIMIT 3;') serializer_class = StudentDetailsSerializers test_views.py from rest_framework.test import APITestCase from rest_framework.reverse import reverse from rest_framework import status STUDENT_URL = reverse('student/') class StudentsDetailsTest(APITestCase): def test_details(self): response = self.client.get(STUDENT_URL, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) college/urls.py urlpatterns=[ path('student/',views.StudentView.as_view(), name='student'), ] django.urls.exceptions.NoReverseMatch: Reverse for 'student/' not found. 'student/' is not a valid view function or pattern name. Ran 1 test in 0.000s FAILED (errors=1) -
"ValidatioError: Value ... is not a valid choice" in Django even with a valid choice
I have a model with a object_type field where the choices should be numbers and the human readable a string like below: OBJECT_TYPES = ( (0, "analog-input"), (1, "analog-output"), (2, "analog-value") ) class MyModel(models.Model): object_type = models.CharField( max_length=20, choices=OBJECT_TYPES, blank=True, null=True ) However, when I try to create an object and assign an integer value to object_type I get a ValidationError that the object_type is not a valid choice and I can't understand how to configure it properly. I have tried with CharField, TextField and IntegerField. obj = MyModel.objects.create(object_type=2) obj.full_clean() ValidationError: {'object_type': ["Value '2' is not a valid choice."]} -
Django ORM taking 10x more time than raw sql for same query
I am trying to fetch around 1000 records from postgress using django ORM and that takes ~1.3sec, but the same with raw sql queries takes 1/10 of the time i.e. ~ 130ms ? Is there any way to speed things up? -
Django – Migrate a field from a child model to its parent model – Manual migration for inheritance leads to a `FieldError`
Short version I'm trying to run a custom migration (via RunPython) that involves an inherited model, say Restaurant. However a FieldError exception is raised at Restaurant.objects.all(), specifying that an inherited field cannot be resolved. Indeed the model returned by apps.get_model("myapp", "Restaurant") oddly does not inherit from the parent class. Longer version Context Consider a Django multi-table inheritance where a model, say Restaurant(address, serves_pizza), inherits from a parent model, say Place(name). The fields for both models are indicated between brackets. The goal is to transfer a certain Restaurant field, say address, to the parent class Place. One challenge is to preserve the data by transferring it through a customized migration operation. One idea that I feel is rather straightforward is first create an intermediate field address_place in Place, then, manually move the data from Restaurant.address to Restaurant.address_place (via migrations.RunPython) finally remove address field and rename address_place into address Focusing on 2., here is what the custom code called by RunPython looks like: def transfer_address_from_restaurant_to_place(apps, schema_editor): Restaurant = apps.get_model("myapp", "Restaurant") for restau in Restaurant.objects.all(): restau.address_place = restau.address restau.save() FieldError, the unexpected error However when running the corresponding migration, a FieldError exception is raised and looks like: FieldError: Cannot resolve keyword 'name' into … -
Django: How to update a class attribute of an invalid form field to display error messages in Bootstrap 5?
When I use server-side validation in Bootstrap 5, I need to add an .is-invalid class to the input form field with an error to display it in div with class="invalid-feedback". To update a class attribute of a form field in Django I can do this, as stated in the docs: class CommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class': 'special'}) self.fields['comment'].widget.attrs.update(size='40') But I cannot figure out how to add .is-invalid to the form field when the form is returned invalid. I have found this in the docs, but it doesn't work. -
Add html code if the element is first in query - Django
In the Bootstrap slider, the first element has the value "active", how to check and add this value to the html code for the queryset, if element is first. Example (which is not working): {% for obj in query %} <div class="carousel-item {% if query|first %}active{% endif %}"> [...] </div> {% endfor %} *this gives activity for all items, not just the first. Expected result is only for first. -
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' with Django + react + load balancer
I have the following in the settings.py ALLOWED_HOSTS = ['http://64.227.106.224', 'http://143.198.246.160',] CORS_ALLOWED_ORIGINS = ['http://64.227.106.224', 'http://143.198.246.160',] CSRF_TRUSTED_ORIGINS = ['http://64.227.106.224', 'http://143.198.246.160',] CORS_ORIGIN_WHITELIST = ['http://64.227.106.224', 'http://143.198.246.160',] INSTALLED_APPS = ['corsheaders',] MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware',] I deployed a load balancer and used react on digital ocean. The error I get is Access to XMLHttpRequest at 'http://64.227.106.224/api/analyze_im/' from origin 'http://143.198.246.160' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. Can someone please point out what is the issue? -
How to active subindex button in django using jinja2 or js?
I am trying to active(highlight) sub-index on a page in Django. Click here to see the sample image Here is my files home.html <div class="col-md-2 text-left" id="subIndex"> <br><br> <h5 class="text-primary">CATEGORIES</h5> <!-- <a href="/" class="abc btn btn-outline-success my-1 " style="width: 100%; text-align: left;">All Products </a> --> <a href="/" class="abc btn btn-outline-success my-1 " style="width: 100%; text-align: left;">All Products </a> <!-- Here href="/?category={{category.id}}" generates the category link --> {% for category in categories %} <a href="/?category={{category.id}}" class="btn btn-outline-success my-1 {% if category.id in request.get_full_path %} active {% endif %}" style="width: 100%; text-align: left;">{{category}} </a> {% endfor %} </div> urls.py from django.urls import path from home import views urlpatterns = [ path('', views.home, name='home'), *** ] view.py from admn import models as AMODEL def home(request): categories = AMODEL.product_category.objects.all() context = { 'categories' : categories, } return render(request, 'home/home.html', context) I have tried to Javascript. But this could not work. main.js // Add active class to the current button (highlight it) let hd = document.getElementById("subIndex"); let btnss = hd.getElementsByClassName("btn"); console.log(btnss) for (let i = 0; i < btnss.length; i++) { btnss[i].addEventListener("click", function () { let current = document.getElementsByClassName("active"); if (current.length>0){ current[0].className = current[0].className.replace(" active", ""); // console.log(current[0]) } // current[0].className = current[0].className.replace(" active", ""); … -
DRF ValueError: Cannot query " ": Must be "Tag" instance
I want to add a field to a serializer that counts all occurrences of a word (a tag). the 2 relevant models in Models.py are: class Tag(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def __str__(self): return self.name or '' class Tagging(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE) resource = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='taggings') tag = models.ForeignKey(Tag, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) # media_type = models.ForeignKey(Gamemode, on_delete=models.CASCADE) origin = models.URLField(max_length=256, blank=True, default='') objects = models.Manager() def __str__(self): return str(self.tag) or '' def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) The Serializer I am trying to write is: class TagCountSerializer(serializers.ModelSerializer): tag = TagSerializer(read_only=True) tag_count = serializers.SerializerMethodField('get_tag_count') class Meta: model = Tagging fields = ('id', 'tag', 'gameround', 'resource', 'tag_count') def get_tag_count(self, obj): # return obj.tag.all().count() tag_count = Tagging.objects.filter(tag=obj).count() return tag_count def to_representation(self, data): data = super().to_representation(data) return data I have tried a couple of potential solutions for the get_tag_count() method, including the ones visible here but I keep getting this error "Cannot query "tag name": Must be "Tag" instance." Does anyone know how I can get around this? -
saving celery data into postgresql
I'm trying to deploy a django project that scrapes data every few minutes and updates redis cache and postgresql data. i used celery tasks and django_celery_beat to do this and it worked fine in development however when i want to automate celery worker and beat in the background and save data to postgres i get this error in logs: [2022-01-07 18:15:17,012: WARNING/MainProcess] django.db.utils [2022-01-07 18:15:17,012: WARNING/MainProcess] . [2022-01-07 18:15:17,012: WARNING/MainProcess] OperationalError [2022-01-07 18:15:17,012: WARNING/MainProcess] : [2022-01-07 18:15:17,012: WARNING/MainProcess] connection to server at "127.0.0.1", port 5432 failed: fe_sendauth: no password supplied celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'personal_website.settings') app = Celery('personal_website') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') tasks.py: from celery import shared_task from .currency_scraper import get_prices from .models import Currency from django.core.cache import cache @shared_task def update_prices(): """ Updates currency model prices using get_prices function. """ prices = get_prices() if prices: for name, price in prices.items(): try: old_price = Currency.objects.get(name=name) old_price.price = price old_price.save() cache.set(name, price, None) except Currency.DoesNotExist: Currency.objects.create(name=name, price=price) cache.set(name, price, None) I understand the error but i don't know how to authenticate to postgresql with celery. i use supervisor to run celery and … -
registering signals in Django results in "Apps aren't loaded yet." error
I keep getting the error, when trying to import signals: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I can't understand this, b/c I've used the following pattern successfully when setting up a user profile in other apps: models.py: from django.conf import settings from django.db import models class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) signals.py: from django.contrib.auth import get_user_model from django.db.models.signals import post_save from my_project.my_app.models import UserProfile def post_save_user_hander(sender, *args, **kwargs): created = kwargs.get("created", False) instance = kwargs.get("instance", None) if created and instance: UserProfile.objects.create(user=instance) post_save.connect( post_save_user_hander, sender=get_user_model(), dispatch_uid="post_save_user_handler", ) app.py: from django.apps import AppConfig class MyAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_project.my_app' try: import my_project.my_app.signals except ImportError: pass According to the documentation, ready() is called "as soon as the registry is fully populated". Therefore, shouldn't the import of UserProfile succeed? Also, the documentation states Although you can’t import models at the module-level where AppConfig classes are defined, you can import them in ready(), using either an import statement or get_model(). Therefore, including them at the top of signals.py which is itself imported in ready() should work, right? -
Accessing django admin panel in Angular + Django application
I am building a website using Django. Now the Angular is used too. I have used Jinja2 before, so any object creation or update was made in the Django admin panel. What is the best way to deal with them now? Is it necessary to create a component for an admin user so he could edit objects from the Angular frontend or is there a way to use Django admin panel after app deployment? What is the best approach? My application does not provide an ability for users to register, so in this case only one root user (admin) will be created. -
In Django Generic Create View Is there any way to add condition like if the item is out of stock return some error otherwise create the item?
In Django Generic Create View Is there any way to add condition like if the item is out of stock return some error otherwise create the item? -
How to perform an action according to different select option value?
I want to show the prices in selected currency from INR,USD,EUR etc. But each currency has a different api key. Plz suggest how can I change api key value based on the selected option. <select class="form-select form-select-lg mb-3 output" aria-label=".form-select-lg example"> <option onclick="getCurrency()" selected>Open this select menu</option> <option value="1">inr</option> <option value="2">usd</option> <option value="3">eur</option> </select> <script type="text/javascript"> function getCurrency() { selectElement = document.querySelector('#select1'); output = selectElement.value; if (output==2){ apidata=api2data; } else if (output == 3){ apidata=api3data; } } P.S api2data and api3data corresponding to apikeys of USD and EUR respectively. -
Getting the Session Key when using Django REST Framework APIViews
I am using Django REST Framework. I have the session middleware activated. Obviously session state management and REST are mutually exclusive, but a session key would be useful to create a single channel websocket, and I see them being generated in my database, but I when request.session.session_key, it returns None. class Init(APIView): def post(self, request): request.session['test']='helloworld' # store a key, this is a test print(request.session['test']) # retrieve a key (I see this in my db, albeit encrypted). Obv don't use session storage for REST (use JWT etc) request.session.session_key # but this returns None Is there any way to get the session key when using DRF APIViews? -
REST API SIMPLE JWT accounts does not return username in http://127.0.0.1:8000/api/auth/jwt/
I am learning Djago REST API and currently want to understand how to run accounts app within the project successfully. I use tutorial that use JWT old version that does not support Django +2 , so i use Simple JWT. So Simple JWT and old one quite different to what the tutor explains and is hardly found in new version. I would apppreciate if you could expalin what i need to do. I want in my http://127.0.0.1:8000/api/auth/jwt/ to return user once i post my username and password, however it returns only 'access' and 'refresh' in my project/accounts/utils.py : from django.conf import settings from django.utils import timzone def jwt_response_payload_hadler(token,user=None,request=None): return { 'token':token, 'user': user.username, } in my project settings i have : from datetime import timedelta REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_FILTER_BACKENDS':( 'rest_framework.filters.SearchFilter', 'rest_framework.filters.OrderingFilter', ), 'SEARCH_PARAM':'search', 'ORDERING_PARAM':'ordering', } JWT_AUTH = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, # 'JWK_URL': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } in old JWT the tutor uses in settings: 'JWT_RESPONSE_PAYLOAD_HANDLER': 'accounts.api.utils.jwt_response_payload_handler' However it does not supprted by Simple … -
Authentication Issues Deploying with Kubernetes
I'm new to Stackoverflow so if I messed something up, please let me know. I have been following a tutorial series on Youtube to learn more about using Django (https://www.youtube.com/watch?v=CELsEhInIEc&list=PL39pssg07dpDJas1vxb7Dyw5f8SkAw6c-&index=8). In this last episode, the application is deployed using Docker, Helm, and Kubernetes. From 23:50 onwards the Bitnami Postgresql subchart is used to deploy a postgresql database. Once I run the (make-helm) deploy command, the postgresql pod starts running and when I inspect the logs I receive the following error: ==> ** Starting PostgreSQL setup ** ==> Validating settings in POSTGRESQL_* env vars.. postgresql x INFO ==> Loading custom pre-init scripts... postgresql x INFO ==> Initializing PostgreSQL database... postgresql x INFO ==> Cleaning stale /bitnami/postgresql/data/postmaster.pid file postgresql x INFO ==> pg_hba.conf file not detected. Generating it... postgresql x INFO ==> Generating local authentication configuration postgresql x INFO ==> Deploying PostgreSQL with persisted data... postgresql x INFO ==> Configuring replication parameters postgresql x INFO ==> Configuring fsync postgresql x INFO ==> Loading custom scripts... postgresql x INFO ==> Enabling remote connections postgresql x INFO ==> ** PostgreSQL setup finished! ** postgresql x INFO ==> ** Starting PostgreSQL ** x GMT [1] LOG: pgaudit extension initialized x GMT [1] LOG: listening on … -
How to assign value to one-to-one field in django
I'm just start learning about django and trying to assign value to one-to-one field in my models using manage.py shell. I try to do this way but not sure why it doesn't assign the value to Author.address author1 = Author.objects.get(first_name="Sam") addr1 = Address.objects.get(post_code="12345") author1.address = addr1 Any missing step i missed? class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) address = models.OneToOneField(Address, on_delete=models.CASCADE, null=True) def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name() class Address(models.Model): street = models.CharField(max_length=80) postal_code = models.CharField(max_length=5) city = models.CharField(max_length=50) def __str__(self): return f"{self.street}" Thanks -
Unable to display the list of name of the tags django-taggit
I currently learning Django and creating my first blog in Django 4.0.x but something is error when i use django-taggit The problem is when i display the tags in my html it doesn't show, i tried watching an example but it is quite difficult for me to follow the method because i have a slug in my MangaDetailView. Here is my code: models class Manga_Info(models.Model): class Newmanager(models.Manager): def get_queryset(self): return super().get_queryset(). filter(status='published') options = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=350) about = models.TextField(max_length=500) type = models.ForeignKey(Type, on_delete=models.PROTECT, default=0, blank=False, null=False) genre = TaggableManager() upload = models.DateTimeField(auto_now_add=True) released = models.DateTimeField(max_length=100) menu_image = ProcessedImageField(upload_to= user_directory_path, processors=[ResizeToFill(175, 238)], default = 'images/blog-post-01.jpeg', format='jpeg', options={'quality': 100}) info_image = ProcessedImageField(upload_to= user_directory_path, processors=[ResizeToFill(175, 579)], default = 'images/blog-post-01.jpeg', format='jpeg', options={'quality': 100}) slug = models.SlugField(max_length=100, unique_for_date='upload', unique=True) status = models.CharField(max_length=15, choices=options, default='draft') objects = models.Manager() # default manager newmanager = Newmanager() # custom manager class Meta: ordering = ("upload",) def __str__(self): return self.title views def MangaDetailView(request,_id): try: dataset = Manga_Info.objects.all() type = Type.objects.exclude(name='default') data = Manga_Info.newmanager.get(slug =_id) except Manga_Info.DoesNotExist: raise Http404("Data does not exist") context = { 'data':data, 'dataset': dataset, 'type': type, 'tag':tag, } return render(request, 'base/home_info.html', context) def tagged(request, slug): tag = get_object_or_404(Tag, slug=slug) posts … -
django modeltranslation prefix_default_language
i add prefix_default_language = False in urls.py urlpatterns += i18n_patterns( path('', include('main.urls')), prefix_default_language= False ) but the form for changing the language stopped working for the default language form: <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} {% if language.code == 'en' %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {%else%} <option value=""> {{ language.name_local }} ({{ language.code }}) {%endif%} {% endfor %} </select> <input type="submit" value="Go"> </form> how fix it? -
Python: how to select n number of elements of each type from OrderedDict?
I have a Django serializer returning an OrderedDict from the serializer.data. It can contain for example this type of data: [OrderedDict([('id', '1'), ('date', '2022-01-08'), ('type', 'A')]), OrderedDict([('id', '2'), ('date', '2022-01-09'), ('type', 'A')]), OrderedDict([('id', '3'), ('date', '2022-01-08'), ('type', 'B')]), OrderedDict([('id', '4'), ('date', '2022-01-09'), ('type', 'B')]), OrderedDict([('id', '5'), ('date', '2022-01-08'), ('type', 'C')]), OrderedDict([('id', '6'), ('date', '2022-01-09'), ('type', 'C')])] I'd like to take the first element of each type and make a json out of that data. I could use for -loops to iterate through the dict and make a new list containing one element of each type: A, B and C. I'd like to know if there's some cleaner and neater way to go through the dict and select n number from each type? -
Ajax Integration with Django and Font Awesome Icon Change
I have a Django app where I want to display a page containing user posts which can be liked by other users by clicking on a Font Awesome Icon which futher is in an anchor tag. When a post is liked by a user, the icon class should be changed from fa-heart to fa-heart-o and vice-versa. To achieve this an Ajax request is made by the click event on the icon. This changes the icon and increments/decrements the like count. I have this like FBV: #feeds/views.py @login_required def like(request): post_id = request.GET.get("post_id", "") user = request.user post = Post.objects.get(pk=post_id) liked= False like = Like.objects.filter(user=user, post=post) if like: like.delete() else: liked = True Like.objects.create(user=user, post=post) resp = { 'liked':liked } response = json.dumps(resp) return HttpResponse(response, content_type = "application/json") And in urls.py : urlpatterns=[ path('like/', views.like, name='like'), ] This is the template {% for post in posts %} ...... </li> <li> {% if post in liked_post %} <span class="like" data-toggle="tooltip" title="Unlike"> <a id="like" post_id="{{ post.id }}"><i class="fa fa-heart"></i></a> <ins>{{ post.likes.count }}</ins> </span> </a> {% else %} <span class="like" data-toggle="tooltip" title="Like"> <a id="like" post_id="{{ post.id }}"><i class="fa fa-heart-o"></i></a> <ins>{{ post.likes.count }}</ins> </span> </a> {% endif %} </li> ... {% endfor %} This is … -
How do I maintain the scroll position when returning to a page using lazy load?
Actually, the question is very clear, as seen in the title. The part I want to add is this, just like on Twitter, when I go down the page and then enter a user profile or post detail and return to the previous page by pressing the back button on the browser, the page opens where I left off, despite being lazy. How can I achieve this with Django. I don't know if it matters, but Vue is used as cdn in my project. I would like to talk about an example on the subject. In Safari and Chrome browsers on a computer with macOS, when the back button is pressed on the browser, exactly the event I want takes place. It comes back as if the previous page was cached, but on computers with Windows or Linux, when the back button on the browser is pressed, it goes to the previous page by requesting it again. -
How to set Django model attribute based on another attribute?
I have a model which takes time into account. So when I set is_all_day as True I want my start_hour and end_hour to return 6:00 and 23:59 respectively but it returns null. This is my model: class TestModel(models.Model): start_hour = models.TimeField(blank=True, null=True) end_hour = models.TimeField(blank=True, null=True) is_all_day = models.BooleanField(default=True) class Meta: managed = True db_table = 'test_model' def start_all_day(self): if self.is_all_day == 'True': self.start_hour = '6:00' self.start_hour.save() return self.start_hour else: return self.start_hour def end_all_day(self): if self.is_all_day == 'True': self.end_hour = '23:59' self.end_hour.save() return self.end_hour else: return self.start_hour What am I doing wrong here?