Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django ORM to sum annotated queries
I am using Django in combination with a TimescaleDB to process energy data from pv installations. Now I would like to calculate, how much energy multiple plants have generated within a given timebucket (usually per day). The plants writing the new values in a table which looks like that: customer datasource value timestamp 1 1 1 01.05.22 10:00 1 1 5 01.05.22 18:00 1 2 3 01.05.22 09:00 1 2 9 01.05.22 17:00 1 1 5 02.05.22 10:00 1 1 12 02.05.22 18:00 1 2 9 02.05.22 09:00 1 2 16 02.05.22 17:00 Now what I would like to have is, get the overal daily gain of values (so, for each day: Last Entry Value - (minus) First Entry Value) for each customer (which means, sum the daily generated energy values from all datasource which belong to the customer). In the above example that would be for customer 1: Day 01.05.22: Daily Gain of Datasource 1: 5 - 1 = 4 Daily Gain of Datasource 2: 9 - 3 = 6 Overall: 4 + 6 = 10 Day 02.05.22: Daily Gain of Datasource 1: 12 - 5 = 7 Daily Gain of Datasource 2: 16 - 9 = 7 Overall: … -
django import-export composite foreign key
I Have two models: ExternalListSettings and PriorityToolPartner. PriorityToolPartner has ForeignKey to ExternalListSettings. ExternalListSettings has complex primary key: import_date + partner. Csv file looks like this: import_date, partner, hotel_name, slug, bookings, num_in_sortorder How can i import PriorityToolPartner and combine ['import_date', 'partner'] into ForeignKey to ExternalListSettings model? Here are my models: class ExternalListSettings(DiModel): class Meta: verbose_name_plural = "External List Settings" unique_together = ['import_date', 'partner'] import_date = models.DateField( blank=False, null=False, ) partner = models.CharField( max_length=200, blank=False, null=False, ) is_top = models.BooleanField( blank=True, null=False, default=False, ) class PriorityToolPartner(DiModel): setting = models.ForeignKey( ExternalListSettings, null=False, blank=False, on_delete=models.CASCADE, default=0, ) hotel_name = models.CharField( max_length=200, blank=False, null=False, ) slug = models.CharField( max_length=300, blank=False, null=False, ) bookings = models.IntegerField( blank=True, null=True, ) num_in_sortorder = models.IntegerField( blank=True, null=True, ) -
HTMX integration with jsTree
I have integrated jsTree Library to load a tree structure menu. On click am using HTMX library to dynamically load content without page refresh. tree node click triggers well, but the htmx get request is only being sent on page load. My tree rerenders everytime I do an HTMX request since data tree is dynamic based on the request. Because I want even when I create a node (Folder), the structure itself should also refresh. Anyone who could have fully integrated such. -
python manage.py runserver : Exception in thread django-main-thread
To run django project after giving cmd "python manage.py runserver" I am getting following errors Please help to solve these errors. Errors -
The view budget.views.budget didn't return an HttpResponse object. It returned None instead
I recently added second form to my project and im struggling to make it work. The form is named AddIncome and when i fill the form and submit nothing happen, i don't see the new income. When i fill the income from admin panel on model page everthing works. Don't know how to make it work from main page. Here is my view (second form that i added is b_form, a_form is working): from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.db.models import Sum from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse from django.utils import timezone from .forms import AddIncome, AddItem from .models import BudgetData @login_required def budget(request): expense_items = BudgetData.objects.filter(user_expense=request.user).order_by( "-date_added" ) # Setting up pagination per expense_items paginator = Paginator(expense_items, 10, 3) # Show 10 items per page. page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) total_cost = BudgetData.objects.filter(user_expense=request.user).aggregate( Sum("cost") ) total_income = BudgetData.objects.filter(user_expense=request.user).aggregate( Sum("income") ) # AddItem{category, cost} form a_form = AddItem() b_form = AddIncome() # form = AddItem(use_required_attribute=False) # ignores the field required text if request.method == "POST" and "expense" in request.POST: a_form = AddItem(request.POST) if a_form.is_valid(): a_form = a_form.save(commit=False) a_form.user_expense = request.user a_form.date_added = timezone.now() a_form.save() … -
Websocket failed in live server. WebSocket connection to 'wss://www.my_domain.com:8001/' failed:
This is the error and maybe solving this will solve the problem of websocket failing. Anyone has an idea about this error? Thank you. May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: return any( May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: File "/home/django/Projects/env/lib/python3.8/site-packages/channels/security/websocket.py", line 74, in <gene> May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: pattern == "*" or self.match_allowed_origin(parsed_origin, pattern) May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: File "/home/django/Projects/env/lib/python3.8/site-packages/channels/security/websocket.py", line 98, in match> May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: parsed_pattern = urlparse(pattern.lower(), scheme=None) May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: File "/usr/lib/python3.8/urllib/parse.py", line 376, in urlparse May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: splitresult = urlsplit(url, scheme, allow_fragments) May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: File "/usr/lib/python3.8/urllib/parse.py", line 430, in urlsplit May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: scheme = scheme.replace(b, "") May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: AttributeError: 'NoneType' object has no attribute 'replace' -
Forbidden (CSRF token missing or incorrect.): /
So i want to make models form to upload file mp3. I was copy the code from website, but suddenly it goes error. Here's error message on the website : Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You're seeing the help section of this page because you have DEBUG = True in your Django … -
How to consume TokenAuthentication based user authentication built in DRF in Django web application
I have created a WebAPI for user authentication using Token Authentication built on Django Rest Framework. with the help of Postman I am able to determine that my user is being created, authenticated and logged out successfully. I have created a Django web application and have successfully consumed the WebAPI endpoints which do not require authentication in my HTML files. Now I wish to create user Login/Logout functionality and since I am new to the subject, I don't know how to do this. Please help? a link to a tutorial would be appreciated Regards, Arun -
How can I import the file in Django from a folder without Errors
Can someone help me with my problem? I have the following project structure: check_project --- check_app --- check_project --- modules --- __init__.py --- tools.py --- robots.py I need to import my tools.py file inside robots.py And here is the problem. If I import it this way from tools.py import * I can run the file inside Visual Studio Code and it works. But when I run Django it gives an Error: "ModuleNotFoundError: No module named 'tools'" And if I import it this way from modules.tools.py import * Django works fine. But when I run the file inside Visual Studio Code it gives Error: "ModuleNotFoundError: No module named 'modules'" How can I fix this problem so, that it would work both in Django and in Visual Studio? Thank you for your help ) -
Can I turn the form on and off in Django via the admin panel?
I am currently doing a restaurant website with Django and have a reservation form there in the form of a contact form. My question is whether I can control via the admin panel whether the form is displayed on the website and not? -
Reopening a closed django InMemoryFileUpload using class based views
I have a Django project which involves a user uploading a CSV file via a form. I parse this file in the forms clean method, and then in the views form_valid method I want to read the file data again (for the purposes of long term storage). My issue is that after parsing the file in the clean method, I'm no longer able to perform IO operations on the file object, any attempt to do so raises an error. Code as below: class MyForm(forms.Form): file = forms.FileField() def clean(self): cleaned_data = super().clean() file = cleaned_data["file"] reader = csv.DictReader(io.TextIOWrapper(file)) for row in reader: ... # process data return cleaned_data class MyView(generic.FormView): form_class = MyForm def form_valid(self, form): file = form.files["file"] file.read() # raises ValueError: I/O operation on closed file. At this point it's no longer possible to call other methods like file.open() either as this leads to the same exception being raised. What I am finding confusing about this is that there are other examples in my application of where IO operations can be performed on the file in the form_valid method, example below: class MyOtherForm(forms.Form): file = forms.FileField() class MyOtherView(generic.FormView): form_class = MyOtherForm def form_valid(self, form): file = form.files["file"] file.read() … -
only a single result allowed for a SELECT that is part of an expression with Django 3.0
I am using Django version 3.0 and Python version 3.7 When trying to save my job i am getting this issue only a single result allowed for a SELECT that is part of an expression Here is my views.py def convert_quote_to_job(request, pk): client = request.user.client quote_data = get_object_or_404(Quote, id=pk, client=client) user = request.user form = ConvertQuoteToJobForm(user=user) if request.POST: dob = request.POST.get('due_date') time_hour = request.POST.get('time_hour') time_minute = request.POST.get('time_minute') assigned_to = request.POST.getlist('assigned_to') maridian = 'AM' if int(time_hour) > 12: time_hour = int(time_hour)-12 maridian = 'PM' if int(time_hour) == 12: maridian = 'PM' form = ConvertQuoteToJobForm(request.POST, user=user) if form.is_valid(): job = form.save(commit=False) job.title = quote_data.job_title job.job_type = JobType.objects.filter(client=client, is_deleted=False).first() job.created_by = user job.contact_info = quote_data.address job.contact = quote_data.contact job.duration = (int(len(assigned_to))*int(request.POST.get('duration', '').strip())) job.quotes_id = pk job.client = client job.save() ..... ..... Here is my forms.py class ConvertQuoteToJobForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ConvertQuoteToJobForm, self).__init__(*args, **kwargs) client = self.user.client self.fields["assigned_to"] = forms.ModelMultipleChoiceField( widget=forms.SelectMultiple(attrs={'required': 'required'}), queryset=ClientUser.objects.filter(client=client). filter(Q(role__role_attribute='Job Worker') | Q(role__role_attribute='Job Worker with documents') | Q(role__role_attribute='Job Administrator') | Q(role__role_attribute='Job / Stock') | Q(role__role_attribute='Job / Stock / Opportunities') | Q(role__role_attribute='Job Worker / Stock')). exclude(is_active=False)) self.fields["duration"].required = True instance = getattr(self, 'instance', None) def clean(self): cleaned_data = super(ConvertQuoteToJobForm, self).clean() return cleaned_data class Meta: model = AddJob … -
Django: How to make json data readable in django?
i am trying to retrieve the lastest news from hackernews api, everthing seems to be working fine and when i print the status code, i get Status Code:200. Now i am getting some data but they are not readable this is how there are displayed b'[31349988,31344981,31348529,31344863,31341698,31348097,31347740,31348772,31347286,31348463,31345478,31348316,31345749,31347983,3' and this is code i used to retrieve the data from the api https://hackernews.api-docs.io/ def index(request): response = requests.get("https://hacker-news.firebaseio.com/v0/topstories.json") return render(request, "index.html", {'response': response}) -
Edit user permission in django admin, for custom user model
I have a custom user model as below: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='ایمیل', max_length=60, unique=True) username = models.CharField(verbose_name='نام کاربری', max_length=30, unique=True) ... USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Then I write a code like this in admin.py: @admin.register(Account) class PersonAdmin(ImportExportModelAdmin): list_display = ('email', 'username', 'phone_number', 'chart_level', 'chart_view_count') list_filter = ("is_admin", 'is_active', 'is_staff', 'chart_level', 'is_plus') search_fields = ['username', 'email', 'phone_number', 'referral_code'] readonly_fields = ("date_joined", "last_login", "chart_view_count", "id") fieldsets = ( ('اطلاعات فردی', { 'classes': ('collapse',), 'fields': ('email', 'username', 'phone_number', 'telegram_user_id', 'profile_image', 'date_joined', 'last_login', 'is_english', 'is_foreign', 'chart_view_count', 'password') }), ('اطلاعات خرید', { 'classes': ('collapse',), 'fields': ('used_referral_code', 'total_pay_r', 'total_pay_c', 'is_using_discount', 'using_discount_code', 'current_transaction_address', 'referral_code', 'is_first_payment') }), ('سطح کاربری', { 'classes': ('collapse',), 'fields': ('chart_level', 'is_plus', 'expiration_date', 'reserved_trader', 'is_admin', 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions') }), ) It works perfectly for thousands of users. now I want to add user permissions to change user page in admin panel, so I add "PermissionsMixin" like this: class Account(AbstractBaseUser, PermissionsMixin): ... then I tried to migrate and get this error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "accounts_account" what should I do? -
Create asyncio tasks indefinitely without blocking (django)
So, I'm trying to create a polling system internal to django commands for fun and to learn async/django. I'm using django_tenants, although it's not overly important. The idea is that there is a table that holds "tenants". I want to loop through those tenants in a higher infinite loop. For each tenant that isn't already in the async queue (perhaps because the process from the last time that tenant was found hasn't finished yet), I want to add a new asyncio task to be run. My test case has this one tenant which I wait 5 seconds for to ensure I get the internal queue/loop working. The idea is that, say there are 3 tenants: t_a, t_b and t_c, and t_a and t_c take 2 and 1 seconds respectively to run, with t_b taking 5. I would ultimate see the infinite loop running like this: t_c Done t_c Done t_a Done t_c Done t_c Done t_a Done t_c Done t_b Done t_c Done --- The long running one t_a Done .... So, t_c doesn't hold up the other tenants from being re-run. Each iteration of the tenants fetches NEW data as tenants might get created between runs. class Command(BaseCommand): help … -
Can Django render a React component that is using React-Router
I was building an application in Django and using templates for the majority of the application as I had simple html pages. I already have a sign in and sign up page as well as some portal pages. I tried react and started using it and building some components with the Django rest framework and I liked it for the majority but now I have the issue of routing. I was migrating the react build folders to the respective Django folders and have Django render the components. However, I built a user list where each user is clickable and takes me to an edit page (admin type). But once I migrated the component it simply did not render while other components rendered normally as they should. This is the list set up ReactDOM.render( <React.StrictMode> <Router> <App /> </Router> </React.StrictMode>, document.getElementById("root") ); Then I call a id "root" div in the index and that works fine in the react server but it does not render at all when I move it to the Django server. If I remove the router related code and make it a simple component it does render but means I will not be able to use routing … -
Getting Error Object of type bytes is not JSON serializable in django
I Everyone i my trying to to convert my response to to json its getting error which i have mention in question. how can i convert this response to json as per me problem is Decimal and b(byte), please help me out. Response. [{'number': '0001', 'name': 'john', 'total_trips': Decimal('32'), 'status': '', 'day1_trips': b'8', 'day2_trips': b'17', 'day3_trips': b'0', 'day4_trips': b'0', 'day5_trips': b'7', 'day6_trips': b'R', 'day7_trips': b'0'}] -
stripe CardError handle django
// value error // from django.shortcuts import redirect, render import stripe import stripe stripe.api_key = 'sk_test_' # Create your views here. def index(request): return render(request,'template/donate.html') def thanks(request): return render(request,'template/thanks.html') def cargo(request): card_num=request.POST['num_card'] month=request.POST['month'] year=request.POST['year'] cvv=request.POST['cvv'] if request.POST: token = stripe.Token.create( card={ "number": card_num, "exp_month": month, "exp_year": year, "cvc": cvv }, ) doc=stripe.Customer.create( email=request.POST['email'], name=request.POST['name'], source=token ) stripe.Charge.create( customer=doc, amount=request.POST['cantidad'], currency='cad', description= "DONATIVO" ) return render(request,'template/thanks.html') else: return render(request,'template/index.html') // stripe card error handle how to render errors in html page because it redirects me to a error page if client insert an invalid CVV or card num or expirationdate i think that i should try using stripe.error.CardError but documentation is not getting in my head // -
Websocket failed in live server , WebSocket connection to 'wss://my_domain.com:8001/' failed:
I am adapting websocket in django app, it was working but I don't know what happened it failed now. I used different channel layer code in live server and in local server. Any Idea about this problem? notification.js const ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; if (ws_scheme == 'wss') ws_path = ws_scheme + '://' + window.location.host + ":8001/"; else ws_path = ws_scheme + '://' + window.location.host; const notificationSocket = new WebSocket(ws_path); routing.py import os from decouple import config from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from django.urls import re_path, path os.environ.setdefault("DJANGO_SETTINGS_MODULE", f'{config("PROJECT_NAME")}.settings') django_asgi_app = get_asgi_application() from chatapp.consumers import ChatConsumer from notification.nconsumers import NotificationConsumer application = ProtocolTypeRouter({ "http": django_asgi_app, 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('chatapp/<int:room_id>/', ChatConsumer.as_asgi()), path('', NotificationConsumer.as_asgi()), ]) ) ), }) asgi.py import os import django from decouple import config from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", f'{config("PROJECT_NAME")}.settings') django.setup() application = get_default_application() consumers.py from django.conf import settings from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from chatapp.models import UnreadChatRoomMessages from notification.models import Notification class NotificationConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, code): pass settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'customer', 'notification', 'rest_framework', … -
Is Model.objects.update() in Django is synchronous? How to get updated rows after updating values?
I'm using Django with MySQL I want to get effected rows after run Model.objects.update() I have code below: # 1 User.objects.filter( pk__in=ids, status=old_status, ).update( status=new_status, pre_update_key=uuid_str, updated_at=datetime.datetime.now(), ) # 2 updated_users = list( User.objects.filter(pre_update_key=uuid_str).values() ) print(len(updated_users)) Results are different between environments Database 1: Users has 3000 rows => len(updated_users) != 0 is correct Database 2: Users has 300000 rows => len(updated_users) = 0 How can I get updated_users after #1 query is done completely? -
Django modifying admin edit interface
So here is my admin.py class ContentPageAdmin(admin.ModelAdmin): fields = (("category", "listing_title1", "show_listing1"),) the category is ManyToMany fields, listing_title1 is CharField, and show_listing1 is a BooleanField. Now it will display all of them in one line, but I want to put the show_listing1 below the listing_title1. How can I do that? -
No module named 'django.conf.urls.defaults'
I upgraded from django 3.2.5 to django 4.0.4. I know that this 'django.conf.urls.defaults' must be deprecated. My problem is that I don't get this error in the development environment but when I push to production, it shows the error. Why is this so??? Also I tried to locate the file so that I can change that line of code to the correct one but could find it's location. It's giving me this path which I can't see how to get to (/workspace/.heroku/python/lib/python3.9/site-packages/django/conf/urls/__init__.py)) -
Error ModuleNotFoundError: No module named 'api'
My Python program is throwing the following error: ModuleNotFoundError: No module named 'api' How to remove the ModuleNotFoundError: No module named 'api' error? -
Comments DateTimeField() Django
I'm trying to build a comments section in my website, and I'm pretty much done, but I'm trying to display the time that it was posted, but it keeps displaying the wrong time. This is my code in my models.py Posts class: ''' date = models.DateTimeField(default=timezone.now) ''' I know that the database recognizes something is wrong because it shows me this message: but I don't know how to fix it. Can someone please help me? Thanks! -
Calculating income and expense by filtering according to the entered date
I have a date picker and I will calculate income and expense based on this date. I want to add a parameter named random_date to my function in view.py. I want the user to set the end date. The start time will be today's date. For example, if the user has selected June 1 as the date, I want to sum the income and expenses from today to June 1st. How can I do that? Here is my views.py file: import datetime from django.shortcuts import render from incomes.models import Income, Source from expenses.models import Expense, Category from .models import SummaryModel # Create your views here. def Summary(request): todays_date = datetime.date.today() six_months_later = todays_date + datetime.timedelta(days=180) all_expenses = Expense.objects.filter(owner=request.user, date__gte=todays_date, date__lte=six_months_later) all_incomes = Income.objects.filter(owner=request.user, date__gte=todays_date, date__lte=six_months_later) def get_amount(EorI): amount = 0 for item in EorI: amount += item.amount return amount final_rep = {'Net_Income' : get_amount(all_incomes) - get_amount(all_expenses)} return render(request, 'summary.html', final_rep) Here is my summary.html file: <div class="card"> <div class="card-body"> </select> <div class="form-group"> <label for="">Choose a date</label> <input type="date" value="{{values.date | date:'Y-d-m'}}" class="form-control form-control-sm" name="random_date" /> </div> <input type="submit" value="Submit" class="btn btn-primary btn-primary-sm" /> <div class="container"> <div class="col s12 m12 l4"> <div class="card-panel"> <h8 class="bold">Net Budget</h8> <h1 class="bold">${{ Net_Income }}</h1> </div> …