Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django group permissions for CBV's
I am working on an app and right now I am dealing with a specific admin group that I created called post admin. In my django admin I have the permissions for the group set to Can Change Post, Can Delete post, Can View Post I want to give my post admin group users better access to be able to do this. Not just in the admin page. I want them to be able to go to my DeleteView, UpdateViewand be able to edit/delete any users posts. So basically I need to be able to give access to the view to the user who originally created the post and my post admin group. Any tips/advice how to incorporate this? -
"NoReverseMatch" when calling a function in views.py from html using Django
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. I get this error when trying to see the page now, I'm not sure where I'm passing the "id/employee_number" incorrectly which is causing this to show: NoReverseMatch at /operations/enter-exit-area/ Reverse for 'ajax_get_employee_name' with keyword arguments '{'id': 'employee_number'}' not found. 1 pattern(s) tried: ['operations/get\\-employee\\-name\\/(?P<id>[0-9]+)\\/$'] models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, … -
Django Wizard form but with forms.ModelForm class
I am trying to build a wizard for booking a room at a small B&B. I thought it would be nice to do the following steps: Let the user first select a date (the user already has an account and is logged in). Then once the dates are selected, it shows the rooms available. After they select some, they fill out a bit more information, and then click book. Once done it basically saves their reservation with the dates, the room they selected and all that. The question I had was, I don't see a good example if Django can do this and if so can it do it using ModelForm? Not only that, can the second 'form' have data filled out based on the first form results? i.e. the dates picked, show which rooms are available. I found this here: https://docs.djangoproject.com/en/1.7/ref/contrib/formtools/form-wizard/ But it didn't show how to work with forms.ModelForm . I wasn't sure where to start on this. My other option was to wire in Ajax that looks when the checkin/checkout date are filled out to return a list of available rooms for selection (but has been ages since I have done Ajax anything). Wasn't sure if the … -
Avoiding page refresh when a form is used in Django
I have a very basic Django view: def myview(request): if request.method == 'POST': if 'button1' in request.POST: form1 = form = myForm(request.POST) # check whether it's valid: if form.is_valid(): profile = form.save() profile.user = request.user profile.save() messages.success(request, f"Success") return HttpResponseRedirect(request.path_info) else: form = myForm() return render(request, "main/mytemplate.html", context={"form":form}) And its template: <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form %} <button name="button1" type="submit" class="btn btn-primary">SUBMIT</button> </form> Everything works here, when this form is used, some data is saved on my DB. What i would like to change, though, is the page reload after the form is used. When the Submit button is hit, the page will be refreshed. Since it makes the navigation way slower, i would like to have the view not refreshing the page each time the form is used. Is it possible to accomplish this in Django? For example, instead of refreshing the page, i would like to only load part of it, or to have a 'Reload' icon while the view is doing its work. I'm pretty new to Ajax, so i don't know how to get started on this. -
django makemigrations work as expected, but migrate throws integrity error
I am currently working on a website for a client using django. I'm currently having an issue that I've never had before. I run makemigrations and it works, and then in the migrate it throws integrity error 'null constraint failed'. The field that's making me issues is the user field, a one to one connection to the django User model. class AuthorityUser: """ Represents an authority user """ role = models.CharField(max_length=40, verbose_name='Role') user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='משתמש') authority = models.ForeignKey(Authority, on_delete=models.CASCADE, null=True, verbose_name='רשות') password_reset_token = models.CharField(max_length=40, null=True, blank=True) active = models.BooleanField(default=True, verbose_name='פעיל') can_create_committee = models.BooleanField(default=False) class Meta: # Order model instances by first name and last name ordering = ('user__first_name', 'user__last_name') def delete(self, *args, **kwargs): """ Delete the components before deleting the model instance """ self.user.delete() super().delete(*args, **kwargs) def save(self, *args, **kwargs): """ Overrides the Model save method """ if '_' not in self.user.username: # Add suffix to the user self.user.username = f'{self.user.username}_AU{self.authority.id}' self.user.save() if not self.password_reset_token: # Generate a password token self.password_reset_token = uuid.uuid4().hex super().save(*args, **kwargs) django.db.utils.IntegrityError: NOT NULL constraint failed: new__authority_authorityuser.user_id -
MySQL issue while migrating in Django
I am trying to do ./manage.py migrate in my django project but it results in django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for t he right syntax to use near '[] NOT NULL, `Y` double precision[] NOT NULL, `Viewtimestamp` datetime NOT NULL)' at line 1") There is no compatibily issue according to documentation and answer here. I also tried this but no luck. My Django version is 2.2.5 Mysql - Ver 14.14 Distrib 5.7.23, mysqlclient version - 1.4.5 models.py from django.db import models from django.contrib.auth.models import User from django.contrib.postgres.fields import ArrayField # Create your models here. class Products(models.Model): title = models.CharField(max_length = 100) description = models.TextField() views = models.FloatField(null = True) image = models.ImageField(upload_to = 'productImages/') dateUploaded = models.DateField(auto_now_add=True) Daytimestamp = models.DateField(auto_now_add=True) actualViews = models.IntegerField(null = True) class Meta: ordering = ['title'] class Views(models.Model): X = ArrayField(models.IntegerField(blank = True)) Y = ArrayField(models.FloatField(blank= True)) Viewtimestamp = models.DateTimeField(auto_now_add=True) -
Why, after login by my own view, user is logged in on admin site but not on my views? Django
I have situation where I wanted to check if my app works on production. When I start app locally, everythink works, but on production when I use my login form, user is authenticated on admin site, but not on my views. My form: class LoginForm(LoginForm): def clean(self): super(LoginForm, self).clean() if not self.user.is_active or self.user.is_deleted: raise forms.ValidationError(self.error_messages['account_inactive']) return self.cleaned_data My view: class LoginView(LoginView): form_class = LoginForm login_view = LoginView.as_view() -
Is there any difference between nbmultitask and multiprocessing?
Am using multiprocessing to perform some tasks at the same time, so I used multiprocessing for this job, but when I run the script, values of the class does not change, it seems that it makes a copy for this values. But when I use nbmultitask, it changes on the object values directly. So is there any difference between them, also in deployment? -
Why can't I add a ManyToMany relation to an object in Django?
I've got an api made in Django which has two models linked by a ManyToMany relation. class Type(models.Model): name = models.CharField(max_length=64) application = models.CharField(max_length=64) description = models.TextField() class Device(models.Model): reference = models.CharField(max_length=64) application = models.CharField(max_length=64) types = models.ManyToManyField(to='Type') I'm using Django Rest Framework, in which I've got a create() method in the serializer to add types to a device. def create(self, validated_data): # Serialize Types types_data = validated_data.pop('types') device = Device.objects.create(**validated_data) print("DEVICE TYPE",type(device)) for type_data in types_data: print("TYPE OF TYPE_DATA", type(type_data)) print("TYPE_DATA", type_data) t = Type.objects.create(device=device, **type_data) print("TYPE", t) device.types.add(t) print("TYPES IN OBJECT", device.types) device.save() return device Unfortunately it doesn't seem to work. I've got some print statements in the code above, and the outpunt of that is: DEVICE TYPE <class 'iot.models.Device'> TYPE OF TYPE_DATA <class 'collections.OrderedDict'> TYPE_DATA OrderedDict([('name', 'Serve north.'), ('application', 'Particular outside.'), ('description', 'Teacher rather.')]) TYPE Type object (1) TYPES IN OBJECT iot.Type.None As you can see at the last line, the Types don't seem to be added. What am I doing wrong here? All tips are welcome! -
How to best set up django apps in a game project
I'm trying to create a game using react + django and recently re-evaluated the folder structure. Currently I have each part of the game separated into it's own app (ie, enemies, items, world are all separate apps). My thinking is that removing an app shouldn't affect other apps, so having each part of the game as a separate app feels bad to me now. I was instead thinking about putting all of those into the same "core" app, and having any expansions to the game as additional apps. Example directory structure below. backend/ backend/ core/ # everything that the base game relies on admin/ __init__.py characterclasses.py enemies.py items.py world.py models/ __init__.py characterclasses.py enemies.py items.py world.py serializers/ __init__.py characterclasses.py enemies.py items.py world.py ... expansion/ # an example expansion to the game, including new characters and items models/ __init__.py characterclasses.py # would include new character classes items.py # would include new items ... Is there anything "wrong" about this set up/anything to be aware of going forward. I'm fairly new to django and anything backend in general. -
change the queryset from a view in a filter
I would like to have default behaviour where queryset in a view returns records where publish_at date is less than some date. I also want to have boolean DRF filter that if set to true returns all the records no matter what publish_at date is. views.py: queryset = ProjectNews.objects.exclude(publish_at__gte=timezone.now()) filters.py: from django_filters import rest_framework as filters class ProjectNewsFilterSet(filters.FilterSet): not_published = filters.BooleanFilter( method='show_not_published_news' ) def show_not_published(self, queryset, name, value): if value: # queryset based on queryset from view # does not return all the records return queryset.all() return queryset.exclude(publish_at__gte=timezone.now()) -
How to resolve `Requested setting INSTALLED_APPS, but settings are not configured.` error in Django?
I have the following error when i run the views.py file. Note that it worked properly before I imported the ratesEUR model: views.py: from django.shortcuts import render from models import ratesEUR import json import requests response = requests.get("http://data.fixer.io/api/latest?access_key=XXX&base=EUR") rates_EUR = json.loads(response.content.decode('utf-8')) timestamp = rates_EUR['timestamp'] base = rates_EUR['base'] date = rates_EUR['date'] rates = rates_EUR['rates'] id = 1 rates_new = ratesEUR(id=id, timestamp=timestamp, base=base, date=date, rates=rates) rates_new.save() def render_Quotes_app(request, template="Quotes_app/templates/Quotes_app/Quotes_app.html"): return render(request, template) according error: Traceback (most recent call last): File "C:\Users\Jonas\Desktop\dashex\Quotes_app\views.py", line 2, in <module> from models import ratesEUR File "C:\Users\Jonas\Desktop\dashex\Quotes_app\models.py", line 4, in <module> class ratesEUR(models.Model): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\Jonas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\Jonas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf\__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [Finished in 0.41s] What I have already tried: Insert and save export DJANGO_SETTINGS_MODULE=dashex.settings to the bottom of the code in venv/bin/activate but I don't have such directory in myvirtualenv folder at all. Link: ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or … -
Django ManifestStaticFilesStorage is not displaying static files. Returns "Not found in HTML"
I'm setting up static files to be served through the django ManifestStaticFilesStorage to hash values busting the browser cache so that it will always upload new static files. I've followed the requirements: # settings.py file STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' DEBUG=False # Command line to set up files python manage.py collectstatic # layout.html example to find static page. It displays the correct hashed value # on the browser. <link rel="stylesheet" type="text/css" href="{% static 'deepsea/css/main.css' %}"> However, it is not uploading the static files. When I click the link to check the static file it returns: <h1>Not Found</h1><p>The requested resource was not found on this server.</p> When I switch to Debug=True it finds static values and displays everything correctly. Why is django not finding the static files? -
Django PasswordResetDoneView Not Finding View or URL Pattern
I have been building a user account functionality for a Django app. In doing so, I have come across a problem and am uncertain of whether I am doing something wrong or have encountered an unfamiliar quirk of Django/Python. Any help is appreciated. I have the following set of (working) urls (user_accounts/urls.py): app_name = 'user_accounts' urlpatterns = [ path('signup', views.UserSignUpView.as_view(), name='signup'), path('logout', auth_views.LogoutView.as_view(), name='logout'), path('login', auth_views.LoginView.as_view(template_name='user_accounts/login.html'), name='login'), re_path(r'^reset/$', auth_views.PasswordResetView.as_view(template_name='user_accounts/password_reset.html', email_template_name='user_accounts/password_reset_email.html', subject_template_name='user_accounts/password_reset_subject.txt'), name='password_reset'), re_path(r'^reset/done/$', auth_views.PasswordResetDoneView.as_view(template_name='user_accounts/password_reset_done.html'), name='password_reset_done'), re_path(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(template_name='user_accounts/password_reset_confirm.html'), name='password_reset_confirm'), re_path(r'^reset/complete/$', auth_views.PasswordResetCompleteView.as_view(template_name='user_accounts/password_reset_complete.html'), name='password_reset_complete') ] I have been trying to test it as follows (user_accounts/tests/test_views_forms.py): class SuccessfulPasswordResetTests(TestCase): def setUp(self): email = 'jon@doe.com' User.objects.create_user(username='john', email=email, password='123abcdef') url = reverse('user_accounts:password_reset') print(reverse('user_accounts:password_reset_done')) self.response = self.client.post(url, {'email': email}) def test_redirection(self): ''' A valid form submission should redirect to password_reset_done ''' url = reverse('password_reset_done') self.assertRedirects(self.response, url) The issue is that I get the following error: File "/home/user-name/sites/project-web/project/user_accounts/tests/test_views_forms.py", line 128, in setUp self.response = self.client.post(url, {'email': email}) django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Yet, when I navigate directly to /user/reset/done/ in the browser, it serves the proper template. -
Django has no object attribute named text - but I don't expect it to?
I have the below structure, When I click on the model name in the admin view, I get the below error. What does this mean? AttributeError at /admin/app/tasksx/ 'tasksx' object has no attribute 'text' Request Method: GET Admin.py from django.contrib import admin from .models import tasksx admin.site.register(tasksx) Views.py def create_task(request): if request.method == 'POST': creator = request.user job_title = 'data engineer' skill_name = request.POST.get('skill_name') starting = request.POST.get('starting') description = request.POST.get('description') target_date = request.POST.get('target_date') i = tasksx.objects.create(creator=creator, job_title=job_title, skill_name=skill_name, starting=starting, current=starting, description=description, target_date=target_date) messages.success(request, ('Skill created')) return redirect('index') models.py class tasksx(models.Model): job_title = models.CharField(max_length=400, default="data") creator = models.CharField(max_length=400, default="none") skill_name = models.CharField(max_length=400, default="none") starting = models.CharField(max_length=400, default="none") current = models.CharField(max_length=400, default="none") description = models.CharField(max_length=4000000, default="none") target_date = models.DateTimeField(default=datetime.now) def __str__(self): return self.text -
Django query join two table
iam new in django and i want to create query in django i'am try with select_related but i don't know how insert the second part of condition AND model1.qty >= model2.items so please i need your help i try **Model1.objects.select_related('model2).filter(model1.qty__gte=?)** but it's not ok this is below sql query that i want to implement with django queryset SELECT model1.name,model2.name WHERE model1.id=model2.model1.id AND model1.qty >= model2.items sorry for my english -
How to pass multiple variables/arguments in a template tag while reverse mapping
I have a model let say Employee which has fields such as name, joined_date, emp_id, designation. I have created a search form which takes 'from_date' and 'to_date' in a post calls then I get all employees based on these two dates by using the filter. Once I come to the employee's page. I have a 'Junior' and 'Senior' tab, once the user clicks on any of these tabs it should again filter with the designation (filter on date range and designation). I have tried with a couple of things, but it does not work. Please suggest. url: path('search/', view.search, name="search"), path('employees/', view.get_employees, name="employees"), re_path(r'^employees/senior/(?P<from_created>)/(?P<to_created>)/$', view.get_employees, name="senior_employees"), model: class Employee(models.Model): name joined_date emp_id designation view: employees = Employee.objects.filter(joined_date__range=(from_created, to_created), designation="senior") html template: <a class="nav-link active" href="{% url 'employee:senior_employees' 'from_created' 'to_created' %}" role="tab">Senior</a> -
How to properly call a modal from views.py in Django?
I'm trying to add a modal that prompts the user for data to update a field in the database. I tried using https://github.com/trco/django-bootstrap-modal-forms/blob/master/README.rst as a reference for creating this update modal, but I am having trouble with properly calling it based on the user's "id/employee_number". The way that this is supposed to work is that, upon form submission, in views.py there is a logic that either flags a current entry in the database, or it creates a new one. What I'm trying to achieve is that, whenever a submission gets flagged, this modal pops up and prompts the user for an estimate of the time they think they entered or left an area. What I need help with is how to call the modal from the views (where I put the comment), or what could be a way to approach this solution I'm trying to achieve? The flagging portion of the logic works, but I'm not sure how to call this modal to show up only when the "edited_timestamp" field is needed from the user. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if … -
Filter many to many set from models instance
I have a product model that has tags, the tags can be in multiple languages. when I get a instance of the product, i have a product.tags manager. I was wondering if there was a way to filter the tags connected to the product instance, that when I pass it to the serializer, i would only get the tags in a single language with the serializer output. class Product(models.Model): ... tags = models.ManyToManyField(Tag) ... class Tag(models.Model) text = models.CharField(max_length=32) language = models.CharField(max_length=2) class ProductSerializer(serializer.ModelSerializer): tags = TagSerializer(many=True) ... I am able to filter them manually then add them to the data response, like so: tags_query = product.tags.filter(language=lang) tag_serializer = TagSerializer(lang, many=True) but I was wondering if this can be done through the serializers? -
Css external files are not working in my django
I am making a simple website with Django and when I apply the <style> </style> tag directly in the html file there are no problems, but when I extract the css to a external file so that the code is cleaner and tidy it no longer works. As I read, I created a static folder and inside this another one called css for saveing the different css files inside. Once this is done, I load the static/css folder using {% load static%} and in the head of the html I declare the path to my css file. But it doesn't load it and it shows me the following error: GET /static/css/main.css HTTP/1.1" 404 1660 It isn't finding my file. I enclose my code below: {% load static %} <!DOCTYPE html> <html lang="es"> <head> <title> {% block title%}{% endblock%} </title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="{% static "css/main.css" %}"> </head> <body> <h1> TÍTULO </h1> {% block content %}{% endblock%} </body> </html> Reading more info I have seen that sometimes the following line is added to the settings.py file,STATIC_ROOT = [os.path.join (BASE_DIR, "static"),]but it doesn't work either. Can somebody help me? Thank you very much. -
unable to get the same code to work in a django view even though it works in the shell
I tried a run a block of code in the shell and it seemed to work but when i converted the same into a function in my views page i seem to be getting a type error that says int object is not iterable Screenshot of terminal: my views.py: def HomePageView(request): val = DepartureTime.objects.exclude(dep_time__exact='') val = val.values('fl_no') link = [None]*val.count() for i in range(val.count()): link =int(val[i].get('fl_no')) cons = Flight.objects.filter(fl_no__in = link) args = { 'cons' : cons } return render(request, 'base_home.html', args) using the above function throws a TypeError saying int object is not iterable. The problems seems to be due to the 'link' part in 'cons' -
Django Models make a field that is updating when another field is changing
I want to make a TextField in my model that store every changes of another field. That field to store data like an array. How can I do that? Can anybody give an advice? exemple: class Exemple(models.Model): field = models.ForeignKey(AnotherModel, blank=True) history_field = models.TextField(blank=True) # => ['old_field_value', 'field_value'] When "field" receive a value I want to append that value to "history_field" -
how to apply filters on a posgres JSONField in django rest framework?
I have a model similar to this: # segment/models.py from django.db import models from django.contrib.postgres.fields import JSONField class Segment(models.Model): name = models.CharField(max_length=100) # docs: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#jsonfield data = JSONField('data', 'data') in field data I store JSON data similar to this { "length": 123.45 "difficulty": { "avg": "easy" "max": "advanced" } } I would like to be able to query data as following: api/segments/?data__difficulty__avg=easy to filter all records where data.difficulty.avg="easy". to do this, I set up the serializer: # api/serializers.py from rest_framework import serializers class SegmentSerializer(serializers.ModelSerializer): class Meta: model = Segment fields = ['id', 'name', 'data'] and the view looks like this: # api/views.py from django_filters.rest_framework import DjangoFilterBackend from .serializers import SegmentSerializer from segment.models import Segment class SegmentViewSet(viewsets.ReadOnlyModelViewSet): queryset = Segment.objects.all() serializer_class = SegmentSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['id', 'name', 'data'] when I call api/segments I get the following error AssertionError at /api/segments/ AutoFilterSet resolved field 'data' with 'exact' lookup to an unrecognized field type JSONField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/master/ref/filterset.html#customise-filter-generation-with-filter-overrides Request Method: GET Request URL: http://localhost:8000/api/segments/ Django Version: 2.2.7 Python Executable: /Users/udos/.virtualenvs/ts/bin/python Python Version: 3.6.4 . . . I tried adding data = serializers.JSONField() to the serializer: # api/serializers.py from rest_framework import serializers class SegmentSerializer(serializers.ModelSerializer): data = … -
using multiple databases to complete one whole record
I'm building a website that displays recipes from cookbooks on a page. Each page will consist of information stored in separate database tables: Cookbook used | Recipe used | Ingredients used | Recipe steps to follow Each recipe has steps to follow : step 1 : Ingredient = Tomato | Instruction = Peel and Slice | Time = 3mins Step 2: Ingrediant = Mozzerella | Instruction = Washs | Time = 2mins Step 3: Ingrediant = Basil | Instruction = Wash and Prepare | Time = 4mins The reason I want to separate the recipe steps from the actual recipe is that I want to be able to make the content in the instruction field searchable and add a detail view for each ingredient and show analytics on what instruction is most used and which is least used. I would also like to see in this detail ingredient view how many different recipes that the ingredient are used in. Here is what I have so far class cookbook(models.Model): title = models.CharField(max_length=255,unique=True) class ingredient (models.Model): name = models.CharField(max_length=255,unique=True) class recipesteps(models.Model): ingredient = models.ForeignKey(ingredient,on_delete=models.CASCADE) instructions = models.TextField() time = models.IntegerField(default=0) class recipe(models.Model): cookbook = models.ForeignKey(cookbook,on_delete=models.CASCADE) ingredient_used = models.ManyToManyField(ingredient) recipe_steps = models.ForeignKey(recipesteps,on_delete=models.CASCADE) My … -
Generate datetime object as a result of query aggregation
Given one of models contains tz anaware TimeField called unaware_time: class MyModel(models.Model): unaware_time = TimeField(...) ... Is it possible to generate a datetime object from unaware_time field using aggregation given that timezone and date are stored in other table OR are provided directly from python code? MyModel.objects.values('unaware_time').annotate(aware_timestamp=???).filter(...) I'm suspecting this may be possible using Query Expressions but I can't find a way of doing that.