Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to know the receiver email in django email
I create a webform where user can enter name, subject, message and email. This is how i recieve in views.py files name=request.POST['name'] email=request.POST['email'] subject=request.POST['subject'] message=request.POST['message'] print(name,email,subject,message) send_mail( subject=subject, message=name +'\n'+ message, from_email=email, recipient_list=['myemail@gmail.com'], fail_silently=False, ) The email received to me is via the email which I have defined in settings.py as EMAIL_HOST_USER. I have no clue who the sender is? One way is to add the email in message parameter. Then to reply user, i have to copy the email id from the mail body and then paste it To of gmail and then I can send it back. Is there a way, instead of receiving email from my mail ID, i get it from sender email ID, so i can reply. Thanks -
Problem when deleting ImageField from database
models.py: Picture = models.ImageField('Picture', null=True, blank=True) When I give the command person.Picture.delete() the picture is deleted from the directory, but in the database still has the record of the file path in Picture as shown in image below. How can I delete it? -
django - No such file or directory: '/static/album.html' in production
i created a django app which is working absolutely fine in my local server but when i'm deploying it to azure web app it's homepage is working fine but some tasks in views.py file of my project even after running collectstatic command is not working and giving this error csss & js files are loading but the file i want to load in getData fn is not loading. here is views.py file of my app. from django.shortcuts import render, HttpResponse from django.templatetags.static import static import requests from bs4 import BeautifulSoup import pandas as pd import os def index(request): return render(request, 'main.html') def getData(request): num = 0 album = [] song = [] streams = [] b = [] temp = open(static("album.html"), "w") temp.close() and this is how my my settings.py file looks STATIC_URL = '/static/' STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [ BASE_DIR / "static" ] this is how my project's folder directory looks like hello is my project name (lol) and jdbsdata is my app and the 'staticfiles' folder is created automatically after running collectstatic command but main static folder is the 'static' one Help me please why it can't locate static folder in views.py … -
Django include app from another project url problem
First of all, hello everyone, thank you in advance to anyone who can help. I'm coding a video site with Django. I wanted to add a custom admin panel to my project to add videos to the website and do other things. I downloaded the admin panel here and am trying to include it as an app in my project. But I could not fully grasp the connection between the app's (I've been using django for 2 weeks) My project has a manage.py and sqlite database file, the same is in the admin panel I downloaded. When I run it from the manage.py file of the admin panel, I can access the admin panel without any problems, but this time I am having trouble accessing the urls of my video site. My project file structure, dashboard is the admin panel i downloaded. File structure of the admin panel You can review the admin panel codes click here. myblog/myblog/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('base.urls')), path('dashboard/',include('dashboard.apps.home.urls')), path('dashboard/',include('dashboard.apps.authentication.urls')) myblog/base/urls.py urlpatterns = [ path('',views.index,name="index"), path('main/',views.main,name="main"), path('video/<slug:slug>/',views.video,name="video"), path('test/',views.addVideo,name="addVideo"), path('apivideo/',views.apivideo,name="apivideo"), ] -
django.db.utils.OperationalError when running MySQL/MariaDB in Docker: Lost connection to MySQL server at 'reading initial communication packet'
Running Django version 4 locally with: manage.py runserver 127.0.0.1:8000 And running MySQL/MariaDB in a Docker container: docker run -p 3306:3306 --name $(DATABASE_NAME) -v /tmp/mysql:/var/lib/mysql -e MYSQL_DATABASE=$(DATABASE_NAME) -e MYSQL_USER=$(DATABASE_USER) -e MYSQL_ROOT_PASSWORD=$(DATABASE_PASSWORD) -d mariadb:latest > /dev/null Error django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 2") I can successfully connect to the database with MySQL Workbench as well as the command: mysql -h 127.0.0.1 -P 3306 -u root -p <database> I am launching Django and the MySQL/MariaDB Docker container from a Makefile. Makefile SHELL := /bin/bash .PHONY: dj-start-local dj-start-local: start-mysql PYTHONPATH=. django_project/src/manage.py runserver 127.0.0.1:8000 .PHONY: start-mysql start-mysql: docker run -p 3306:3306 --name $(DATABASE_NAME) -v /tmp/mysql:/var/lib/mysql -e MYSQL_DATABASE=$(DATABASE_NAME) -e MYSQL_USER=$(DATABASE_USER) -e MYSQL_ROOT_PASSWORD=$(DATABASE_PASSWORD) -d mariadb:latest > /dev/null -
Django get related object's QuerySet inside annotate
My Models class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) #Unnecessary class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_comments") post = models.ForeignKey(Post, on_delete=models.CASCADE,related_name="post_comments") liked_users = models.ManyToManyField(User, blank=True, related_name="liked_comments") disliked_users = models.ManyToManyField(User, blank=True related_name="disliked_comments") #Unnecessary What I Have Normally, i use this code to make my comment objects have the attribute "voting" and order them by that attribute. comments = models.Comment.objects.annotate(voting=Count("liked_users")-Count("disliked_users")).order_by("-voting") But when I want to query posts, I can't reach their comments: What I Want I want my QuerySet "posts" to have an attribute for every single post, called "best_3_comments". Which is a QuerySet of comments of them ordered by their voting's. Can I achieve this without querying all of the comments everytime I query posts? posts = models.Post.objects.annotate( best_3_comments = get_query_of_the_posts_comments("post_comments").annotate( voting=Count("liked_users")-Count("disliked_users") ).order_by("-voting")[:3] ) What function(s) can i use to get query of the post's comments, and how should i approach this ? I'm completely open to new ideas of ways to do what I want to achieve, I couldn't find which function and how to use for it. Thank you in advance. -
Django Queryset to include and filter related data
I'm trying to render a template with a list of participants (adult and minor) and their latest checkin and checkout times. There are two types of participants and they are represented in two tables/models: AdultParticipant and MinorParticipant. MinorParticipants have a foreign key relationship to the ParentParticipant. Checkin information (checkin and checkout) is stored in a single table irregardless of whether the checkin data refers to AdultParticipant or the MinorParticipant. One record in this table captures the participant reference and the checkin and checkout times. Any participant can have many checkins. A checkin record can only have one participant. The code as it exists now does everything I want except it displays every checkin record for the participant. I only want to display the last (most recent) record for the participant. How can I construct the queryset to include the participant information and include only the last checkin record for the participant? Thank you in advance. You are appreciated. Models class AdultParticipant(models.Model): first_name = models.CharField(max_length=50) middle_initial = models.CharField(max_length=50, blank=True) class MinorParticipant(models.Model): first_name = models.CharField(max_length=50) middle_initial = models.CharField(max_length=50, blank=True) parent = models.ForeignKey( WaiverAdult, on_delete=models.CASCADE, related_name='minor_of_adult') class CheckIn(models.Model): adult = models.ForeignKey( AdultParticipant, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin') minor = models.ForeignKey( MinorParticipant, on_delete=models.CASCADE, blank=True, null=True, … -
twilio + django calling from browsers
hello working on django app, I set up twilio voice calls in my app, I realised that users can't call in all browsers, but only brave browser, what might be the problem, and how can I solve it? -
How do I separate the attributes of a class in a Django admin form in sections?
Django admin site shows the attributes of a class in a form so you can add a new object, I want to know if there is an easy way to separate the attributes in sections to make the form more organized, like having a "Physical features" section title over fields about physical features, similar to how inline attibutes work having the name of the inline class as a section name. -
Django viewset annotate in subquery based on filterset field
It seems like this should be a common use case but i cant find an existing answer online. I am trying to annotate a count based on a query that is filtered using a filterset field in DRF. class SurveyViewset(viewsets.ModelViewSet): entries = models.SurveyEntry.objects.filter( survey=OuterRef("id") ).order_by().annotate( count=Func(F('id'), function='Count') ).values('count') queryset = models.Survey.objects.annotate( total_entries=Subquery(entries) ).all().order_by("id") serializer_class = serializers.SurveySerializer filter_backends = ( SurveyQueryParamsValidator, CaseInsensitiveOrderingFilter, django_filters.DjangoFilterBackend, SearchFilter, ) filterset_fields = { "surveyaddressgroup": ("exact",), } I have surveys and I want to count the number of SurveyEntry based on a a particular address group. I.e. I ask a survey in a several shopping centres, and I want to see the results when i only choose 1 particular centre to show. At the moment, I get total count regardless of filter the main query. How can i make the subquery take the filterset choice into account? -
In Django's models.Manager create method, how do I store a random object in a foreignkey field?
I am able to create Game objects that have the product_selection field being populated correctly, but for some reason, the correct_product field is not getting populated. Why is that? Here is my code from models.py: import random class GameManager(models.Manager): def create_game(self, player): game = self.create(player = player) product_selection = random.sample(list(Product.objects.exclude(users_who_viewed=player)),3) game.product_selection.set(product_selection) game.correct_product = random.choice(product_selection) return game class Game(models.Model): player = models.ForeignKey(User, on_delete= models.CASCADE,related_name='costcorrect_player') score = models.IntegerField(default=0) product_selection = models.ManyToManyField(Product, blank=True, null=True) correct_product = models.ForeignKey(Product, on_delete= models.CASCADE, related_name='costcorrect_correct_product', null=True) objects = GameManager() -
Heroku with waitress and django
I am trying to use waitress because I am on windows. I cant seem to quite get the Procfile right. This is everything in that file right now. import waitress from waitress import serve web: waitress-serve --port=$PORT QRCodes.wsgi:application There is a yellow warning under 'port' and a red error under '$PORT'. I have looked everywhere and cannot find a solution to this. Please help! -
Can't select related category in Django
I have 2 models class InnerCategory(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Product(models.Model): name = models.CharField(max_length=70) category = models.ForeignKey(InnerCategory, null=True, on_delete=models.SET_NULL) slug = models.SlugField(unique=True) so i'm trying to get Product queryset and select related Category like so queryset = Product.products.filter( category__slug=self.kwargs['category_slug'] ).select_related('category') print(queryset.category) and when i try to run this page i get an error AttributeError: 'QuerySet' object has no attribute 'category' so how can i get all my Products and Categories in one query -
How to fix "There is no current event loop in thread" when using Celery to execute an asyncio coroutine?
I need to execute an coroutine that establishes websocket streams from a Celery Task in my Django application, but it throws RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-1_0'. When I insert set_event_loop between new_event_loop and run_until_complete it's still the same error. What could be the solution ? tasks.py from myapp.celery import app import nest_asyncio nest_asyncio.apply() @app.task(bind=True, name='Websocket starter') def ws_starter(self): ws_loops() methods.py import asyncio import nest_asyncio nest_asyncio.apply() def ws_loops(self): async def method_loop(args): while True: try: do_stuff() except ccxt.NetworkError as e: break await client.close() async def clients_loop(loop, dic): do_stuff() await asyncio.gather(method_loop(args)) await client.close() async def main(loop): do_stuff() loops = [clients_loop(loop, dic) for dic in lst] await asyncio.gather(*loops) loop = asyncio.new_event_loop() # asyncio.set_event_loop(asyncio.new_event_loop()) loop.run_until_complete(main(loop)) setings.py os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" -
Django Forms: Select a valid choice. That choice is not one of the available choices
I am using Django as a CRUD app to run on a Postgresql database. Every quarter, data is added, and I need a way to update the underlying data. I have a form set up, but when I try to save the form, I get met with "Select a valid choice. That choice is not one of the available choices." I have other forms (that work) set up on my app that do not have this issue, and the code is similar for those. Can anyone tell me what is happening here? forms.py: class MarketViewForm(ModelForm): class Meta: model = MarketView fields = "__all__" widgets = { 'marketview_entry' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Marketview Entry'}), 'costarid' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Costar ID'}), 'direct_available' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Direct Available Space'}), 'direct_vacant' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Direct Vacant Space'}), 'sublet_available' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Sublet Available Space'}), 'status' : forms.Select(attrs={'class' : 'form-control', 'placeholder': 'Development Status'}), 'import_date' : forms.SelectDateWidget(attrs={'class' : 'form-control', 'placeholder': 'Import Date'}) } labels = { 'marketview_entry' : "Marketview Entry", 'id' : "ID", 'direct_available' : "Direct Available Space", 'direct_vacant' : "Direct Vacant Space", 'sublet_available' : "Sublet Available Space", 'status' : "Development Status", 'import_date' : "Import Date" } … -
How do you run a function to compare two date by month?
I'm trying to run a function to compare today's month with the month input by a user. The dates will be input by the user as 'YYYY-MM-DD'. This is what I have so far: class Sneaker(models.Model): name = models.CharField(max_length=100) brand = models.CharField(max_length=100) description = models.TextField(max_length=250) date = models.DateField('release date') price = models.IntegerField() def worn_for_the_month(self): return self.worn_set.filter(date=date.today().month).count == date.month But get the following error: fromisoformat: argument must be str So I tried using the following function instead with string: def worn_for_the_month(self): return self.worn_set.filter(date=str(date.month)) == str(date.month) And I get this error: %(value)s” value has an invalid date format. It must be in YYYY-MM-DD format. I'm not sure if I'm using the right type of function at this point. I just want to compare the month we're in with the one the user entered. -
Django Forms : How to show objects in a dropbox based on the user's group(in the Django admin)
I have a list of all categories mentioned in the models.py. I'm trying to filter categories based on the group defined in django admin. Can somebody suggest me how to get this done. Please let me know if you need anymore info. Thanks in advance for your inputs. models.py class Post(models.Model): # No Role Required WATCHLIST = "Watchlist" LESSON = "Lesson/Review" GENERAL = "General" # Blogger Role Required ANALYSIS = "Analysis" MILESTONE = "Milestone" FEATURES = "Features" TUTORIALS = "Tutorials" CAREERS = "Careers" COMMUNITY = "Community" # Founder Role Required # FOUNDER = "Founders Journey" CATEGORY_CHOICES = [ # No Role Required (WATCHLIST, "Watchlist"), (LESSON, "Lesson/Review"), (GENERAL, "General"), # Blogger Role Required (ANALYSIS, 'Analysis'), (MILESTONE, "Milestone"), (FEATURES, "Features"), (TUTORIALS, "Tutorials"), (CAREERS, "Careers"), (COMMUNITY, "Community"), ] forms.py class Meta: model = Post fields = [ "title", # "slug", "category", "associated_portfolios", "body", # "created_on", # "allow_comments", ] exclude = ('allow_comments',) # widgets = { # 'symbol': autocomplete.ModelSelect2Multiple(url='symbol-autocomplete'), # } def __init__(self, *args, **kwargs): super(PostCreateForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): if field.widget.attrs.get("class"): field.widget.attrs["class"] += " form-control" else: field.widget.attrs["class"] = "form-control" -
Write django query to select users and order users by latest conversation they had?
My models: class User(models.Model): id = models.UUIDField(primary_key=True) first_name = models.Charfield() class Conversation(models.Model): id = models.UUIDField(primary_key=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class Message(models.Model): id = models.UUIDField(primary_key=True) conversation = models.ForeignKey(Conversation, on_delete=models.PROTECT, null=False) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True, blank=True) I tried to to order by adding annotate and adding order by. Can some body help me to select all users and order them by the latest message they had. I need user with latest message at to and then accordingly. -
Django - Different user types in a DetailView
I have two user types: Buyer and Merchant and I want to display in a page details of the selected user but a detail view can only use one model My models class User(AbstractUser): is_buyer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_moderator = models.BooleanField(default=False) pgp = models.CharField(max_length=150, blank=True) date_created = models.DateTimeField(default=timezone.now) class Merchant(models.Model): # items user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return f'{self.user.username}' class Buyer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pin = models.CharField(max_length=6, blank=True) def __str__(self): return f'{self.user.username}' My views class ProfileDetailView(DetailView): model = User template_name = 'users/profile.html' slug_field = 'username' slug_url_kwarg = 'username' My template and url {% extends 'base.html' %} {% block content %} <article> <div> <p>{{ object.pgp }}</p> </div> </article> {% endblock %} path('profile/<str:username>', usersViews.ProfileDetailView.as_view(), name='user-profile'), The only thing that seems to work on the template is object.username, if I try using other names it wont show. What should I do? Create another model Profile? Change my current view or model? -
How can we merge two BytesIO buffer of video and audio into a single BytesIO object
I am using pytube which helps to download YouTube videos. It downloads videos with audio up to 720px after this resolution, it splits audio and video files separately to maintain quality. I want to merge those bytes objects into a single bytes object which can be downloaded. I have tried this from another StackOverflow question. import ffmpeg from io import BytesIO from pytube import YouTube def download_video(request): buffer=BytesIO() yt_test = YouTube(video_url) video = yt_test.streams.get_by_itag(137) input_video = ffmpeg.input(video) audio = yt_test.streams.get_by_itag(137) input_audio = ffmpeg.input(audio) combined = ffmpeg.concat(input_video, input_audio, v=1, a=1) combined.stream_to_buffer(buffer) buffer.seek(0) but this gives an error. Error: AttributeError: 'FilterableStream' object has no attribute 'stream_to_buffer' SO, I want to ask if there is any way that I can directly merge those audio and video bytes buffer using FFmpeg only or by another method so that I can further use that for download and other things according to my use case. -
Custom button in Django Admin page, that when clicked, will change the field of the model to True
I have a sample model in my Django App: class CustomerInformation(models.Model): # CustomerInformation Schema name=models.CharField(max_length=200, verbose_name="Name",default="Default Name") login_url=models.URLField(max_length=200, verbose_name="Login URL",default="") is_test=models.BooleanField(default=False,verbose_name="Test") I have to create a button on the Django Admin page for each entry of the model (which I have) that says "Test Integration", like this: [Screenshot of admin page Now once I click the button, the 'is_test' value for that specific CustomerInformation model, should be True. I haven't been able to do that so far. Here's what I have tried so far, thanks to Haki Benita's blog postBlog here: # admin.py class CustomerAdmin(admin.ModelAdmin): list_display = ( 'name', 'username', 'account_actions' ) def get_urls(self): urls = super().get_urls() custom_urls = [ url( r'^(?P<account_id>.+)/test_integration/$', self.admin_site.admin_view(self.test_integration), name='test-integration', ) ] return custom_urls + urls def test_integration(self, request, account_id, *args, **kwargs): return self.process_action( request=request, account_id=account_id ) def process_action(self,request,account_id): pass def account_actions(self, obj): return format_html( '<a class="button" href={}>Test Integration</a>', reverse('admin:test-integration', args=[obj.pk]), ) account_actions.short_description = 'Account Actions' account_actions.allow_tags = True I realize that I have to do something with the process_action and test_integration methods in this class to execute what I am wanting to do, but as a Django Beginner, I'm kinda lost. Any suggestions? Thank you so much!! -
sending scheduled emails over django
I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) start_time = models.TimeField(null=True) end_time = models.TimeField(null=True) and I want to send an email to all Users who have joined a particular Group 30 minutes before the start_time. For example: if a Group has a start_time of 1:00 PM, I want to send an email to all the joined Users at 12:30 PM, letting them know the group will be meeting soon. I've used the send_mail() function for other types of email notifications (like when a User joins or creates a Group) but I can't figure out how to send an email based on the start_time of Group. I've seen people say Celery is a way to do this, but I'm having trouble figuring out how to implement it in my django project. Will it conflict with the other email settings I already have? # Email settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = NOTIFICATION_EMAIL EMAIL_HOST_PASSWORD = NOTIFICATION_PASSWORD EMAIL_USE_TLS = True Is there a specific function I need to write and then call it in my Group model? Or do I call it in a view? … -
User bookings not appearing when logged in
me again. I still can't seem to get my user bookings to appear when the user is logged in. I know it is probably something super basic but I am just not seeing it. Here is the code I have written so far. I feel like a new set of eyes on this might help as I have been staring at it for days now. Thank you in advance for any help you can give. HTML: {% extends "base.html" %} {% block content %} <section id="booking" class="book_a_table"> <div class="booking_container"> <h2>My Bookings:</h2> <p>To edit or cancel a booking please click on the buttons below.</p> <div class="row"> <div class="col-md-3 mt-5 offset-md-3"> {% for booking in bookings %} <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> <h4 class='card-title text-uppercase text-center'>{{ booking.date }} at {{ booking.time }}</h4> <h6 class="text-uppercase">{{ booking.name }}</h6> <div class='card-text'> <p><i class="fas fa-phone"></i> {{ bookings.phone }}</p> <p><i class="far fa-envelope"></i> {{ bookings.email }}</p> <p>Number of People: {{ bookings.number_of_people }}</p> {%endfor%} </div> </div> </div> </section> View.py: class ListBookingView(generic.ListView): """ This is the view that will bring up the list of bookings for a particular users so that they can be edited or deleted """ model = Booking template_name = 'my_bookings.html' def get(self, request, *args, … -
Demo user accounts with dj-rest-auth
I need to have a demo account for my app. I'm using the stock views from dj-rest-auth to handle login, registration etc. How would I go about doing this? I want the user to click a button on the front end and sign in to this account without inputting credentials. -
Calling ModelViewset create() from another python file?
I would really appreciate some advice on this particular challenge I'm facing. I am using IMAP to receive emails ( on emails.py) and need to have some of the data in the email messages to be posted on an existing API endpoint (using DRF) and saved in my database. so far, I have come up with two ideas. Call the ModelViewSet create() method from emails.py. But I'm assuming that I would need to make sure that the request object is exactly the same as the one that is generated when an HTTP post request is made from the frontend. I'm afraid the metadata can get too complicated and leave room for messy errors. class RequestView(viewsets.ModelViewSet): serializer_class = RequestSerializer def get_queryset(self): queryset = Request.objects.all().select_related('user_id') user_id = self.request.query_params.get('user_id') if user_id is not None: queryset = Request.objects.filter(user_id=user_id).order_by('id') return queryset def create(self, request): # enter code here return super().create(request) Or I can make an HTTP request from emails.py. Does it make sense to have HTTP client code in a server-side framework? Per my research, I can use Python's requests library. Any input/advice would be greatly appreciated!