Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / postgresql - model with only foreign keys
I have a model which looks like this: class InputTypeMap(models.Model): input_type = models.ForeignKey(InputType, on_delete=models.CASCADE) training = models.ForeignKey(Training, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) gender = models.ForeignKey(Gender, on_delete=models.CASCADE) When I try to create instances of this model with: InputTypeMap.objects.create(input_type=input_type, training=training, gender=gender, category=category) I get an exception when using Postgres-11.9: Traceback (most recent call last): File "/home/hove/sleipner/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, Maintenance, Female, MareGielding, No). From the error message it seems to me that a ID key for the new entry is not generated. This code has worked as I expected for quite some time, but has "suddenly" started to fail locally - probably after a apt get upgrade. When I run the same code with sqlite or Postgres-10.14 thing continue to work as before. It is not clear to me whether this is a bug in my code (most probable ...), Django or Postgres. I am using Django version 3.1.2 -
Email field encryption django
I want to save my email as a encrypted form and in future other fields aswell may include. I checked is https://github.com/erikvw/django-crypto-fields but I am unable to figure out KEY_PATH = '/etc/myproject/django_crypto_fields') what is this and what I am suppose to paste here ? And if somebody knows any other good solution kindly tell me . Any help would be highly appreciated -
updating a queryset throws an error upon iteration in python/django
I have an ordered query that I want to append to a list and then split into sublists based on the price. My code is as follows: def home(books): grouped_books = [] for i in range(len(books) - 1): this_book = books[i].price next_book = books[i+1].price if this_book != next_book and price >= 100: r = books[:i+1] grouped_books.append(r) for ob in grouped_books: books = books.exclude(id__in=[o.id for o in ob]) Upon iterating after the query is updated, this code throws an error that list index is out of range Am I doing something wrong here? I'd appreciate your help. Thanks! -
Python Django how to interact and link from one app to another?
I created an app called 'user' that has all of the login, registration, and logout (user/login, user/registration, user/logout) logic using the Django's User model. If the user logs in, how do I redirect them to a different app, say, 'posts' where they can view a list of different posts? Here's the main urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('user/', include("user.urls")), ] Also, if I wanted to create a view for the main index page, do I create a views.py file in the main folder and add a path to that page? What would that path look like? I am trying to teach myself everything so let me know if there are some gaps of information. Thanks. -
Django - how to build a GenericRelation query?
I'm trying to access all my different model objects by the Hit table. What I do not understand is why I'm unable to Build the actual query to do that. I simply want to get all objects at queryset_m1-m3 where the Model1-3.pk is the hit.object_id as hit.object_id is the primary key of a related object of Model1, 2 or 3. def recently_viewed_proposals(): hit = Hit.objects.all() queryset_m1 = Model1.objects.filter(pk=hit.object_id) queryset_m2 = Model2.objects.filter(pk=hit.object_id) queryset_m3 = Model3.objects.filter(pk=hit.object_id) hit_elements = chain( queryset_m1.random(len(queryset_m1)), queryset_m2.random(len(queryset_m2)), queryset_m3.random(len(queryset_m3)) ) elements_list = list(hit_elements) n_proposals = min(len(elements_list), config.MAX_RECENTLY_VIEWED_PROPOSALS) recently_viewed_proposals = random.sample(elements_list, n_proposals) return recently_viewed_proposals This is how my Hit model Class looks like: ... class Hit(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=hit_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') viewer = models.ForeignKey(User, verbose_name="Viewer", on_delete=models.CASCADE) counted = models.BooleanField(verbose_name="Counted", default=False, editable=True) date_added = models.DateTimeField(auto_now=True) But I'm always falling into the following issue: 'QuerySet' object has no attribute 'object_id' Of course my Model(s)1-3 containing the field: hits = GenericRelation(Hit, related_query_name='hit') Thanks in advance -
Django - Store Model Objects In Separate Database Table
What is the best approach to separate specific instances of a Django model from the general pool of stored instances? I think about these 3 possibilities: Store information as field in parent model: class SampleModel(models.Model): attr1 = models.CharField(max_length=50) attr2 = models.CharField(max_length=50) is_special = models.BooleanField() Store as reference in a separate model: class SampleModel(models.Model): attr1 = models.CharField(max_length=50) attr2 = models.CharField(max_length=50) class SpecialSampleModel(models.Model): sample_model = models.OneToOneField(SampleModel, on_delete=models.CASCADE) Inherit base model in additional class: class SampleModel(models.Model): attr1 = models.CharField(max_length=50) attr2 = models.CharField(max_length=50) class SpecialSampleModel(SampleModel): pass I can imagine that these approaches might have advantages and disadvantages in regards to the performance and usability in the project... Or is there maybe a better approach i did not consider yet? -
Cannot cast type integer to uuid
I tried to run python3 manage.py migrate, but i got this error: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django /db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: cannot cast type integer to uuid LINE 1: ...BLE "core_post" ALTER COLUMN "id" TYPE uuid USING "id"::uuid I'm using PostgreSQL My models.py: Link to pastebin I hope you will help me) Thank you! -
How to get user location using google maps in a django web app?
I'm building an e-commerce application using django and I need to store my clients location in database. how can I use google maps in sign up page so that my clients can choose their location on google maps? and how can I see their chosen location in my admin page? thanks for your time -
Return the url to a newly created Item using ModelSerializer and ModelViewSet in Django Rest Framework
I'd like to return the URL / hyperlink to a newly created item as a response after making a Post in the Django Rest Framework. Intended function: User creates a new item using Post method in a Django Rest Framework API --> in return User gets a json with the hyperlink to the new item created. Response: { "id-url": "www.website.com/api/products/id/" } I am aware this topic been covered in various ways and I have read many, but as I am new to it I am looking for a minimal (but complete) example using a ModelSerializer, I have not be able to find this yet, thus my question. My serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' My view: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer My urls: router = routers.DefaultRouter() router.register('products', ProductViewSet) urlpatterns = [ path('', include(router.urls)), ] Attempts: Here is similar question but the answers does seems incomplete ex_0 I can re-create this ex_1, but does not give me the id Here is an example with function based view, but I am looking for model view, ex_2 This example looked promising but was about nested Serializers ex_3 -
Using Python Dataclass in Django Models
My goal is to create a struct-like object in Django PostgreSQL, such as: specs.coordinate.x specs.coordinate.y specs.coordinate.z x,y,z should therefore be subclasses of coordinate. They should be me mutable as well, wherefore named tuples cannot be used. I have tried it using the new dataclass: from django.db import models from dataclasses import dataclass class Specs(models.Model): name = models.CharField(max_length=80) age = models.IntegerField() @dataclass class coordinate: x: float y: float z: float However the coordinate x,y,z items are not visible in pgAdmin: What am I doing wrong? Is there any better approach for this than with dataclass? -
Why is `socket.error` being treated like it doesn't derive from `BaseException`?
So I've got Django 2.2.16 running with redis library 3.5.0. Somewhere along the way Connection objects of Redis go out of scope and get their __del__ called, which calls disconnect() method on Redis library, it looks as follows: def disconnect(self): "Disconnects from the Redis server" self._parser.on_disconnect() if self._sock is None: return try: if os.getpid() == self.pid: shutdown(self._sock, socket.SHUT_RDWR) self._sock.close() except socket.error: pass self._sock = None Now when this happens this exceptions gets caught: October 12th 2020, 14:28:30.750 Exception ignored in: <function Connection.__del__ at 0x7fddec766830> October 12th 2020, 14:28:30.750 Traceback (most recent call last): October 12th 2020, 14:28:30.750 File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 537, in __del__ October 12th 2020, 14:28:30.750 File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 667, in disconnect October 12th 2020, 14:28:30.750 TypeError: catching classes that do not inherit from BaseException is not allowed Line 667 in disconnect here refers to this line: except socket.error: Now socket is a standard library and its .error surely derives from BaseException, why do I get this exception at all? -
return different queryset with different radio button in template in the same page django
I want to render different queryset when user click radio button without submitting the radio button input. My models are these: class A(models.Model): name = models.CharField(max_length=10) def get_a_list(self): return self.b_set.filter(name__endswith='lorem') def get_b_list(self): return self.b_set.filter(name='blah') class B(models.Model): dept = models.ForeignKey(A, on_delete=models.CASCADE) In template I can do something like this: <ul> {% for a in a.objects.all %} {% for b in a.b_set.all %} <!-- instead of returning all I can do a.get_a_list or b.get_b_list --> <li></li> {% endfor %} {% endfor %} </ul> If I have a group of radio buttons in the same template like this: <div> <input type="radio" id="a-list" value="a-list" name="filter"> <label for="a-list">a_list</label> </div> <div> <input type="radio" id="b-list" value="b-list" name="filter"> <label for="b-list">b_list</label> </div> <div> <input type="radio" id="all" value="all" name="filter"> <label for="all">all</label> </div> When user select a-list button, I want to call get_a_list, and for b-list button, get_b_list. I want to display the result without changing url. I managed to get those different list by putting custom method in models class, but I'm lost. And I know I might lose some reputation for this question, for it might be so easy for somebody. Any suggestion would be so grateful. Thank you in advance. -
jinja2 or Django template engine for Django project?
Currently I am using Django 3.1 and the default Django template engine. But I am very confused between the Django template engine and Jinja2 template engine. please tell is it worth it to move to jinja2 template engine -
How to create custom model Manager that returns users based on group membership
I have a model that is fairly simple. It defines Persons as follow: class ActiveTAsManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_active=True) class Person(AbstractUser): company_id = models.IntegerField(null=True, blank=True, default=None) objects = models.Manager() active_TAs = ActiveTAsManager() the custom model manager works well but I want to add a condition based on group membership. class ActiveTAsManager(models.Manager): def get_queryset(self): phds = Group.objects.get(name="phds") return super().get_queryset().filter(is_active=True) This fails because the Group class is not imported. My question is twofold: how can I import the Group class? How can I write the filter so it filters based on group membership? -
IntegrityError at /admin/images/images/add/ NOT NULL constraint failed: images_images.user_id
IntegrityError at /admin/images/images/add/ NOT NULL constraint failed: images_images.user_id Request URL: http://127.0.0.1:8000/admin/images/images/add/ Django Version: 3.1.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: images_images.user_id Exception Location: C:\Users\Jameskumar haobam\Envs\clone2\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute Python Executable: C:\Users\Jameskumar haobam\Envs\clone2\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\Jameskumar haobam\Desktop\web dev ' 'related\Django-project\clone', 'C:\Users\Jameskumar haobam\Envs\clone2\Scripts\python38.zip', 'c:\python\python38\DLLs', 'c:\python\python38\lib', 'c:\python\python38', 'C:\Users\Jameskumar haobam\Envs\clone2', 'C:\Users\Jameskumar haobam\Envs\clone2\lib\site-packages'] Server time: Mon, 12 Oct 2020 12:18:10 +0000 views.py from django.shortcuts import render from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from .models import Images from .form import ImageForm @login_required def show_all_images(req): all_images = Images.objects.all() context = { 'images':all_images, } return render(req,"imagesapp/showimages.html",context) def upload_image(request): if request.method == "POST": uploaded=ImageForm(data=request.POST,files=request.FILES) if uploaded.is_valid(): uploaded.save() return redirect('show_all_images') else: up=ImageForm() return render(request,"imagesapp/upload.html",{"up":up}) form.py from django import forms from .models import Images class ImageForm(forms.ModelForm): class Meta: model = Images fields=('title','image','user') models.py from django.db import models from django.db import models from django.contrib.auth.models import User class Images(models.Model): title = models.CharField(max_length=50,blank = False) user = models.ForeignKey(User,on_delete=models.CASCADE,) about_image = models.CharField(max_length=500,blank = True) created_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to="Images") def __str__(self): return self.title helpme Guys ,i have encouter these errors i don't know what to do...i have been working on this project which is to upload image from userinterface and filter with user...So please anyone … -
How to get multiple queryset from textarea in django
I have a text area in which user inputs multiple values in different line and i want to get object for every single line in text area and send it to template. How i should do it.? if request.method == 'GET': search = request.GET.get('search') slist = [] for i in range(4): slist.append(search.splitlines()[i]) sdata = Stock.objects.all().filter(slug=slist) return render(request, 'stocks/searchbar.html', {'sdata':sdata}) I'm trying to do it in this way. -
Heroku Requirements for Django
I am trying to deploy my Django project via Heroku. I have done: pip freeze > requirements.txt to generate requirement file. While deploying I am getting the below error- ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /tmp/build_3fb1fde9_/requirements.txt (line 1)) (from versions: none) ERROR: No matching distribution found for apturl==0.5.2 (from -r /tmp/build_3fb1fde9_/requirements.txt (line 1)) I tried to do pip install that in my system but again I am getting exception- requests.exceptions.HTTPError: 404 Client Error: Not Found for URL: https://pypi.org/simple/apturl/ Note- This is the first time I am deploying my project. I guessed I need to do pip install so I did. If I should be doing something else to fulfil the requirement. Please tell me. Thanks! -
How to customise ModelAdmin UI
How does one go about editing the template(s) shown when using wagtail.contrib.modeladmin? Assuming class EventsAdmin(ModelAdmin): menu_label = 'Events' list_display = ('title',) Say I want to make the titles clickable, how would I go about doing so? I figured I could check the templates in wagtail/contrib/modeladmin/templates and add something like <a href="{{ url }}" /> alas the furthest I got to finding that title section was in wagtail/contrib/modeladmin/templates/modeladmin/includes/result_row_value.html where it outputs the title section through the {{ item }} tag {% load i18n modeladmin_tags %} {{ item }}{{ url }}{% if add_action_buttons %} {% if action_buttons %} <ul class="actions"> {% for button in action_buttons %} <li>{% include 'modeladmin/includes/button.html' %}</li> {% endfor %} </ul> {% endif %} {{ closing_tag }} {% endif %} #modeladmin_tags.py @register.inclusion_tag( "modeladmin/includes/result_row_value.html", takes_context=True) def result_row_value_display(context, index): add_action_buttons = False item = context['item'] closing_tag = mark_safe(item[-5:]) request = context['request'] model_admin = context['view'].model_admin field_name = model_admin.get_list_display(request)[index] if field_name == model_admin.get_list_display_add_buttons(request): add_action_buttons = True item = mark_safe(item[0:-5]) context.update({ 'item': item, 'add_action_buttons': add_action_buttons, 'closing_tag': closing_tag, }) return context Going further I don't really understand how the <td> with the title are put in there nor what I can do to make it clickable or customise that template. A screenshot to illustrate the … -
session in django is not getting expired after browser close
i am new to django and python. I am getting issue with session expiry after user close the web-browser without logout. I can see that session remains active in session table, even after waiting for more than 10 min. I updated custom middleware.py and setting.py file as below: middleware.py from django.contrib.auth import logout from django.contrib import messages import datetime import syslog class SessionIdleTimeout(deprecation.MiddlewareMixin if DJANGO_VERSION >= (1, 10, 0) else object): def process_request(self, request): if request.user.is_authenticated(): current_datetime = datetime.datetime.now() syslog.syslog("This user is authenticated") if ('last_login' in request.session): last = (current_datetime - request.session['last_login']).seconds syslog.syslog("there is last_login present in request.session.") if last > settings.SESSION_IDLE_TIMEOUT: syslog.syslog("calling loggout since last > SESSION_IDLE_TIMEOUT") logout(request, login.html) else: syslog.syslog("no logout yet") request.session['last_login'] = current_datetime return None In setting.py MIDDLEWARE = [ .. 'webapp.middleware.SessionIdleTimeout', .. SESSION_EXPIRE_AT_BROWSER_CLOSE = True INACTIVE_TIME = 10*60 # 10 minutes - or whatever period you think appropriate SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' SESSION_EXPIRE_AT_BROWSER_CLOSE= True SESSION_COOKIE_AGE = INACTIVE_TIME # change expired session SESSION_IDLE_TIMEOUT = INACTIVE_TIME # logout SESSION_TIMEOUT_REDIRECT = '/logout/' SESSION_SAVE_EVERY_REQUEST = True These are my python and django version: Python 2.7.9 django.VERSION (1, 11, 4, u'final', 0) Can anyone point me out whats is still missing in above code? -
ValueError: Missing staticfiles manifest entry for 'img'
When Debug = True, Everything is perfect in http://127.0.0.1:8000/ and https://parasnathcorporation.herokuapp.com/ and No errors in logs. When I turn Debug = False, it shows Server Error (500) on http://127.0.0.1:8000/ and https://parasnathcorporation.herokuapp.com/ and ValueError: Missing staticfiles manifest entry for 'img' in my logs img is a folder which contains all images of my project located in static/assets/ and I am trying to deploy my app in Heroku STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR,'credential.json')) ###configuration for media file storing and reriving media file from gcloud DEFAULT_FILE_STORAGE='PMJ.gcloud.GoogleCloudMediaFileStorage' GS_PROJECT_ID = '------------' GS_BUCKET_NAME = '-----------------------' MEDIA_ROOT = "media/" UPLOAD_ROOT = 'media/uploads/' MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) -
How to reset Django transaction after exception during multiprocessing?
How do you reset a Django transaction after a database exception (e.g. IntegrityError) occurs so you can continue to write to the database? I have several workers running in their own processes, all launched via the joblib package, that process database records. They all write their progress to a database via Django's ORM. Generally, they work fine, but occasionally, if one encounters an error, such as trying to write a record with a column that violates a unique constraint, then an IntegrityError is thrown. I have error handling logic to capture these, record the error, and allow it to skip to the next file to process. However, I'm finding that once one of these errors is encountered, that effectively prevents all further database access by that worker, as all further write attempts return the notorious error: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. The weird thing is, I'm not directly using atomic(), so I'm assuming this is being implicitly run by Django somewhere. How do I work around this? I know the usual way to avoid this error is to explicitly wrap your writes inside atomic. So I … -
No reverse match django with slug_pattern
So I want to insert a url from urls.py, but because we have a slug_pattern arg, i'm confuse how to do that. Below are the traceback : Environment: Request Method: GET Request URL: http://localhost:8000/universitas-indonesia Django Version: 1.11.20 Python Version: 2.7.15 Installed Applications: ('neliti', 'publisher', 'accounts', 'hal', 'mtam', 'haystack', 'django_countries', 'storages', 'select2', 'modeltranslation', 'tastypie', 'mathfilters', 'fastsitemaps', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.redirects', 'debug_toolbar', 'django_extensions') Installed Middleware: ('corsheaders.middleware.CorsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'publisher.middleware.CustomDomainMiddleware', 'publisher.middleware.IndexingMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'publisher.middleware.RemoveSlashMiddleware', 'publisher.middleware.ToLowercaseMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'publisher.middleware.NonHtmlDebugToolbarMiddleware') Template error: In template E:\Project\neliti\backend\publisher\templates\publisher\headers\sub-menu\sub_menu_repository.html, error at line 51 Could not parse the remainder: '-indonesia' from 'universitas-indonesia' 41 : <li> 42 : <a href="#">Policies</a> 43 : </li> 44 : <li> 45 : <a href="#">For developers</a> 46 : </li> 47 : </ul> 48 : </div> 49 : 50 : <div class="section"> 51 : <a id="contact" href=" {% url 'organisation_detail' slug=universitas-indonesia %} "> 52 : <div class="header"> 53 : CONTACT 54 : </div> 55 : </a> 56 : </div> 57 : </div> The urls.py look like this we use OrganisationDetailView and slug_pattern slug_pattern = '(?P<slug>[a-z0-9_\\-]+)' url(r'^%s$' % slug_pattern, cache_page(content_page_cache_time)(OrganisationDetailView.as_view()), name='organisation_detail'), prefix_default_language=False ) My Organisation view look like this class OrganisationDetailView(NelitiDetailView): model = Organisation filter_set = 'Publication' template_name … -
Django factory, problem with string primary key
My Django model has string as primary key class ActOfWithdrawal(models.Model): ext_act_id = models.CharField(max_length=256, primary_key=True) ready_to_print = models.BooleanField(default=False) class SapPosition(models.Model): act = models.ForeignKey(ActOfWithdrawal, on_delete=models.CASCADE) solution_for_position = models.CharField(max_length=1) Based on it I created two factories class ActOfWithdrawalFactory(factory.django.DjangoModelFactory): class Meta: model = 'apps.ActOfWithdrawal' django_get_or_create = ('ext_act_id',) ext_act_id = 'M' + str(factory.fuzzy.FuzzyInteger(1, 100000)) ready_to_print = False class SapPositionFactory(factory.django.DjangoModelFactory): class Meta: model = 'apps.SapPosition' act = factory.lazy_attribute(lambda a: ActOfWithdrawalFactory()) solution_for_position = factory.fuzzy.FuzzyText(length=1) But when I try to create SapPositionFactory I got such error self.withdraw_act = factories.ActOfWithdrawalFactory.create( ext_act_id='M3', ) self.sapposition = factories.SapPositionFactory.create( act=self.withdraw_act, solution_for_position='B' ) django.db.utils.DataError: invalid input syntax for type integer: "M3" Does factory boy supports Foreign key in string format? -
Django Time Zone issue
I'm having lot's of troubles with TimeZones in my Django application. For explanation purposes I'll jump right to the example : I have an object which has a TimeField(null=True, blank=True), and I basically want to show this time depending on the users timezone. I have a Middleware class which activates the timezone to the authenticated user : #'middleware.py' import pytz from django.utils import timezone class TimezoneMiddleware(object): """ Middleware to properly handle the users timezone """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: timezone.activate(pytz.timezone(request.user.timezone)) else: timezone.deactivate() response = self.get_response(request) return response Next to this, I'm pulling timezones from User model field timezone = models.CharField(max_length=128, choices=[(tz, tz) for tz in ['UTC'] + pytz.country_timezones('US')], default="UTC") which basically tells me the timezone user selected. And that's all good until I need to render the time adopted to the users timezone. So In my case user has the 'Pacific/Honolulu' timezone. Object time field was saved to 'American/New_York' timezone, and I'm still getting the same time no matter which timezone I select. What am I doing wrong? (I was fallowing the official docs for this) This is my template : {% load tz %} {% get_current_timezone as TIME_ZONE %} {% for object … -
Please if you know how to use django on pydroid, kindly read and answer this question
Please has anyone used django on pydroid? If you had, please can you describe, how you did it yourself, with examples.