Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django, constraint without effect?
I had something like the following model in my Django Application: class custom_user(models.Model): # ... number = models.IntegerField() # ... location = models.ForeignKey( Locations, on_delete=models.PROTECT ) I then relaized that number and location needs to be unique together, therefore I added the following to custom user class Meta: verbose_name_plural = "Patienten" constraints = [ models.UniqueConstraint( fields=['nummer', 'praxis'], name='unique_patientennummer_praxis' ) ] I ran makemigrations and migrate afterwards, and the console told me that the contraint was added successfully. Unfortunately it is still possible to add new users with the same number and location! Am I missing something? -
Can't paass count result using annotate with Django querysete to template
I'm using annotate with my Django queryset to count a number of records. I am using it with filter and understand the order makes a difference. My query is: numcontestants = Contestant.objects.filter(assigned_team__id=urlid).annotate(num_contestants=Count('id')) When I pass numcontestants to my template and display it with {{ numcontestants }}, I see a queryset containing each of the records I want to view. When I try {{ numcontestants.num_contestants }} I get nothing. I don't want to have to iterate over numcontestants to get a count, my understanding was that num_contestants should be a single integer number. What is the right way to access the number generated by annotate here? -
Image Upload Issue with TinyMCE
I'm trying to upload the images from tinymce's textarea to the server side media folder. I try to do it with file_picker_callback instance from tinymce and images_upload_url with postAcceptor.php. Here's the details; Tinymce customize script: tinyMCE.init({ selector: 'textarea', plugins: 'quickbars wordcount preview codesample image imagetools hr link lists media fullscreen autosave powerpaste nonbreaking', image_title: true, automatic_uploads: true, images_upload_url: "/static/js/postAcceptor.php", images_upload_base_path: "/media/images", file_picker_types: 'image file media', /* and here's the custom image picker */ file_picker_callback: function (cb, value, meta) { var input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'image/*'); input.onchange = function () { var file = this.files[0]; var reader = new FileReader(); reader.onload = function () { var id = 'blobid' + (new Date()).getTime(); var blobCache = tinymce.activeEditor.editorUpload.blobCache; var base64 = reader.result.split(',')[1]; var blobInfo = blobCache.create(id, file, base64); blobCache.add(blobInfo); cb(blobInfo.blobUri(), { title: file.name }); }; reader.readAsDataURL(file); }; input.click(); } }); *And the postAcceptor.php I get from static folder: <?php $accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com", "http://127.0.0.1", "127.0.0.1"); $imageFolder = "/media/images"; if (isset($_SERVER['HTTP_ORIGIN'])) { if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } else { header("HTTP/1.1 403 Origin Denied"); return; } } if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header("Access-Control-Allow-Methods: POST, OPTIONS"); return; } reset ($_FILES); $temp = current($_FILES); if (is_uploaded_file($temp['tmp_name'])){ if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) { … -
How to delete whole directory with files in it using Django default_storage
My Storage Structure: my-bucket/ - dir_1/ - file_1 - dir_A - dir_2/ What I tried: default_storage.exists('dir_2/') o/p: True default_storage.delete('dir_2/') dir_2 got deleted successfully. But when I try the same for dir_1: default_storage.exists('dir_1/') o/p: False default_storage.delete('dir_1/') This doesn't work. dir_1 still exists How to delete dir_1 completely using the default_storage? -
Cannot link an authenticated user to their new Account upon creation
I'd like each User to be able to create an Account (max of one account each). The user in session won't be able to see the option to create an account unless they are logged in/authenticated. When I log in and click submit on the Create Account form, this error is raised: 'ValueError at /accounts/create/ Cannot assign "<SimpleLazyObject: <User: Jimmy>>": "Account.user" must be a "User" instance.' My models.py: from django.db import models from django.contrib import auth from django.utils.text import slugify from django.urls import reverse from django import template register = template.Library() class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return self.username class Account(models.Model): user = models.OneToOneField(User,related_name='customer_account',on_delete=models.CASCADE) first_name = models.CharField(max_length=30,blank=True) surname = models.CharField(max_length=30,blank=True) billing_address = models.TextField(blank=True) delivery_address = models.TextField(blank=True) def __str__(self): return f"Account: {self.user.username}" def get_absolute_url(self): return reverse('about',kwargs={'username':self.user.username, 'pk':self.pk}) Views.py: from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from braces.views import SelectRelatedMixin from django.views.generic import (CreateView, UpdateView, ListView, DetailView, TemplateView,) from . import forms from . import models from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import redirect from django.contrib.auth import get_user_model # User = get_user_model() class SignUp(CreateView): form_class = forms.CreateCustomerForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html' class CreateAccount(LoginRequiredMixin,CreateView): model = models.Account fields = ['first_name','surname','billing_address','delivery_address'] template_name = 'accounts/create_account.html' def form_valid(self,form): self.object = form.save(commit=False) … -
Django template tags through TinyMCE editor
I have a custom template tag which returns the URL of an image @register.simple_tag def mediaURL(slug): """Gets the URL of the media with the inputted slug""" print("Here") return str(utilities.getMediaURL(slug)) Referencing this template tag directly from the HTML file like shown below returns the URL of the image. {% load custom_tags %} {% mediaURL 'logo-300-by-300' %} When I try to create an image though the TinyMCE editor and set the image source as the template tag, the template tag isn't being rendered, {% block content %} {{ page.body | safe }} {% endblock %} This is the source code from the browser: <img style="display: block; margin-left: auto; margin-right: auto;" src="{% mediaURL 'logo-300-by-300' %}" alt="" /> How do I allow template tags through the TinyMCE editor? -
How to seperate messages based on both sender and receiver of the message in blog app using Django
Guys I have the following code for my message app in my instagram-like project in Django. I can get all the messages in my app. In the dialogues page I want to just classify the messages into categories based on the dialogues that the user has between him/herself and the other users of the app. How can I classify these messages. Is there any good solution for that. Just know that I dont want any online chat or anything related to web socket programming. Model of the Message: class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') dispatcher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='dispatcher') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') content = models.TextField(max_length=500, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) content = models.TextField() def get_dialogues(user): sent_messages = Message.objects.filter(dispatcher=user) received_messgaes = Message.objects.filter(receiver=user) all_messages = sent_messages | received_messgaes return all_messages And this is the view @login_required def dialogues(request): messages = Message.get_dialogues(request.user) return render(request, 'message/dialogues.html', {'messages':messages}) I think this much of code suffices for the question to be answered. -
Is there a way to merge 2 querysets in Django and order them by a their repecting field?
I'm trying to create a twitter clone and this is my user and tweet Model(some irrelevant fields have been removed). class TwitterUser(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE,primary_key=True) Bio = models.CharField(max_length=200, blank=True) Location = models.CharField(max_length=200, blank=True) Website = models.URLField(blank=True) ProfilePicture = models.ImageField(upload_to="Twitter", default="../static/twitter/images/default_profile.png") CreateDate = models.DateField(default=timezone.now) class Tweet(models.Model): TweetBody = models.CharField(max_length=140, blank=False) TweetDate = models.DateTimeField(default=timezone.now) Owner= models.ForeignKey(to=TwitterUser,on_delete=models.CASCADE,related_name="Owner") RetweetedBy= models.ManyToManyField(to=TwitterUser,related_name="Retweeted",blank=True,through="RetweetIntermediate") and this the table that my many to many relationship for retweet is using. class RetweetIntermediate(models.Model): twitteruser=models.ForeignKey(TwitterUser,on_delete=models.CASCADE) tweet=models.ForeignKey(Tweet,on_delete=models.CASCADE) retweetDate=models.DateTimeField(default=timezone.now) In profile view all the tweets and retweets should be shown ordered by date what I'm doing right now (and it is working fine) is this: def keymaker(a): return a.TweetDate def ProfileView(request): tweets= list(Tweet.objects.filter(Owner=user.user_id,IsReplyToTweet__isnull=True).order_by("-TweetDate")) retweets = list(user.Retweeted.all().order_by("-id")) retweetInter=RetweetIntermediate.objects.all().order_by("-tweet_id") for i , j in zip(retweets,retweetInter): i.TweetDate=j.retweetDate tweets=(tweets+retweets) tweets.sort(key=keymaker,reverse=True) I retrieve all the tweets ordered by date. then I retrieve all of retweets and make a list out of them and change the data of tweet to the date saved in intermediate table and merge both lists and sort them by date. I want to know is there a better way or more standard way to do this? Thanks in advance. -
How can I store user ip and warn him if his current ip is different from the previous one on Django?
I'm working on doing a blog on Django for a project and I've created everything about login, registration and forum... The last step is to create a logging system which stores the last Ip accessing the platform for a certain user and shows a warning message if it is different from the the previous one... logger = logging.getLogger(__name__) logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { 'format': '[%(asctime)s] %(name)-12s %(levelname)-8s %(message)s' }, 'file': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'console' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'formatter': 'file', 'filename': '/tmp/debug.log' } }, 'loggers': { '': { 'level': 'DEBUG', 'handlers': ['console', 'file'] } } }) def login_page(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-0] else: ip = request.META.get('REMOTE_ADDR') if user is not None: logger.info("".join([ip, " : ", username, " logged in"])) login (request, user) return redirect("../") else: messages.error(request, "Username o Password Errati... Riprova!") return render(request, 'login.html') I have added some code to my login view to show information when a user sign in and it works... I don't know how can I continue, I … -
How to make forms and add data for 4 nested one-to-many relationships in Django?
I have 4 models: Corporation, Division, Store and Section. Corporation has one or many divisions, division has one or many stores and store has one or many sections. I need to make a html which will allow adding corporation, then many divisions for that corporation and for every division possibility to add stores and so on. That has to be on the same page. For every model there needs to be add button which will open form for adding desired object and delete button which will remove object if user changes its mind. If user clicks 'add store', form for store will show up inside division in which store needs to be added. I don't know how to manage that and organize forms and how to pack data back through POST nor how to unpack it and save into database. I have tried manually making all fields that I need on html and not bounding it to any django form and packing all data in json, then sending it through ajax, but it's very tiresome and ugly, because I have to pack four level nested json and do the unpacking on the back and again manually save every object. -
Django Async Views, AsyncIO
Is it available to call an async function inside django main view function, and return main before the second is continuing its execution? As video convert is taking too long, I need to return media paths before convert finishes. views.py async def optimize(request): serializer_data = FileUploadSerializer(data=request.FILES).custom_validation() media_paths = {} for data in serializer_data.validated_data: #converting video if data == 'video': media_paths['video'] = [] for file in serializer_data.validated_data['video']: file_path = file.file.name file_name = generate_file_name() new_path = os.path.join(settings.BASE_DIR, 'media') extension = file.name.rsplit('.', 1)[-1] loop = asyncio.get_event_loop() loop.create_task(video_converter.start_convert(file_path, file_name, new_path)) # loop.run_until_complete(video_converter.start_convert(file_path, file_name, new_path)) media_paths['video'].append(request.build_absolute_uri() + "media/video/" + file_name + "." + extension) return JsonResponse(media_paths) video_converter.py clip = VideoFileClip(f"{file_path}") if round(clip.w/clip.h, 2) == 1.78: if clip.h < 720: clip.write_videofile(f"{new_path}\\video\{file_name}.mp4", fps=24) clip.close() else: clip_resized = clip.resize(height=720) clip_resized.write_videofile(f"{new_path}\\video\{file_name}.mp4", fps=24) clip.close() return new_path + file_name + '.mp4' else: clip.close() raise Exception("Uploaded video resolution is not supported") -
How to get the current user time zone? Django
I'm trying to get my Django app work with the current user time zone but I'm not getting any results... In my settings.py file I set: TIME_ZONE = 'UTC' and in my views.py I set at the top of the code: activate(settings.TIME_ZONE) But this is not working, while creating a post, is getting my last time zone that was 'Madrid', instead of my current time zone. Is there a way to make this work? Thank you! -
Double reverse filtering in Django ORM
I am facing one issue while filtering the data . I am having three models ... class Product: size = models.CharField(max_length=200) class Make(models.Model): name = models.ForeignKey(Product, related_name='product_set') class MakeContent(models.Model): make = models.ForeignKey(Make, related_name='make_set') published = models.BooleanField() I can generate a queryset that contains all Makes and each one's related MakeContents where published = True. Make.objects.filter(make_set__published=True) I'd like to know if it's possible (without writing SQL directly) for me to generate a queryset that contains all Product and each one's related MakeContents where published = True. I have tried this Product.objects.filter(product_set__make_set__published=True) But it's not working -
Proper File Structure For Sending E-Mails In Django
I'm sending many e-mails from within my Django views like this if form.is_valid(): form.save() # email contents first_name = form.cleaned_data['first_name'] surname = form.cleaned_data['surname'] full_name = first_name + ' ' + surname from_email = form.cleaned_data['email'] try: html_content = """ <p>HEADING</p> <p>Sent from: """+ full_name +""".</p> <p>Email address: """+ from_email +""".</p> """ email = EmailMessage('TITLE', html_content, 'example@gmail.com', ['example@gmail.com']) email.content_subtype = "html" email.send() except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('example', first_name=first_name) But I'm sure there has to be a standard file structure and way to separate the logic when sending e-mails. If there is, or if anyone has any tidy ways to organise the contents of many emails rather than having them bloating my views, please share :). Thank you. -
django-allauth facebook login issue with facebook accounts that is not connected to any email address
I have a site where users have to login only using facebook. Most of time it works fine. But sometimes, when user logins with facebook, it again asks for email address. But I have a new issue. Those facebook made with mobile number and not any email address connected to it are not able to login. So how can i solve this problem ? I am using django-allauth for social login. -
Heroku Django DB connection
I have an eLearning application developed in Django and deployed on Heroku. But I am facing one issue that is the local testing data that I have created is not reflected on the Heroku server. My application is successfully been deployed and is working like a charm but I don't have data on the Heroku server. Like on my local machine I have a username and password to login into the application and it works well on my local system but not on Heroku, the form gets displayed but I cannot log in. The error is that the data entry doesn't exist. Even some static data which gets rendered onto the home page is also not displayed. Is there any command which I need to run to upload my data from the local machine to the Heroku server? I have already used this command heroku run python manage.py migrate and then also pushed the updated version of the project to the Heroku master branch with git push heroku master after doing the commit. But still, no data is reflected onto the server. I have also tried the command heroku pg:push but it gives me missing two arguments error. Can someone … -
'Manager' object has no attribute 'normalize_email'
I have a fairly simple model with a many-to-many relationship: class Person(AbstractUser): ... topics = models.ManyToManyField("web.Topic", through="Interests", blank=True) ... objects = models.Manager() def __str__(self): return "{last}, {first} ({id})".format( last=self.last_name, first=self.first_name, id=self.id ) class Meta: ordering = ("last_name", "first_name") Based on that model, I have a form defined by: class TopicForm(ModelForm): class Meta: model = Person fields = ("topics",) def __init__(self, *args, **kwargs): super(TopicForm, self).__init__(*args, **kwargs) self.fields["topics"].widget = SelectMultiple(attrs={"size": 20}) self.fields["topics"].queryset = Topic.objects.order_by(Lower("name")).all() self.fields[ "topics" ].help_text = "Don't forget to hold the CTRL key (or cmd on a Mac) to select multiple topics" Finally, the view looks like: def update_my_profile(request): topics_form = TopicForm(request.POST or None, instance=request.user) if request.method == "POST": if topics_form.is_valid(): topics_form.save() context = { "topics_form": topics_form, } return render(request, "web/profile.html", context) for a reason I really don't get, the django framework is failing on if topics_form.is_valid(): I get the following error message: 'Manager' object has no attribute 'normalize_email' Surprinsingly, the failing code is within the django framework (django/contrib/auth/models.py in clean at line 365): def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) Even more surprisingly, if I put a breakpoint (in VSCode) at the line if topics_form.is_valid(): and run the command manually in the debug console, it does not fail... what did … -
Adjusting images in django templates
I am working on a django website, the code works pretty well but I'd like to make a few adjustments in order to make the web more professional. There's a section in the web called latest posts. Here's the code: <!-- Latest Posts --> <section class="latest-posts"> <div class="container"> <header> <h2>Latest from the blog</h2> <p class="text-big">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </header> <div class="row"> {% for obj in latest %} <div class="post col-md-4"> <div class="post-thumbnail"><a href="#"><img src="{{ obj.thumbnail.url }}" alt="..." class="img-fluid"></a></div> #Here's the image <div class="post-details"> <div class="post-meta d-flex justify-content-between"> <div class="date">{{ obj.date }}</div> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> </div><a href="#"> <h3 class="h4">{{ obj.title }}</h3></a> <p class="text-muted">{{ obj.overview }}</p> </div> </div> {% endfor %} </div> </div> </section> What you can see in the website is this: As you might have noticed, the images aren't adjusted and therefore, the text doesn't look aligned. Is there any code that can adjust this so that it looks like this? -
How to Write Custom Username validation using Self.clean_username for Profile Update form in Django?
I am newbie and i'm still learning django. If i've written something wrong please help me to correct it. Don't downvote the question. Hi i am writing my custom form validation for user profile update. My profile update form has - username first name last name profile image First i have used default form validation. It is also good but i want to update the error message so i tried to create a custom validation function as i seen in a post in stackoverflow. Please also check my username validation in forms.py So what is the error now? Now i am facing one more issues If i click on update button without changing anything then it shows can't use this username. {username is set to unique=True in model fields} If i don't update username and update just first name and last name. It doesn't allow this says same error. "Username is already taken" {because that username is validated and it already taken by current user"} what exactly i want? Instead of changing just error message now i want to write my own validation for this. I want if some click on update without changing any data no error message should … -
More optimal Database Design (Django) (PostgreSQL)
I have a SQL database table called Emp_Mast. This is quite a big table with around 70 columns and about 2000 rows. I have a few foreign key relations (eg Desgn_Mast) that need the history of their changes to be recorded. To do this another table is maintained called Desgn_Trans which will eventually have around 10000 records but only 4-5 columns. Here are the Table structures: Emp_Mast emp_mast_id (pk) fname mname lname desgn_mast (fk) ...... (around 65 more columns) Desgn_Mast desgn_mast_id (pk) desgn_name Desgn_Trans desgn_trans_id (pk) emp_mast_id (fk) desgn_mast_id (fk) created_date_time Currently whenever a change is made in desgn of the employee I update both the tables (Emp_Mast) and (Desgn_Trans). A PATCH request is made to Emp_mast and POST request is made to desgn_trans for any change. However this seems redundant and wasteful. The other option I have is to remove the column 'desgn_mast' from Emp_mast altogether, however the issue I think I will face is that I will have to query two tables - Emp_mast & Desgn_trans to get both the employee and desgn data. When the tables get large I think the speed overhead will be significant. Can someone please comment on which is the better design approach? -
Hi guys, I'm working on Writing your first Django app, part 2 tutorial, and I tried _str_() function and it doesn't give me the same result
this is my Question class in models.py : class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def _str_(self): return self.question_text when I execute : Question.objects.all() it gives me : <QuerySet [<Question: Question object (1)>, <Question: Question object (2)>]> any ideas ??? -
can't update checkbox in django template for loop table from model object, using jquery. jquery doesn't iterate with django loop
I have a dynamic table using for-loop in django template, it contains a checkbox on each row which I want to update as checked or unchecked from the boolean model object which is already available in the template, on loading the page. I have the code on template as: <tbody id="order_list_body"> {% for item in items %} <tr height="50px"> <td align="center"> {{item.item}} </td> <td align="center"> {{item.price}} </td> <td align="center"> {{item.stock}} </td> <td align="center"> <input type="checkbox" id="available" name="available" > {{item.available}} </td> <td align="center"> <a href="{% url 'order' %}" class="btn btn-info">Edit</a> <a href="{% url 'order' %}" class="btn btn-warning" >Delete</a> </td> </tr> //jquery to update the checkbox with the 'item.available' boolean <script> $(document).ready(function(){ if ('{{item.available}}' == 'True'){ $('#available').prop('checked', true); console.log("checked {{item.item}} as {{item.available}} in the true loop"); } else if ('{{item.available}}' == 'False'){ $('#available').prop('checked', false); console.log("checked {{item.item}} as {{item.available}} in the false loop"); } }); </script> {% endfor %} But somehow the javascript is not updating the checkboxes according to the boolean 'item.available' on the load of page. console.log gives : checked item1 as True in the true loop (index):197 checked item2 as False in the false loop (index):270 checked item4 as True in the true loop (index):353 checked item6 as False in … -
How to run this code inside a view function in views.py? urgent. thank you
import cv2 import pandas as pd import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() img = cv2.imread(file_path) clicked = False r = g = b = xpos = ypos = 0 index = ["color", "color_name", "hex", "R", "G", "B"] csv = pd.read_csv('codes.csv', names=index, header=None) def getColorName(r, g, b): minimum = 10000 for i in range(len(csv)): d = abs(r - int(csv.loc[i, "R"])) + abs(g - int(csv.loc[i, "G"])) + abs(b - int(csv.loc[i, "B"])) if d <= minimum: minimum = d colorname = csv.loc[i, "color_name"] return colorname def draw_function(event, x, y, flags, param): if event == cv2.EVENT_MOUSEMOVE: global r, g, b, xpos, ypos, clicked clicked = True xpos = x ypos = y b, g, r = img[y, x] b = int(b) g = int(g) r = int(r) cv2.namedWindow('Machining Process Identification') cv2.setMouseCallback('Machining Process Identification', draw_function) while 1: cv2.imshow("Machining Process Identification", img) if clicked: cv2.rectangle(img, (20, 20), (380, 60), (b, g, r), -1) text = getColorName(r, g, b) cv2.putText(img, text, (50, 50), 2, 0.8, (255, 255, 255), 2, cv2.LINE_AA) if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyAllWindows() root.mainloop() -
NOT NULL constraint failed: forum_thread.title
i recently learn django and want to do some project and i thought lets a forum website but while making a discuss forum when i login and want to post query i got this error NOT NULL constraint failed: forum_thread.title models.py from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User from datetime import datetime class Thread(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) category = models.ForeignKey('category', related_name="Thread", on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() timestamp = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title class Category(models.Model): sno = models.AutoField(primary_key=True) name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) description = models.TextField() timestamp = models.DateTimeField(default=datetime.now, blank=True) class Meta: verbose_name_plural = "Categories" views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .models import Thread, Category def addThread(request): if request.method == "POST": thread_title = request.POST.get('threadtitle') thread_slug = request.POST.get('threadslug') thread_category = request.POST.get('threadcategory') thread_description = request.POST.get('threaddescription') user = request.user thread = Thread(title = thread_title, slug = thread_slug, category=thread_category, description = thread_description, user = user) thread.save() messages.success(request, 'thread added successfully') return redirect('home') -
Django get all the latest values of unique entries of a column in a Table
I want to get all the latest values of unique entries of a column in a Table. For Example I have a table like this, which is called Test |____id|____fk1|__created| | 1| 1| Nov 5| | 2| 1| Nov 2| | 3| 1| Nov 1| | 4| 2| Nov 4| | 5| 3| Nov 9| | 6| 3| Nov 7| Now I want to get all the entries in the table with unique 'fk1' values but the row where the 'created' column has the latest date. I want Django to return the queryset of the following rows |____id|____fk1|__created| | 1| 1| Nov 5| | 4| 2| Nov 4| | 5| 3| Nov 9| What is a efficient Django way to do this?