Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
uWSGI call randomly injected into Python call stack?
I'm trying to get to the bottom of a weird bug (see here) - basically I'm seeing unexpected DB disconnects. To investigate I added a call stack dump to the disconnect code in Django - now I'm more confused than ever... What I'm seeing in the call stack is a completely unexpected call sequence, e.g.: ... File "/deployment/v_env/lib/python3.8/site-packages/qrcode/base.py", line 326, in __mod__ for item, other_item in zip(self, other)] File "/deployment/v_env/lib/python3.8/site-packages/qrcode/base.py", line 303, in __iter__ return iter(self.num) File "/deployment/v_env/lib/python3.8/site-packages/django/http/response.py", line 292, in close signals.request_finished.send(sender=self._handler_class) File "/deployment/v_env/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ ... Here the QR code library I'm using suddenly jumps to HttpResponse.close(). Another: ... File "/deployment/v_env/lib/python3.8/site-packages/django/db/models/query.py", line 1268, in _insert query = sql.InsertQuery(self.model, ignore_conflicts=ignore_conflicts) File "/deployment/v_env/lib/python3.8/site-packages/django/db/models/sql/subqueries.py", line 141, in __init__ super().__init__(*args, **kwargs) File "/deployment/v_env/lib/python3.8/site-packages/django/http/response.py", line 292, in close signals.request_finished.send(sender=self._handler_class) File "/deployment/v_env/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ ... Here some Django DB query code suddenly jumps to HttpResponse.close(). There's no way that this call stack is right - the code immediately above close() simply does not call that code, nor does it call a close() method that may somehow be bound to the wrong object. Now HttpResponse.close() can be called by uWSGI from the C runtime - the only … -
How to hide or delete the date in finish field without breaking the logic of the program
enter image description here Hi everybody. I am trying to solve this problem, but I do not know how to do it without breaking the logic of the program. I try to delete or hide the date field in finish because the difference between them will be no more than six hours. -
Design for Repetitive CRUD Operations with React and Django
I'm refactoring an old Django project (E-commerce) from server side rendered pages, to using a REST API instead and a React frontend. I'm trying to take learnings from the "v1" of the app and make them better in this refactor. Whilst there is a side to the app that offers business logic including e-commerce, payment functionality and customer facing storefront etc., the sort of "behind the scenes admin" functionality, like adding products, displaying them, adding coupons, displaying them etc., is all super repetitive. It's practically just a bunch of different Models with various fields and it's mostly just CRUD. Nothing complex at all. In the "v1" version, I leveraged Django's built in Forms for this and with this refactored version I plan on using Django REST and leverage their Generic Views and Viewsets where possible to reduce the amount of code needed, but also to keep it clean and generic. I'm a bit stuck on the frontend though. The idea of having to make a Create, Read, Update and Delete component for each "model" to show in the "dashboard" sounds awful. If it has to be done that way fine, but I'm wondering is there any sort of React library … -
django.core.exceptions.SynchronousOnlyOperation in Consumers.py
Here is the exception: Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. ... File "E:\socialnetwork\snsite\anime\consumers.py", line 48, in receive await self.fetch_messages() File "E:\socialnetwork\snsite\anime\consumers.py", line 21, in fetch_messages 'notifications': json.dumps(serializer.data) File "E:\socialnetwork\lib\site-packages\rest_framework\serializers.py", line 745, in data ret = super().data File "E:\socialnetwork\lib\site-packages\rest_framework\serializers.py", line 246, in data self._data = self.to_representation(self.instance) File "E:\socialnetwork\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation return [ File "E:\socialnetwork\lib\site-packages\django\db\models\query.py", line 280, in __iter__ self._fetch_all() File "E:\socialnetwork\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "E:\socialnetwork\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "E:\socialnetwork\lib\site-packages\django\db\models\sql\compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "E:\socialnetwork\lib\site-packages\django\utils\asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. WebSocket DISCONNECT /ws/like-comment-notification/ [127.0.0.1:50066] This is my consumers.py class NotificationConsumer(AsyncJsonWebsocketConsumer): async def fetch_messages(self): user = self.scope['user'] notifications = await database_sync_to_async(self.get_notifications)(user) serializer = NotificationSerializer(notifications, many=True) content ={ 'command': 'notifications', 'notifications': json.dumps(serializer.data) } await self.send_json(content) Although the WebSocket connection works but an error arises when it calls the fetch_message method. The problem seems to lie in json.dumps(serializer.data). Can you guys show me how to fix this? -
change django auth form password field error message
I have a form for my custom user sign up. like this: class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text='Required. Add a valid email address') class Meta: # model = User model = Account fields = ('username', 'email', 'password1', 'password2',) def __init__(self, *args, **kwargs): """ specifying styles to fields """ super(SignUpForm, self).__init__(*args, **kwargs) for field in ( self.fields['email'], self.fields['username'], self.fields['password1'], self.fields['password2']): field.widget.attrs.update({'class': 'form-control '}) now I want to override the error messages. specially for password fields. error text: password2 This password is too short. It must contain at least 8 characters.This password is too common.This password is entirely numeric. also I do not want that password2 word in the beggining. -
Running django with ASGI?
I have a django app I using this [docker] (https://github.com/tiangolo/uvicorn-gunicorn-docker) for production deployment when I run the app using: gunicorn --log-level debug --workers 3 myapp.asgi:application --worker-class uvicorn.workers.UvicornWorker I see the warning ASGI 'lifespan' protocol appears unsupported. after reading here I understand that django do not support, but is this have any effect on my app? or where should the effect be? My app is using sync endpoints, for example: class MyViewSet(viewsets.ModelViewSet): queryset = My.objects.all() serializer_class = MySerializer is by running using ASGI the call to the database would be async? I don't use any web sockets I can see online many version for the asgi.py file, with manny different middleware and the django.setup() keyword, where can I find a documentation about the use cases? -
how to dynamically update html table in django
how to dynamically update search content under the hostname column in HTML table. the search content needs to be updated every time and the row number should increase accordingly on the basis of number of hostname entered by the user. this is my index.html {% extends 'base.html' %} {% block title %} IP Finder {% endblock %} {% block body %} <body> <div> {% csrf_token %} <div class="form-group"> <label> <input type="text" class="form-control" name="search" placeholder="Enter website" autocomplete="off"> </label> <input type="submit" class="btn btn-primary" value="Search"> </div> <div> <div id="section2"> <center> <table class = "a"> <tr> <th>ID</th> <th>Hostname</th> <th>IP Address(IPv4)</th> <th>IP Address(IPv6)</th> <th>Port 1</th> <th>Port 2</th> </tr> <tr> <td>1</td> <td>{{ hostname }}</td> <td>{{ ipv4 }}</td> <td>{{ ipv6 }}</td> <td>{{ port1 }}</td> <td></td> </tr> this is my views.py from django.shortcuts import render import dns import dns.resolver import socket import sys def index(request): if request.method == 'POST': search = request.POST.get('search') # search = 'www.google.com' # search = "'" + search + "'" ip_address = dns.resolver.Resolver() IPv4 = ip_address.resolve(search, 'A').rrset[0].to_text() IPv6 = ip_address.resolve(search, 'AAAA').rrset[0].to_text() return render(request, 'index.html', {"ipv4": IPv4, "ipv6": IPv6, "hostname": search}) -
Filter django model field based on another field
I have a Django model : class System(models.Model): system = models.CharField(max_length=100,verbose_name = "system ", db_column = "SYSTEM") product = models.ForeignKey(Product,verbose_name="product",db_column="PRODUCT_ID") program = models.ForeignKey(Program, verbose_name = "program", db_column = "PROGRAM_ID") def __str__(self): return self.system class Meta: db_table = 'user_system_data' verbose_name = "System" default_permissions = ('add', 'change', 'delete', 'view') And 3 tables : Product table : id PRODUCT 1 P1 2 P2 3 P3 Program table : id PROGRAM PRODUCT_ID 1 Pr1 1 2 Pr1 2 3 Pr3 3 System table : id SYSTEM PROGRAM_ID 1 S1 1 2 S2 3 My problem is when i try to a new System to a Program that has multiple entries but to different Products , in this case the PROGRAM_ID column value is set randomly and not the one that i want. I tried to add the Product information when adding a new System to filter the Program information but that didn't work. Is there a way i can filter the PROGRAM field based on the PRODUCT selection ? or any solution that i can use to have the correct information stored in the table ? -
Fetching database Items based on Instance Settings
I have created a database model that saved user-added settings to the database. and I would like to read from these database entries to print reports. I have already read from the forms instances to allow the use to edit the settings like this : Url : path('accConnect/setting/<int:setting_pk>', views.viewSettings, name='viewSettings' ), Views: setting = get_object_or_404(SettingsClass, pk=setting_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: form = SettingUpdateForm(request.POST, instance=setting) if form.is_valid(): form.save() return redirect('settingsHome') However while trying to do the same thing to read from the class' instace settings. I cannot seem to get the code right. The below is what I have tried to get these instances but im not sure it works with the model urls.py: #Reports path('reportsHome' , views.reportsHome, name='reportsHome'), path('accConnect/printReports/<int:reports_pk>' , views.printReports , name='printReports') Views.py: pkForm = get_object_or_404(SettingsClass , pk=reports_pk) form= SettingsClass(instance=pkForm) This returns that the 'pk' is not found. So i'm not to sure what the proper way to do this is? -
Django: best way to write product characteristics in models if there are more than one categories
I am new django developer. I was trying to make ecommerce website. All things was going alright, but when I started coding product-details, I faced a problem with adding characteristics of product. So, how can I get characteristics if there are more than one category. I tried just adding textField and print it as a characteristics. But, it's not getting as a list and it is just printing as a text. models.py class Product(models.Model): name = models.CharField(max_length=200, verbose_name="Название продукта") category = models.CharField(max_length=300, choices=TOTAL, verbose_name="Категория") subcategory = models.CharField(max_length=300, choices=SUBPRODUCT) price = models.FloatField(verbose_name="Цена") description = models.TextField(max_length=5000,blank=True, verbose_name="Описание:") image = models.ImageField(null=True, blank=True, verbose_name="Изображение") novinki = models.BooleanField(default=False, verbose_name="Новинки") popularnye = models.BooleanField(default=False, verbose_name="Популарные") def __str__(self): return self.name class Meta: verbose_name = 'Продукты' verbose_name_plural = "Продукты" @property def imageURL(self): try: url = self.image.url except: url = '' return url templates <div class="u-product-control u-product-desc u-text u-text-default u-text-2"><!--product_content_content--> <p>{{product.description}}.</p><!--/product_content_content--> </div><!--/product_content--><!--product_button-- So, what can I do? What do you recommend me to do? Please help? I can not solve this problem for a week So, Can you tell me ways to do that? Please, help? -
Django Jquery Autofill data from models
i want make autofill form like this : http://www.tutorialspark.com/jqueryUI/jQuery_UI_AutoComplete_Overridding_Default_Select_Action.php what i already know is to get list of cities form models : views.py def autofill(request): if 'term' in request.GET: qs = Citi.objects.filter(cities__icontains=request.GET.get('term')) citys = list() citys = [city.cities for city in qs] return JsonResponse(citys, safe=False) return render(request, 'part/test.html',) jquery : <script> $(document).ready(function() { var zipCode = { Chicago: 60290, California: 90001, Chennai: 600040, Cambridge:02138 , Colombo:00800 }; $('#autoSuggest').autocomplete({ source: "{% url 'autofill' %}", select: function(event, ui) { $('#zipCode').val(zipCode[ui.item.value]); } }) }); </script> while i still don't understand how to get zipCode data from models, and pair it with city ? Thanks -
Django + Angular = Global Variable
I have a Django backend that generate, using its settings, a frontend settings.js with variable inside. This "global" contains, for example, the backend URL to allow Angular Frontend to contact. Es. settings.js var backend_url = "https://mydomain/mysite/rest/api" I my Angular frontend I need a way to read it. Unfortunally I cant simply using it becase the "symbol" is not known. Es. app.component.ts ngOnInit() { this.base_server_url = backend_url; <<---- error TS2304: Cannot find name 'backend_url'. } backend_url exists at runtime but Angular/Typescript doesn't know it. I read something about creating a global.d.ts to create a global placeholder but I cant figure out how to use. -
django AttributeError: 'tuple' object has no attribute 'rsplit'
Running python manage.py check throws an error AttributeError: 'tuple' object has no attribute 'rsplit'. Traceback (most recent call last): File "/home/mieltn/django_projects/batch/manage.py", line 22, in <module> main() File "/home/mieltn/django_projects/batch/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/mieltn/django_projects/batch/unesco/models.py", line 4, in <module> class Category(models.Model): File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/base.py", line 320, in __new__ new_class._prepare() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/base.py", line 333, in _prepare opts._prepare(cls) File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/options.py", line 285, in _prepare pk_class = self._get_default_pk_class() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/options.py", line 238, in _get_default_pk_class pk_class = import_string(pk_class_path) File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/utils/module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) AttributeError: 'tuple' object has no attribute 'rsplit' I saw similar thread about such error and it doesn't seem to be the case. The problem is supposedly connected … -
Complex filtering Django Model based on array inside JSONField
I read all the questions that had anything related to what I am trying to achieve, but still no luck. The one that did help me a little is this one How to filter JSON Array in Django JSONField but I still need something extra. I need to return the Profiles that provide a certain service (filtered by service_id) within a price range. This is the model: class Profile(models.Model): tagline = models.CharField(null=True, blank=True, max_length=40) experience_years = models.IntegerField(null=True) experience_description = models.CharField(null=True, blank=True, max_length=500) services_offered = models.JSONField(null=True) the services_offered attribute has an array of JSON objects, like this: "services_offered": [ { "noOfPets": 1, "hasDogWalk": "N", "pricePerPet": 27, "petServiceId": "2", }, { "noOfPets": 1, "hasDogWalk": "N", "pricePerPet": 30, "petServiceId": "1", }, ] I can filter profiles that offer a certain service (not using the price to do anything here) with this: Profile.objects.filter(services_offered__contains=[{'petServiceId': query_params['service_id']}) But how can I filter the profiles that offer a certain service within a price range? In other words, I need to find the JSON object of that service by the ID and then check the price (using lte and gte) for that service. I have tried this as well, but it returns nothing (price_max was set very high, just … -
Need multiple vendors registered under one business in django-oscar
I am trying to build an Oscar application where: A user can register their store and start selling under pre-defined categories. I want user to have access to dashboard in limited manner such as adding product, stock and product related attributes. Have seen some strategies, but not sure how to start. Any help is very much appreciated, I am trying to build an ecomm site which can help the underprivileged by let them create shops without any hustle. -
Access a variable in Django cron.py from other modules
I defined a variable in urls.py which will be updated every 10 seconds from views.py. I am trying to access this variable in cron.py, I need the updated value when I called from cron.py but I am getting the intialised value but not the updated one. -
How do I rearrange the cards in ascending order django
I have a page where the customer name in the cards is not rearrange in ascending order via alphabetical order Ex: B,M,S. How do I make it to arrange in alphabetical order so that the cards with the customer name Bangkok airways will appear first follow by the cards with malaysia airlines will appear next and so on? views.py def outgoinggallery(request): user = request.user category = request.GET.get('category') if category == None: alloutgoinglru = OutgoingLRU.objects.filter(category__user=user) else: alloutgoinglru = OutgoingLRU.objects.filter(category__name=category, category__user=user) # if query: # return OutgoingLRU.objects.filter(title__icontains=query) categories = Category.objects.filter(user=user) context = {'categories': categories, 'alloutgoinglru': alloutgoinglru} return render(request, 'Outgoing/outgoinggallery.html', context) outgoinggallery.html {% extends "logisticbase.html" %} {% block content %} <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <style> td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; border-radius: 15px; } .image-thumbail { height: 200px; object-fit: cover; } .list-group-item a { text-decoration: none; color: black; } </style> <br> <div style="padding-left:16px"> <div class="row"> <div class="col-md-9"> <div class="row"> <h5>View Outgoing LRU</h5> <div class="col-md-7"> </div> <br> <div class="col-md-9"> <div class="row"> {% for OutgoingLRU in alloutgoinglru %} <div class="col-md-4"> <div class="card my-4"> <img class="image-thumbail" src="{{OutgoingLRU.image.url}}" > <div class="card-body"> <small>Customer Name: {{OutgoingLRU.category.name}}</small> <br> <small>Delivery Order: {{OutgoingLRU.Deliveryor}}</small> </div> <a href="{% url 'viewlruphoto' OutgoingLRU.id %}" style="width:265px" class="btn … -
How to avoid duplicate key error with django allauth?
I have made some changes to my user model and as a result it seems that when a new user tries to sign up they receive the error: IntegrityError at /accounts/signup/ duplicate key value violates unique constraint "users_user_username_key" I am not sure what is causing the error This is the forms.py: from django.contrib.auth import get_user_model, forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ User = get_user_model() class UserChangeForm(forms.UserChangeForm): class Meta(forms.UserChangeForm.Meta): model = User class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( { "duplicate_username": _( "This username has already been taken." ) } ) class Meta(forms.UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) settings.py # django-allauth # ------------------------------------------------------------------------------ ACCOUNT_ALLOW_REGISTRATION = env.bool( "DJANGO_ACCOUNT_ALLOW_REGISTRATION", True ) # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_AUTHENTICATION_METHOD = "username" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_REQUIRED = True # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_VERIFICATION = "mandatory" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_ADAPTER = "pharmhand.users.adapters.AccountAdapter" # https://django-allauth.readthedocs.io/en/latest/configuration.html SOCIALACCOUNT_ADAPTER = ( "pharmhand.users.adapters.SocialAccountAdapter" ) # Your stuff... # ------------------------------------------------------------------------------ ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.UserCreationForm' And the models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ class User(AbstractUser): # First Name and Last Name Do Not Cover Name Patterns # Around the Globe. name = models.CharField( … -
Rendering charts using local Chart.js in overriding Django templates
I am trying to add charts to Django admin form with Chart.js. I would like to run my Django website completely offline. Therefore, I downloaded (i.e., copy/past the Chart.js script from the internet and saved the script locally) the js script and saved it in the "templates" folder where I put my overridden Django html pages. Originally, if I directly quote the JS script like other people do, I am able to render the Chart correctly in my Django admin form. Like the code below <script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script> However, if I trying to quote the local JS script, I will not get any chart. Like the code below <script src="Downloaded_CHART_JS_script.js"></script> But if I do not rendering the html page from Django, I can see my chart rendering normally. I tried to search through Django reference for several days, but can't find solution so far. Thank you. -
TypeError: expected str, bytes or os.PathLike object, not tuple in bash console of pythonanywhere.com [closed]
I am using Django for a project. I am getting this error -->TypeError: expected str, bytes or os.PathLike object, not tuple here is my settings.py in vscode settings.py in vscode and this is the image of settings.py on pythonanywhere.com where i am trying to upload my website settings.py on pythonanywhere.com and this is the image of bash console of pythonanywhere.com where i am trying to collect all my static files bash console of pythonanywhere.com any suggestions? -
How to separate decimal value with commas in python? [duplicate]
I want to separate decimal value with commas in the following format. value = 1079149.00 Using f'{value:n}' returns 1,079,149.00 But The output I want is : 10,79,149.00 First separate with 3 then afterward separate by 2 . How can I do this ? In django I only find to change the format in the templates only but not in views. So can I do this with pure python ? -
Making the user active when tapping a button in html, and using a DetailView (Django)
I'm trying to make a user active when I tap a button, and I'm using a DetailView. views.py from .models import Model from django.contrib.auth.models import User from django.shortcuts import redirect class UserInspectView(DetailView): model = Model template_name = 'user-inspect.html' # Make the user is_active = True def accept (request, pk): user = User.objects.get(id=pk) user.is_active return redirect('home') ... urls.py from django.urls import path from . import views urlpatterns = [ path('inspect/<slug:slug>/', views.UserInspectView.as_view(), name='user-inspect'), path('inspect/<int:pk>/accept/', views.accept, name="user-accept"), ... ] user-inspect.html {% extends 'base.html' %} {% block title %} <title>User Inspection</title> {% endblock %} {% block content %} <div class="d-flex justify-content-center"> <div class="container d-flex flex-column"> <div class="ms-5 ps-5" > <h3><strong>User:</strong> {{model.user}}</h3> <br> <h3><strong>Name:</strong> {{model.name}}</h3> </div> </div> </div> <br><br><br> <div class="d-flex justify-content-center"> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group me-2 me-5 pe-5" role="group" aria-label="First group"> <form method="post" action="{% url 'user-accept' model.user.pk %}"> {% csrf_token %} <button type="submit" class="btn btn-primary">Accept</button> </form> </div> <div class="btn-group me-2 me-5 ps-5" role="group" aria-label="First group"> <a href="" type="button" class="btn btn-secondary">Back</a> </div> </div> </div> {% endblock %} models.py from django.db import models from django.contrib.auth.models import User class Model(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True, blank=False, null=False) Before my accept view looked like this def accept (request, … -
Method that show error message if name field is not provide
I create a Django form to create a template (that is an object) with some attributes. The user that want to create this template, obviously, should give a name to template. I write clean name() method that checks if a template with that name already exists but now I want to create a method that shows an error message if the user does not provide a name for the template that he's creating. How can I do? This is the django model for the templateForm with his fields: class TemplateForm(BaseForm): enabled_parameters = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(label=_("name *")) sport = forms.CharField(label=_("sport"), widget=forms.TextInput(attrs={"readonly": "readonly"})) owner = forms.CharField(label=_("owner"), widget=forms.TextInput(attrs={"readonly": "readonly"})) visibility = forms.ChoiceField(label=_("visibility"), choices=Template.VISIBILITIES, widget=forms.RadioSelect()) last_update = forms.CharField(label=_("last update"), widget=forms.TextInput(attrs={"readonly": "readonly"})) def clean_name(self): """check if template's name is unique""" name = self.cleaned_data.get("name") template_num = 0 if self.template.pk and name == self.template.name: template_num = 1 if Template.objects.filter(name=name, team=self.template.team).count() != template_num: raise ValidationError(_("A Template named {} already exists.".format(name))) return name -
Form URL Error :Reverse for 'printReports' with no arguments not found. 1 pattern(s) tried
I am currently running into the above error when trying to access my reportsHome page. It seems to be a problem with the 'HREF' section of the form where the code is href="{% url 'printReports' reports_pk %}" The templates , views and URLs are listed in the below code: reportsHome.html : {% block content%} <h1 style=" text-align: center">Reports</h1> <hr> <br> <div class="list-group"> <a href="#" class='list-group-item active'>Print Single Complex's</a> {% for x in model %} <a href="{% url 'printReports' reports_pk %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a> {% endfor %} </div> {% endblock %} printPDF.html : <title>PDF Outuput - TrialBalance</title> {% block content%} <h1 class = 'center'>Kyle Database Trial Balance</h1> <br> </div> <br> <br> <div class="table-container"> <table style="width: 100%"> <th >Account</th> <th>Description</th> <th>Debit</th> <th>Credit</th> {% for arr_trbYTD in arr_trbYTD %} <tr> <td>{{ arr_trbYTD.Description }}</td> <td>{{ arr_trbYTD.Account }}</td> <td> {%if arr_trbYTD.Debit > 0%} {{arr_trbYTD.Debit}} {%endif%} </td> <td> {%if arr_trbYTD.Credit > 0%} {{arr_trbYTD.Credit}} {%endif%} </td> </tr> <tr > {% endfor %} <td> <b>Totals</b> </td> <td> </td> {% for xDebitTotal in xDebitTotal %} <td><b>R {{ xDebitTotal }}</b></td> {% endfor %} {% for xCreditTotal in xCreditTotal %} <td><b>R {{ xCreditTotal }}</b></td> {% endfor %} </tr> </table> </div> <br> <br> <br> {% endblock %} Views.py : … -
Combine 2 django models based on multiple columns without using select_related
I have 2 models where both of them contain 2 columns which can be treated as keys and a third column which is the value The goal is to inner join both the models but somehow I'm having trouble doing that I tried following this link but I don't think in my case I would want the columns to foreign key to the other so I can't use "select_related" My Models are as follows: class AssetReturnTs(models.Model): data_date = models.DateTimeField() asset = models.ForeignKey(Asset, on_delete=CASCADE) return = models.DecimalField(max_digits=19, decimal_places=10, null=True) class Meta: db_table = "return" class AssetWeightTs(models.Model): data_date = models.DateTimeField() asset = models.ForeignKey(Asset, on_delete=CASCADE) weight = models.DecimalField(max_digits=19, decimal_places=10, null=True) class Meta: db_table = "weight" I want to do a query such that I join the AssetReturn and AssetWeight on data_date and asset_id The end goal is to then do a weighted sum of the return. Currently I'm querying both separately and converting them to pandas and merging them. It looks like this: asset_return_ts = AssetReturnTs.objects.get_returns(start_date, end_date, asset_list).values(*columns_required) asset_weight_ts = AssetWeightTs.objects.get_weights(start_date, end_date, asset_list).values(*columns_required2) # Convert to df # Use pd.merge() and then compute weighted sum Any solution which reduces 2 separate queries to one and helps compute the weighted sum would be greatly …