Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to hide password with ********* on swagger UI with Django
Can you please tell what should i do to to hide the password with ***** when i entering on the swagger UI , and value should be passed to the argument correctly -
Django model inheritance primary keys
I am using Django model inheritance. Similar to the example from the documentation: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) Since "Each model corresponds to its own database table", how are primary keys assigned? Do I have any guarantee that there are no collisions between the restaurant _id values and the Place _id values? How strong is this guarantee (Will the DB enforce it)? -
How to Develop individual dashboard interphase for different users
Hello fellow developers, I am at an intermediate level in Backend Development using Django. I need to create a dashboard system whereby different users can create an account which automatically creates a Bar for them on which they can view their individual analytics on it. I am not sure of what specific keyword to use to search for my request, but I think it's somewhat close to a multivendor system. I would be glad to have recommendations as to how to get this done or references to simple systems similar to this or tutorials. Thanks in advanvce. -
Django or React for a website ? What should I use [closed]
I want to build a website but I can’t decide that should I use Django or React.js because they both are awesome but there is one thing that I can’t find In React and that is smtplib because the website I am building has to send mails to me and I know about Firebase but it has some limits, is there any good alternative to smtplib in React. -
why cant i access my django website on heroku
2020-12-07T09:11:23.229280+00:00 app[web.1]: File "", line 971, in _find_and_load 2020-12-07T09:11:23.229280+00:00 app[web.1]: File "", line 953, in _find_and_load_unlocked 2020-12-07T09:11:23.229284+00:00 app[web.1]: ModuleNotFoundError: No module named 'STOCK' 2020-12-07T09:11:23.229493+00:00 app[web.1]: [2020-12-07 09:11:23 +0000] [12] [INFO] Worker exiting (pid: 12) 2020-12-07T09:11:23.312182+00:00 heroku[web.1]: Process exited with status 3 2020-12-07T09:11:23.354768+00:00 heroku[web.1]: State changed from starting to crashed 2020-12-07T09:11:26.483885+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=stockwares.herokuapp.com request_id=886eaa6b-6294-49e8-a765-634918f2e93b fwd="223.236.7.136" dyno= connect= service= status=503 bytes= protocol=https 2020-12-07T09:11:28.426668+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=stockwares.herokuapp.com request_id=f89b8ecb-bbc3-4004-93a3-63dd230a3b73 fwd="223.236.7.136" dyno= connect= service= status=503 bytes= protocol=https 2020-12-07T09:12:41.759328+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=stockwares.herokuapp.com request_id=ab605bed-037f-4f76-b3b9-bccf30882066 fwd="223.236.7.136" dyno= connect= service= status=503 bytes= protocol=https 2020-12-07T09:12:42.571231+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=stockwares.herokuapp.com request_id=ab5dfcf0-beeb-4f3b-b65e-1ba34acde43c fwd="223.236.7.136" dyno= connect= service= status=503 bytes= protocol=http -
Python : name 'set_password' is not defined
Im trying to register users hashing their passwords before add to database as follows settings.py PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) Models.py from django.contrib.auth.models import AbstractBaseUser class Users(AbstractBaseUser): name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=255) Views.py name = form.cleaned_data.get('name') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') date_joined = date.today() if Users.objects.filter(email=email).exists() and Users.objects.filter(name=name).exists() : messages.info(request, 'User already exists') else: Users.objects.create(name=name, email=email, password=set_password(password), date_joined=date_joined) but when i actually trying to create the user i get Python : name 'set_password' is not defined What is wrong? do i need to import something at Views.py? -
Generate CSV while saving the django Model
In my django model I have start and end date once I filled and then click the generate button (Save modified as Generate) It will save and download the data as CSV. In my case I have done all the parts but the csv is not downloaded because the form is reloaded and then come back to list data page. I want to download the csv file after data saved.