Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Listview must return only the courses that student have puchased in django
My models User class User(AbstractUser): is_student = models.BooleanField(default=False) .... purchased = models.ManyToManyField(Course, blank=True) Course class Course(models.Model): title = models.CharField(max_length=1000) ..... price = models.FloatField() My Views class StudentPurchasedcourse(ListView): model = Course template_name = 'tutspack/purchasedcourse.html' context_object_name = 'course' def get_queryset(self): queruset = Course.objects.filter(pk=self.request.user.purchased.all()).order_by('title') return queruset My Urls.py path('purchased_course/', views.StudentPurchasedcourse.as_view(), name='purchased-course'), I want to return all the courses That student have purchased on the studentViewpage. It would be helpful If anyone knows the answer. -
How to fill dropdown on Django from database?
I am trying to fill up a dropdown on a form and the data is from database forms.py // ERROR: unsupported operand type(s) for +=: 'ModelChoiceIterator' and 'tuple' for x in MyModel.objects.values_list( 'id', 'name', named=True): self.fields['mymodel'].widget.choices += ((x.id, '%s - %s' % (x.id, x.name)),) // I've tried, but it doesnt work for x in MyModel.objects.all(): self.fields['mymodel'].widget.choices += ((x.id, '%s - %s' % (x.id, x.name)),) What am I doing wrong? Thank you -
Dynamic URL Routing Django
I Created a dynamic url routing/views for each one of the product on my website, Everything is working fine until I go to Cart/checkout and it loads on of the product page currently in Cart instead of Cart.html and Checkout.html urlpatterns = { path('<str:pk>/', views.dynamic_product_view, name='productdetail'), } views.py: def dynamic_product_view(request, pk=None): products = Product.objects.all() slug=None data = cartData(request) items = data['items'] if pk is not None: try: slug = Product.objects.get(slug=pk) except: Http404() context = { 'slug':slug, 'products': products, 'items': items } return render(request, 'product-details.html', context) It's currently working fine on any other Page like index, store and Products page but the problem appear in Cart and Checkout -
Javascript Django like button doesn't update counter
I have created Put request to update like count, but when I press like button count doesn't change unless I refresh page. and like/unlike function works fine. Can somebody help me resolve this issue? view.py Here is how i have done put request. class PostLikeView(APIView): authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated] def get(self, request, post_id, slug=None, format=None): post = Post.objects.get(pk=post_id) serializer = PostSerializer(post, many=False, ) return JsonResponse(serializer.data, safe=False) def put(self, request, post_id, slug=None, format=None): post = Post.objects.get(pk=post_id) user = self.request.user # if user.is_authenticated(): if user in post.likes.all(): post.likes.remove(user.id) else: post.likes.add(user.id) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False) In javascript at like_button.addEventListener i calling function like post where i pass post_id this function works except counter doesnt change unless i refresh page, can I edit so counter update without refreshing if not how to setup automatically to refresh after put request complete? index.js function post_list(post) { const postdiv = document.createElement('div') postdiv.setAttribute('id','post-div') const userdiv = document.createElement('div') userdiv.setAttribute('id', 'username-div') const bodydiv = document.createElement('div') bodydiv.setAttribute('id', 'body-div') const datediv = document.createElement('div') datediv.setAttribute('id', 'date-div') const datep = document.createElement('p') datep.setAttribute('id', 'date-paragraph') const userp = document.createElement('p') userp.setAttribute('id', 'username-paragraph') const bodyp = document.createElement('p') bodyp.setAttribute('id', 'body-paragraph') // LIKE const likesdiv = document.createElement('div') likesdiv.setAttribute('id', 'likes-div') let likesp = … -
Multipart form parse error - Invalid boundary in multipart: None'. Django Rest Framework [closed]
Всем привет. Не получается отправить данные вместе с файлом изображения через клиент запрос fetch на сервер DRF. Вот метод VUE при отправке формы: async createTodo(){ const formData = new FormData formData.append('title', this.titleValue) formData.append('description', this.descriptionValue) formData.append('image', this.imageValue[0]) formData.append('urgent', this.urgentValue) const response = await fetch('http://localhost:4000/api/v1/todo-list/', { method: 'POST', headers: { "Content-Type": "multipart/form-data", }, body: formData, }) const newTodo = await response.json() } В переменной newTodo я получаю следующий результат: {detail: 'Multipart form parse error - Invalid boundary in multipart: None'} Код view django: from rest_framework import generics from .serializers import TodoSerializer from .models import Todo from rest_framework.parsers import MultiPartParser, FormParser class TodoAPIList(generics.ListCreateAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer parser_classes = (FormParser, MultiPartParser, ) Я так понимаю нужно дописывать функционал в django, или я просто не правильно отправляю запрос на стороне сервера? -
How can I create fixtures that references a few foreign instances with pytest and factory-boy?
I have the function that calculate the sales of each companies in month, then I want to test this function. so I want to create some Sales fixtures of a few companies for the test. like: create 2 or 3 companies fixtures create many sales fixtures for these companies use created sales fixtures for my aggregation function test How can I do this? Do some methods exist for this like FuzzyXXX? I defined factories like below, but it generates sequential company ids. def aggregate_companies_sales_in_month(): result = ( Sales.objects.all() .annotate(year=TrunkYear('sold_at'), month=TrunkMonth('sold_at')) .values("year", "month", "company") .annotate(sales=Sum("amount")) .values("year", "month", "company", "sales") ) return result and models like: class Company(Model): name = CharField(max_length=64) class Sales(Model): sold_at = DatetimeField() company = ForeignKey(Company, on_delete=CASCADE) amount = PositiveIntegerField() then define factories using factory-boy class CompanyFactory(DjangoModelFactory): class Meta: model = Company name = faker.company() class SalesFactory(DjangoModelFactory): class Meta: model = Sale sold_at = FuzzyDate(start_date=date(2022,4,1), end_date=date(2022,12,31)) company = Subfactory(CompanyFactory) # maybe should change here? amount = 100 my test code is like: @pytest.fixture def setup(sales_factory): # This creates sales for 20 companies with sequential ids. sales_factory.create_batch(size=20) @pytest.mark.django_db def test_my_aggregation_function(setup): # create sales fixtures here or take it as argument? actual = aggregate_companies_sales_in_month() ... -
How to configure Celery when a database is shared between 2 Django projects?
I build an application with 2 Django projects, A and B. Both projects: have Celery configured and their own tasks share the same PostgreSQL database have a common Django application trading because they need access to the same models live in separate Docker containers on the same Docker host have dedicated Redis container and port number The problem is that Celery from project A says the task my_task from project_b/trading/tasks.py isn't registered. What is the reason for this and how can I isolate further more the two projects ? Project A settings.py CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://127.0.0.1:6377/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "redis://127.0.0.1:6377/0") CELERY_IMPORTS = ('trading.tasks',) celery.py app = Celery("project_a", broker='redis://localhost:6377/0') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) tasks.py empty Project B settings.py CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://127.0.0.1:6376/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "redis://127.0.0.1:6376/0") CELERY_IMPORTS = ('trading.tasks',) celery.py app = Celery("project_b", broker='redis://localhost:6376/0') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) tasks.py from project_b.celery import app @app.task def my_task(): pass -
How can I retrieve values of previously set session variables in a class based view?
I would really appreciate some insight on this because I think I've tried everything I could think of but I can't seem to make this work. I've tried using cache.set and cache.get instead of session variables but the class can't seem to read the cache that has been set even though my other function-based views can read them. I'm currently attempting to use server-side processing to display over 100k rows of data in a data table. The examples I've seen so far are mostly like this: class ItemListView(ServerSideDatatableView): queryset = TableName.objects.all() columns = ['column1', 'column2', 'column3'] But for my case, I have a function that stores filters selected by the user from the page. What I would like to do is: class ItemListView(ServerSideDatatableView): (code that retrieves session variables that store the filters selected by the user) queryset = TableName.objects.filter(country__in=selectedcountries, plant__in =selectedplants) columns = ['column1', 'column2', 'column3'] something like that. Can someone please help me, I don't have much experience on class-based views. thank you! -
Django - query extracts most frequent values field by field
i would like to return a single tuple with, field by field, the most frequent values. My models is as follows: class myTable(models.Model): a = models.IntegerField(blank = True, default = 0) b = models.IntegerField(blank = True, default = 0) c = models.IntegerField(blank = True, default = 0) d = models.IntegerField(blank = True, default = 0) My DB is as follows: ID a b c d 0 2 4 1 0 1 3 4 2 3 2 2 3 1 3 3 1 2 6 2 The single tuple that I want to return is constitued like that: a=2, b=4, c=1, d=3 (a is 2,3,2 and 1 so the most frequent value is 2). How can I do that? -
Problems with jquery/select2 framework - it doesn't work in my django project
i'm newbie in python, still learning this language and django framework. So i making simple project now, and now i meet this problem: i can't modify my design cause select2 and jquery not working in html document. Here is my files: base.html {% url 'cities:home' as cities_home_url%} {% url 'cities:create' as cities_create_url%} {% url 'trains:home' as trains_home_url%} {% url 'trains:create' as trains_create_url%} <!doctype html> <html lang="ar" dir="rtl"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.rtl.min.css" integrity="sha384-+4j30LffJ4tgIMrq9CwHvn0NjEvmuDCOfk6Rpg2xg7zgOxWWtLtozDEEVvBPgHqE" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/> <title>{% block title %}{% endblock %}</title> {{ form.media.css }} </head> <body> <nav class="navbar navbar-expand-lg container" style="background-color: #e3f2fd;"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home'%}">FindRoute</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item {% if request.path == cities_home_url%}active {% endif %}"> <a class="nav-link" aria-current="page" href="{% url 'cities:home'%}">Города</a> </li> <li class="nav-item" {% if request.path== trains_home_url%}active {% endif %}> <a class="nav-link" href="{% url 'trains:home'%}">Поезда</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item dropdown" {% if request.path== cities_create_url or request.path== trains_create_url %} active {% endif %} > <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Добавить </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" … -
problem with rendering <form> asynchronously using fetch in javascript in django application
I have written an ajax request in jQuery that I want to rewrite to pure javascript using fetch. What I am currently using is this: views.py @login_required def like_article(request, id): article = get_object_or_404(Article, id=id) is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' liked = False if article.likes.filter(id=request.user.id).exists(): article.likes.remove(request.user) liked = False else: article.likes.add(request.user) liked = True context = { 'article': article, 'is_liked': liked, 'total_likes': article.total_likes(), } if is_ajax: like_form = render_to_string('components/ajax_like.html', context, request=request) return JsonResponse({'like_form': like_form}) url.py path('like_article/<int:id>/', views.like_article, name='like_article'), ajax_like.html <form action="{% url 'like_article' article.id %}" method="POST"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" value="{{article.id}}" class="btn btn-clicked"><i class='bx bxs-like'></i></button> {% else %} <button type="submit" id="like" value="{{article.id}}" class="btn btn-to-be-clicked"><i class='bx bx-like'></i></button> {% endif %} {{ total_likes }} like{{ total_likes|pluralize }} </form> jQuery ajax request (working fine) $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var id = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like_optimazon" article.id %}', data: { 'id':id, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function(response){ $('#like-section').html(response['like_form']) }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); }); What I tried to do is below. Basically, after clicking the like button the class should change from .btn-not-liked to .btn-liked and the number of likes should increase by 1. I;d like to … -
Nested dynamic URLs from different Viewsets
backend noob here. I have a question about nested URLs in Django/DRF. I want to nested url structure, for example: site.com/blog/: shows list of blog. site.com/blog/blog-name/: which shows single blog with name. site.com/blog/blog-name/posts: shows the post list of the blog. site.com/blog/blog-name/posts/some-blog-post: single blog post. site.com/blog/blog-name/posts/some-blog-post/tags: list of tags. site.com/blog/blog-name/posts/some-blog-post/tags/1: a tag with id = 1. I have read this answer but it suggest an additional method in BlogViewset. However I need to nest URLs using two different viewsets. Because as you can see this is just initial fields of an userblog system and I want to be able to manage it without having big files. I have three models, like this: class TagModel(models.Model): tag = models.CharField(max_length=32) def __str__(self): return self.tag class BlogModel(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) profession = models.CharField(max_length=100) class Meta: pass def __str__(self): return self.name class PostModel(models.Model): title = models.CharField(max_length=120) content = models.TextField() tags = models.ManyToManyField(TagModel) blog = models.ForeignKey(BlogModel, on_delete=models.CASCADE, related_name="posts") def __str__(self): return self.title This is my viewset for Blogs: from ..models.blog import BlogModel, PostModel from ..serializers.blog import BlogSerializer from rest_framework import viewsets from rest_framework import mixins from django.shortcuts import render class BlogViewset( mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = BlogModel.objects.all() serializer_class = BlogSerializer # Return … -
How to run VBScript file using django in IIS
I want to execute vbscript file in project folder using django in IIS. It is working fine in django production server but it is not working in IIS server. I have used the following code to execute vbscript file completed = subprocess.run(["cscript", "C:\\Automation\\Python\\Invoicepdfdemo\\pdfdemo\\media\\pdfs\\start.vbs"]) please advice how to call and execute vbs file in django in IIS -
Multiple models seaarch with Django Rest Framework
I need to make a search through some different models and than make an endpoint for it with DRF. So my attempt to make it looks like this class DataSearch(FlatMultipleModelAPIView): def get_querylist(self): q = self.request.query_params.get('query') if q: vector_data = SearchVector('research', 'data', 'research__name') vector_var = SearchVector('label', ) query = SearchQuery(q, search_type='websearch') querylist = [ { 'queryset': Data.objects.annotate(search=vector_data).filter(search=query), 'serializer_class': DataSerializer }, { 'queryset': Variable.objects.annotate(search=vector_var).filter(search=query), 'serializer_class': VariableSerializer } ] else: querylist = [Data.objects.none()] return querylist Here I'm using DjangoRestMultipleModels for making query goes by two models. When I'm trying to run thin stuff I have an error DataSearch cannot use the regular Rest Framework or Django paginators as is. Use one of the included paginators from drf_multiple_models.pagination or subclass a paginator to add the format_response` method. Any ideas of what paginators doing here? Or how to make all this stuff work correctly? -
JSON parse error - Expecting value: line 1 column 1 (char 0)
I want to serialize with Django and Django Rest, but I am getting the error I mentioned above while adding a record. Can you help me? def recordCreate(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = RecordSerializer(data = data) if serializer.is_valid(): serializer.save() return render(request,"registration_form.html") return render(request,"registration_form.html") serializers.py class Meta: model = Records fields = ['id','username','tel','tcNo','adress','kurum','diagnosis','intervention','conclusion','doctor'] -
Creating a nested Comment section
What is the best way to create a nested comment section? I haven't been able to set it up add to my current setup. My current Views is setup is class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'add_comment.html' # fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('home') This is my current models is.. class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=250) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) Any help on this would be greatly appreciated! -
Django query by separate date and time fields (how to perform conditional order_by)
I have a Meeting model. It has a separate data and time field, the reason why it is not a single datetime field, is that the time is allowed to be null. If I used a single datetime field and set the hours/minutes to 00:00 if no time given, then I can't distinguish that from a meeting set at 00:00. And some unusual sentinel value like 13:37:42 as no meeting is a werid hack. Heres the model: class Meeting(models.Model): meeting_date = models.DateField(db_index=True) meeting_time = models.TimeField(db_index=True, null=True, blank=True) Now the problem comes in to filter by a given date/time. So I think the solution is to filter by date, then order by the time. E.g. to get the latest meeting that is before now: from datetime import datetime now = datetime.now() prev_meeting = ( Meeting.objects.filter(meeting_date__lte=now.date()) .order_by('-meeting_date', f'meeting_time <= {now.time()}', '-meeting_time') .first() ) The f'meeting_time <= {now.time()}' is the part I don't know how to do with the django ORM, but I know how to do with SQL. the Django Docs do not mention conditional ordering. -
Call is-valid when pagination is applied to data in DRF
I have a ModelViewSet and I am using ModelSerializer. I am also using Pagination that is from django.core. My views code snippet that works: page_number = request.data.get("page") data = Model.objects.filter() paginator = Paginator(data, 100) page = paginator.page(int(page_number)) serializer = self.serializer_class(page, many=True) list_data = serializer.data What I want to do is to validate the data. Meaning to do: if serializer.is_valid(raise_exception=True): list_data = serializer.validated_data But I am getting error if I try to run the above code. Error: "Expected a list of items but got type \"Page\"." How can I send the data to is_valid in this case? -
How to return a TemplateView.as_view() if user is authenticated?
# urls.py from django.contrib import admin from django.urls import path, include from home import views from django.views.generic import TemplateView urlpatterns = [ path('',views.index, name="home"), path('', TemplateView.as_view(template_name='index.html')), path('login',views.loginUser, name="login"), path('logout',views.logoutUser, name="logout"), ] Above is my urls.py file. # views.py from django.views.generic import TemplateView def index(request): print(request.user) if request.user.is_anonymous: return redirect("/login") return render(request, TemplateView.as_view(template_name="about.html")) . . . Above is a part of my views.py I'm trying to return/render my "index.html" file as a TemplateView.as_view() (as I am using React on the frontend) ONLY if the user is authenticated. I have handled the authentication part, I need help figuring out how to write code to return/render index.html file as a TemplateView.as_view(). Thanks. -
How to Integrate Bitpay Payment Gateway with Django?
Bitpay provides this button to add in the HTML file which also having a unique token key. Could anyone please help me in the process to integrate the Bitpay account through Django? I can't understand the further procedure. Thanks in advance. -
How to generate a dynamic html as string error f-string: expressions nested too deeply
I am requesting the html content of file by html_text = requests.get('https://buildpro.store/products/jaquar-water-closet-kus-wht-35951').text after getting this i want to extract the title price and a lot of different things and then fill my html template with the data and save it as text in csv file <html> <head> <title>Free Health Faucet On Jaquar Water Closet KUS-WHT-35951 </title> <script type="application/ld+json"> { "@context": "https://schema.org/", "@type": "Product", "name": "Health Faucet On Jaquar Water Closet", "image": [ "https://example.com/photos/1x1/photo.jpg", "https://example.com/photos/4x3/photo.jpg", "https://example.com/photos/16x9/photo.jpg" ], "description": "Get Jaquar Health Faucet Free (Worth Rs.999) On purchase of Jaquar Water Closet KUS-WHT-35951 and get 25% discount Product SKU : KUS-WHT-35951FREEALD-CHR-583 Closet Details: Product Code: KUS-WHT-35951 MRP: 15990 Closet Size: 385*595*385 Brand : Jaquar Closet Series: Kubix Type of Trap: P-Trap Type of Mounting", "sku": "0446310786", "mpn": "925872", "brand": { "@type": "Brand", "name": "Jaquar" }, "review": { "@type": "Review", "reviewRating": { "@type": "Rating", "ratingValue": "4", "bestRating": "5" }, "author": { "@type": "Person", "name": "BuildPro" } }, "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "989" }, "offers": { "@type": "Offer", "url": "https://buildpro.store/products/jaquar-water-closet-kus-wht-35951", "priceCurrency": "INR", "price": "1,119.99", "priceValidUntil": "2020-11-20", "itemCondition": "https://schema.org/UsedCondition", "availability": "https://schema.org/InStock" } } </script> </head> <body> </body> </html> The problem i face is that it have that i cant declare string by … -
AWS CloudFront combine static page from S3 and a dynamic page from a second server in same url
I have a static page on S3 which is served through AWS CloudFront. I now want to add a dynamic page form a server running Django under the same url. All pages served from the Django server have the url form '/subscription*'. Is it possible to use behavior settings in CloudFront to just add the Django app subscription to the url of CloudFront? -
Azure AD User access token requested by angular MSAL library and validation by WEB API using django_auth_adfs
I am playing to setup an Angular Single Page Application using MS MSAL Angular library to request an Access token to get user details from Microsoft Graph API and to authenticate into a custom WEB API build with DJango Python Framework. I use the django_auth_adfs and rest_framework libraries to build this API. I used the following tutorials to setup my environments : https://docs.microsoft.com/en-US/azure/active-directory/develop/tutorial-v2-angular-auth-code and https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-angular/ for the Angular Side https://django-auth-adfs.readthedocs.io/en/latest/rest_framework.html for the DJango side In my Angular App, I am able to login with my Azure AD credential. I can see that the access tokens for MS Graph and for my API are well fetched but this last is not accepted by my WEB API. On Azure AD, I setup the two applications. One for the Angular frontend and one for the django backend. Here are my configurations: For DJango backend: Authentication using Web configuration with redirect URI to http://localhost:8000/oauth2/callback and only organizational directory accounts (no implicit flow). Tried without and with a client secret (same result). No token configuration Permissions to MS Ggaph without admin consent required and granted for my organization as status. Scope defined to expose the API: api://xxxxxxxx-32d5-4175-9b05-xxxxxxxxxxxx/access_as_user (Admins and Users consent enabled) and my frontend … -
Efficiently get first and last model instances in Django Model with timestamp, by day
Suppose you have this model: from django import models from django.contrib.postgres.indexes import BrinIndex class MyModel(model.Models): device_id = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) my_value = models.FloatField() class Meta: indexes = (BrinIndex(fields=['timestamp']),) There is a periodic process that creates an instance of this model every 2 minutes or so. This process is supposed to run for years, with multiple devices, so this table will contain a great number of records. My goal is, for each day when there are records, to get the first and last records in that day. So far, what I could come up with is this: from django.db.models import Min, Max results = [] device_id = 1 # Could be other device id, of course, but 1 for illustration's sake # This will get me a list of dictionaries that have first and last fields # with the desired timestamps, but not the field my_value for them. first_last = MyModel.objects.filter(device_id=device_id).values('timestamp__date')\ .annotate(first=Min('timestamp__date'),last=Max('timestamp__date')) # So now I have to iterate over that list to get the instances/values for f in first_last: first = f['first'] last = f['last'] first_value = MyModel.objects.get(device=device, timestmap=first).my_value last_value = MyModel.objects.get(device=device, timestamp=last).my_value results.append({ 'first': first, 'last': last, 'first_value': first_value, 'last_value': last_value, }) # Do something with results[] This … -
Access ForeignKey type from get_context_data
I have a CreateView in which i want to access the type(choice field) of foreign key in my model which is being used in my current model. Class Mymodel1(models.Model): name = models.CharField() type = models.CharField(choices=SomeTypes.choices()) Class MyModel2(models.Model): name = models.CharField() cas = models.ForeignKey(Mymodel1) Class Mymodel2CreateView(models.Model) def get_context_data(self): type = *queryset to access type from model1*