Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-tables2: row number ordering column not in DB
I am using django-tables2 to create a table, How to make the column row_number follow the sort of id and age columns? https://github.com/jieter/django-tables2/blob/master/docs/pages/ordering.rst import django_tables2 as tables import itertools class SimpleTable(tables.Table): row_number = tables.Column(empty_values=()) id = tables.Column() age = tables.Column() def render_row_number(self): self.row_number = getattr( self, 'row_number', itertools.count(self.page.start_index())) return next(self.row_number) def render_id(self, value): return f"<{value}" I think the best way is if statement if asc = itertools.count(self.page.start_index()) |row_number| id | age | | -------- | -------- |-------- | | 1 | id.1 | age | | 2 | id.2 | age | | 3 | id.3 | age | else desc = itertools.count(self.page.end_index(), -1) |row_number| id | age | | -------- | -------- |-------- | | 3 | id.3 | age | | 2 | id.2 | age | | 1 | id.1 | age | but i don't know how to implant that. -
Django + Docker + Postgres. FATAL: password authentication failed for user "postgres"
I don't know how to solve this simple error: django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" When I run docker-compose up, it can't connect to Postgres. I have tried stopping the service with docker-compose down -v. Please help me understand why am I getting this error. Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } docker-compose.yml: version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code env_file: - .env ports: - "8000:8000" depends_on: - db db: image: postgres:15 volumes: - ./data/db:/var/lib/postgresql/data/ environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres I've reviewed many tutorials and videos about this without success. -
Django Delete file from storage model not working from IIS but working on localhost
I have file Delete Model for deleting file chosen by user. for that after conforming from user that you want to sure delete file I have view.py code as below. @login_required(login_url='/login/') def Delete_files(request, pk): # Get the RadioFile object based on the primary key (pk) radio_file = get_object_or_404(RadioFile, pk=pk) print(radio_file) # get the file path and file object from the database file_obj = RadioFile.objects.get(id=pk).audio_file radio = radio_file.audio_file file_path =file_obj.path print(file_path) # Check that the user is the owner of the file if request.user != radio_file.uploaded_by: messages.success(request, 'File can be deleted by its owner.') # store the message in a message queue return redirect('/') elif os.path.exists(file_path) and not os.path.isfile(file_path): print(f"Error: {file_path} is not a file") response_data = {'success': False, 'error': str(e)} else: try : with transaction.atomic(): # Remove the many-to-many relationship with categories radio_file.categories.clear() radio_file.share_with.clear() # Delete the Radio object radio_file.delete() # Delete the file from the filesystem radio.close() radio.delete() messages.success(request, 'Radio and file deleted successfully.') response_data = {'success': True} except Exception as e: print(str(e)) messages.error(request, 'some error is coming while deleteing file.') # Redirect to the file list view return redirect('/') code deleting file when running from localhost. But it is giving me Win32 permission error says file already in … -
How to authenticate custom table of MySQL using Django?
I was trying to Authenticate my website using Django. Basically I am Using MySQL Database in the backend and I create a custom table that name is Signup. Data is successfully inserted into signup table but whenever I was trying to login it is showing 'No user found' my authenticate function is working properly but it did not fetch the data from signup table. What should I do? Here is so some Screenshot of my code what I have tried . This is the image of my settings.py where I connected MYSQL database using Django Login Code and Output This is image of my login page Code and the output is showing in the terminal Signup Code This is image of Signup Code where signup is correctly working MYSQL entered Datathis is the image of MySQL where I successfully entered my data from signup page -
Serializer has initial_data, but validated_data is empty
I passed some data via post request and Iwant to get the data in the key 'items' (it contains a list of objects that i need to use to create OrderItem). The problem is I don't get any data in the validated_data after calling is_valid(). However the data can be found in serializer.initial_data, Printing what is in serializer.validated_data() shows that it's empty ({}). I don't see where the issue is and why I can't get the data to be in validated_data after using is_valid(). Any help would be very much appreciated. Thanks An Order has 1 or many OrderItems. The model of OrderItem class OrderItem(models.Model): """Model for an item in an order""" order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name="items") bookedition = models.ForeignKey(BookEdition, on_delete=models.PROTECT, related_name="orderitems") quantity = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=8, decimal_places=2) price = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self): return '%s' % self.id The serializer of OrderItem class OrderItemSerializer(serializers.ModelSerializer): """Serializer for OrderItem""" class Meta: model = OrderItem fields = [ 'bookedition', 'quantity', 'unit_price', 'price' ] The model of Order class Order(models.Model): """Model for an order""" PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] payment_status = models.CharField(max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING) customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name="orders") … -
Access to the date details in a Django database
I'm currently going over the official Django tutorial. At some point we're shown how to filter keys by the year of the the automatically-filled pub_date column. >>> Question.objects.get(pub_date__year=current_year) <Question: What's up?> But somehow the syntax when calling the year of the date directly has to be with a . instead of a __... In [56]: q=Question.objects.get(pub_date__year=current_year) In [57]: q.pub_date__year --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In [57], line 1 ----> 1 q.pub_date__year AttributeError: 'Question' object has no attribute 'pub_date__year' In [58]: q.pub_date.year Out[58]: 2023 Is there some reason it has to be different when called outside of the parenthesis? -
CSRF token (in Django) vs Session token
From what I understand CSRF token is generated on the server and sent to the client on every login. When client sends the request, CSRF token is sent with it and client token is checked if it matches server token. Isn't this how Session token works as well? The only difference I see is that CSRF token isn't saved anywhere (it's in the hidden field) as opposed to session token which is saved is session cookie? If that's the case, then how Django CSRF cookie works? From other post: When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. The site should require every form submission to include this pseudorandom value as a form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An attacker cannot read any data sent from the server or modify cookie values, per the same-origin … -
DJANGO : ManyToManyField self symetrical unique together how to mange it?
I have some trouble trying to fetch some manytomanyrelated data in by Django Application Here is my model : SoftwareVersion(models.Model): id = models.AutoField( primary_key=True, db_index=True ) ... Some other fields ... incompatibilities= models.ManyToManyField( "self", symmetrical=True, blank=True, default=None, through="Incompatibilities" ) Incompatibilities(models.Model): id = models.AutoField( primary_key=True, db_index=True ) softwareversion_a = models.ForeignKey( "SoftwareVersion", models.CASCADE, db_index=True, db_column='softwareversion_a ', related_name='softwareversion_a', verbose_name="software version a", ) softwareversion_b = models.ForeignKey( "SoftwareVersion", models.CASCADE, db_index=True, db_column='softwareversion_b', related_name='softwareversion_b', verbose_name="softwareversion_b", ) status = models.BooleanField( verbose_name='Status', default=False ) class Meta: unique_together = (('softwareversion_a', 'softwareversion_b'),) To this I add in the SoftwareVersion's save method a logic to create related Incompatibilities for each new software version. I have tried several way to do it (with a loop or with a bulk_create) here is the bulk create function i use : # Inside SoftwareVersion Model class def save(self, force_insert=False, force_update=False, using=None, update_fields=None) -> None: save = super().save(force_insert, force_update, using, update_fields) Incompatibilities.objects.bulk_create( (Incompatibilities( softwareversion_a=self, softwareversion_b=software_version, status=False ) for software_version in SoftwareVersion.objects.exclude(self)), ignore_conflicts=True, batch_size=1000 ) return save First problem I have is this method ignore the unique_together constraint, it creates duplicates. Before i was using a loop on each SoftwareVersion to create an object but it was too long so i wanted to use bulk_create but it seems … -
Django Loglevel is undefined in project app views.py
I try to log something with INFO level in the views.py in a created app in my Django project. When I initialize the logger with: logger = logging.getLogger(__name__) the loglevel is set to 0 which means undefined. Why does it not read the log level defined in the settings py? I start the project in the pycharm IDE and a environment variable with name LOGLEVEL is set to INFO (I checked if the loglevel was correctly read by debugging the settings.py on startup and it is correct set to INFO) Project Structure: myApp views.py ... myproject settings.py ... settings.py loggin config: # Disable Django's logging setup LOGGING_CONFIG = None LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { # Use JSON formatter as default 'default': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', }, 'django.server': DEFAULT_LOGGING['formatters']['django.server'], }, 'handlers': { # Route console logs to stdout 'console': { 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'django.server': DEFAULT_LOGGING['handlers']['django.server'], }, 'loggers': { # Default logger for all modules '': { 'level': LOGLEVEL, 'handlers': ['console', ], }, # Default runserver request logging 'django.server': DEFAULT_LOGGING['loggers']['django.server'], } } views.py logger = logging.getLogger(__name__) def teams_overview(request): try: print(f"loglevel set: {logger.level}") print(f"info logleve: {logging.INFO}") logger.error("error") logger.info("info") logger.warning("warning") logger.critical("critical") logger.debug("debug") output: error warning … -
How to pass json data to frontend using Django
I have response from another api of json data and i want to send this json data to my frontend to parse this json there But when im using return JsonResponse it just returns html with json i dont need that, i want to return blank html with json which was send on front and frontend with js will parse it views.py def json_project_budget(request): session = requests_cache.CachedSession('project_budget_cache') url = config('REPORT_PROJECT_BUDGET') response = session.get(url=url, auth=UNICA_AUTH).json() queryset = [] for item in response: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) obj = parsed_json.ObjectGUID for budget in parsed_json.BudgetData: budget.SectionGUID = CleanSections.objects.get(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) return JsonResponse(response, safe=False) I will update bcs i think that i understand my problem I have problems in url or something like that I have ListView which renders my template and the main question how am i suppose to send this function json_project_budget in my template to get json data? views.pyy class ShowProjectBudgetList(ListView): login_url = '/login/' redirect_field_name = '' template_name = 'customer/customer_home.html' context_object_name = 'json_list' allow_empty = True # paginate_by = 5 def get_queryset(self): return None urls.py path('customer/', ShowProjectBudgetList.as_view(), name='customer_view'), path('customer/', json_project_budget, name='json_project_budget'), -
Django cannot find TemplateDoesNotExist
I am trying to create a login page using django and I am getting this error. TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 4.1.5 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/template/loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: /Library/Frameworks/Python.framework/Versions/3.11/bin/python3 Python Version: 3.11.1 Python Path: ['/Users/jasonfan/Desktop/Swe/TAPortal', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python311.zip', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages'] Server time: Mon, 20 Mar 2023 17:02:00 +0000 I have a couple ideas of where the problem may lie. I created a templates/registration/login.html. Does it matter which directory i put these subdirectories in? My file structure is attached. This is my settings.py folder. I modified TEMPLATES. I added 'DIRS': [BASE_DIR/"templates"], I also added LOGIN_REDIRECT_URL = "/" at the bottom. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/"templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I also modified urls.py adding urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include("django.contrib.auth.urls")) ] I modified the login.html to a basic login screen and that is where I am trying to get to when i run server. I do http://127.0.0.1:8000/accounts/login/ -
Django Rest Framework: Remove Appended "[]" from List Parameter
I have a django rest framework application set up with two packages: One's called djangorestframework-camel-case (to "camelizes" the parameters in the API docs) and the other is drf-spectacular (to automatically generate Swagger docs for my API). The camel case package also has the effect that it causes parameters from the request data sent from the frontend (in camelCase) to be received in the Python backend in snake_case. However, I just found out that when one of the requests from the frontend contains a list of data, lets say dataList = ["1", "2", "3"], the parameter is received in the Python backend as a dictionary with the key data_list[]. Is there a setting to remove that [] at the end? Its messing up with the rest of my logic. -
Adding items to wishlist
so Im trying to work on adding a wishlist item to the wishlist page. So Im creating a view to add a wishlist to the page and a view to show the items ive added. But the issues ocurs when i press the add to wishlist button on a product.The item i added is not showing up in the wishlist page for some reason i cant seem to figure out. I get the error of add_to_wishlist() missing 1 required positional argument: 'product' Here is my code below: views.py: @login_required def wishlist(request): wishlist, created = Wishlist.objects.get_or_create(user=request.user.userprofile) return render(request, 'products/wishlist.html') @login_required def add_to_wishlist(request, product, product_id): product = Product.objects.get(id=product_id) return redirect('wishlist') @login_required def remove_from_wishlist(request, product_id): product = get_object_or_404(Product, pk=product_id) wishlist = Wishlist.objects.get(user=request.user.userprofile) wishlist.products.remove(product) return HttpResponseRedirect(reverse('add_to_wishlist')) models.py: class Wishlist(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) product = models.ManyToManyField(Product, blank=True) wishlist.html: {% block content %} <div class="overlay"></div> <div class="container"> <h1>My Wishlist</h1> <div class="row"> {% if wishlist.products.all %} {% for product in wishlist.products.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <div class="card-body"> <h2 class="card-title">{{ product.name }}</h2> <p class="card-text">{{ product.description }}</p> <p class="card-text">$ {{ product.price }}</p> <form action="{% url 'remove_from_wishlist' product.id %}" method="POST"> {% csrf_token %} <button class="btn btn-danger" type="submit">Remove from Wishlist</button> </form> </div> </div> </div> {% endfor %} … -
Inertia Django Vite not working on deployment
I'm trying to deploy this template to fly.io (https://github.com/mujahidfa/inertia-django-vite-vue-minimal.git). Additionally I installed "gunicorn" as WSGI-server. I got it running locally but if I deploy it, I get a CORS-error because Vite ist still requesting localhost. All I see is a white page. index.html: {% load django_vite %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% vite_hmr_client %} {% vite_asset 'main.ts' %} <title>Inertia + Django + Vite + Vue minimal</title> </head> <body> {% block inertia %}{% endblock %} </body> </html> In the browser it gets resolved to: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script type="module" src="http://localhost:5173/static/@vite/client"></script> <script type="module" src="http://localhost:5173/static/main.ts"></script> <title>Inertia + Django + Vite + Vue minimal</title> </head> <body> <div id="app" data-page="{&quot;component&quot;: &quot;Index&quot;, &quot;props&quot;: {&quot;name&quot;: &quot;World&quot;}, &quot;url&quot;: &quot;http://nameless-mountain-1344.fly.dev/&quot;, &quot;version&quot;: &quot;1.0&quot;}"></div> </body> </html> I think the interesting parts are: {% vite_hmr_client %} {% vite_asset 'main.ts' %} <script type="module" src="http://localhost:5173/static/@vite/client"></script> <script type="module" src="http://localhost:5173/static/main.ts"></script> Has anybody an idea how to get it working? I couldn't figure it out for days now. I've tried fiddling with the Dockerfile, but I'm still in the eary phase with fullstack-developement. Also in the vite.config.ts I've tried many … -
why do i get Forbidden (403) CSRF verification failed. Request aborted. when I'm trying to register?
from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm def register(response): if response.method == 'POST': form = UserCreationForm(response.POST) if form.is_valid(): form.save() else: form = UserCreationForm() return render(response, 'register/register.html', {'form':form}) html {% extends 'libraryfinish/base.html' %} {% block title %} Create an account {% endblock %} {% block content %} <form method="POST", class="form-group"> {% csrf_token %} {{form}} <button type="submit", class="btn btn-success">Register</button> </form> {% endblock %} I found that I should pass the RequestContext in my render_to_response for the context processors to actually be run, but I'm not using render to response from django.views.decorators.csrf import csrf_protect @csrf_protect doesn't work -
ModelForm groupé - can_delete=True, impossible de sélectionner les checkbox par JS
Je souhaite afficher un message d'avertissement aux utilisateurs qui cochent la case correspondant à form.DELETE d'un formulaire groupé. J'utilise un script JQuery, mais impossible de filtrer les champs sur leur nom (contenant DELETE) dans ce qui est généré par Django. J'ai ajouté en début de page une checkbox avec name = Truc et utilisé le même script (avec filtrage sur le nom contenant "truc", et là, ça marche... <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('input[name*="truc"]').change(function () { alert("Checkbox cliquée. Name contient truc"); }); }); </script> <script type="text/javascript"> $(document).ready(function () { $('input[name*="DELETE"]').change(function () { alert("Checkbox cliquée. Name contient DELETE"); }); }); </script> <Div class="row"> <form method="post"> <input type="checkbox" name="truc" id="cbox"> {% csrf_token %} {{ data_form_set.management_form }} <br> <br> <table class="table table-hover table-striped" data-toggle="table" data-pagination="true"> <thead> <tr> <th>id</th> <th><i class='bx bx-trash nav_icon'></i></th> <th>Champ 1</th> <th>Champ 2</th> </tr> </thead> <tbody> {% for form in data_form_set %} <tr> <td>{{ form.id }}</td> <td>{{ form.DELETE }}</td> <td>{{ form.champ1 }}</td> <td>{{ form.champ2}}</td> </tr> {% endfor %} </tbody> </table> <br> <button name="enregistrer" type="submit" class="btn btn-primary"> <i class='bx bx-save nav_icon'></i> Sauvegarder </button> </form> </form> </div> -
Django template list not showing all the images
I am working on a Django project and its a simple product website which will look like: First page- 1.Electronics link 2.Toys link Second page after clicking on the link: For electronics I have 3 item listed and same for toys. How to show images of different product once user will click on it along with the list of items. I have index.html which will show 1.Electronics link,2.Toys link <!DOCTYPE html> {% load static %} <html> <head> <title></title> <link rel="stylesheet" href="{% static "productApp/css/index.css" %}" </head> <body> <h1>Welcome to our online shoping portal</h1> <ul> <li><a href="/electronics">Electronics<img src="productApp/images/electronics.jpeg"/></a></li> <li><a href="/toys">Toys</a></li> <li><a href="/shoes">Shoes</a></li> </ul> </body> </html> Product.html <!DOCTYPE html> {% load static %} <html> <head> <title></title> <link rel="stylesheet" href="{% static "productApp/css/product.css" %}" </head> <body> <h1>{{heading}}</h1> <ul> <!-- <img src="{% static "productApp/images/electronics.jpg"%}"/> --> <li>{{product1}}</li> <li>{{product2}}</li> <li>{{product3}}</li> </ul> </body> </html> -
NOT NULL constraint failed: app_User.user_id
I've made an abstractuser model so I can register users through email, and when I'm trying to register new user I get this error NOT NULL constraint failed: app_shahadati_user.user_id How can I fix this error? models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Shahadati_user(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) user_nID=models.PositiveIntegerField() def __str__(self): return self.user.email forms.py class CustomUserCreateForm(forms.ModelForm): password = forms.CharField() password_validation = forms.CharField() class Meta: model = CustomUser fields = ['first_name','last_name','email'] def clean_password_validation(self): pwd1 = self.cleaned_data.get('password') pwd2 = self.cleaned_data.get('password_validation') if pwd1 and pwd2 and pwd1 != pwd2: raise ValidationError("Passwords don't match") return pwd2 def save(self, *args, **kwargs): self.instance.set_password(self.cleaned_data.get('password')) return super().save(*args, **kwargs) class ShahadatiUserForm(forms.ModelForm): class Meta: model = Shahadati_user fields =['user_nID'] views.py def user_reg(request): if request.method == 'POST': form = CustomUserCreateForm(request.POST, request.FILES) form_ShU = ShahadatiUserForm(request.POST,request.FILES) if form.is_valid() and form_ShU.is_valid(): form.save() form_ShU.save() else: pass return render(request, 'Register.html', {}) -
How do I get typing working in python mixins?
I have a mixin that will always be used with a specific type of class i.e. a subclass of widgets.Input I want to override a few methods using the mixin, and I'm referencing attributes that exist on widgets.Input in my custom methods How do I tell the python type system that this mixin extends the widgets.Input interface without inheriting from widgets.Input? Bonus: Can I tell the type system that this mixin can only be used with subclasses of widgets.Input? from django.forms import widgets class MaskedWidgetMixin: def format_value(self, value): return "" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) # <--- super().get_context does not exist context["widget"]["attrs"] = self.build_attrs(self.attrs, attrs, value) # <--- self.attrs does not exist return context def build_attrs(self, base_attrs, extra_attrs=None, value: str = ""): attrs = super().build_attrs(base_attrs, extra_attrs) # <--- super().build_attrs does not exist if value: attrs.update({"placeholder": "* ENCRYPTED *", "required": False}) return attrs class EncryptedTextInputWidget(MaskedWidgetMixin, widgets.TextInput): pass class EncryptedTextareaWidget(MaskedWidgetMixin, widgets.Textarea): pass -
Django admin model
Подскажите пожалуйста, как в model переменной присвоить имя класса: Т.е. есть class abonents(models.Model) и нужно переменной name присвоить имя abonents Либо можно ли с class Meta: verbose_name = "ПРОВЕРКА ВСЕХ АБОНЕНТОВ " verbose_name_plural = " ПРОВЕРКА ВСЕХ АБОНЕНТОВ " Передать в list_display admin модели. ничего не могу найти в нете похожего -
how to optimise queries n+1 problem in django orm
I have the following queries: I need to resolve the n+1 problem. I have the following code: sesializers.py: from rest_framework import serializers from django.db.models import Prefetch, Subquery, OuterRef from .models import Item, Size, Price class SizeSerializer(serializers.ModelSerializer): price = serializers.SerializerMethodField('get_price') class Meta: model = Size fields = ['title', 'price'] def get_price(self, obj) -> int: price_qs = Price.objects.filter(size=obj) price = price_qs.first() return price.price class ItemSerializer(serializers.ModelSerializer): price = serializers.SerializerMethodField('get_min_price') brand_name = serializers.CharField(max_length=20) size = SizeSerializer(many=True) class Meta: model = Item fields = ['title', 'sku', 'price', 'brand_name', 'size'] def get_min_price(self, obj) -> int: price_sq = Subquery(Price.objects.filter(size=OuterRef('pk')).values('price')[:1]) size_qs = Size.objects.filter(item=obj).prefetch_related( Prefetch('price', queryset=Price.objects.all())).annotate(min_price=price_sq) prices = size_qs.values_list('min_price') return int(''.join([str(i) for i in min(prices)])) In def get_min_price I have tried to implement it. It seems to me that I understand it not completely. In models I have the following structure: Brand -> Item(brand_name as foreign key, related_name=item) -> Size(item as foreign key, related_name=size) -> Price(size as foreign key, related_name=price) Give the cue that I am doing not so UPD: It has to be optimized with Prefetch and Subquery -
Raw SQLite3 command in Django
I am trying to join 2 tables to display the orders that are matched to the username for the currently logged in user using SQLITE3, I have the SQL raw command written but I recieve the error: there is no such table Account. I have checked using the .tables sql command and the table is created and working. The program is also migrated without any errors but the Account table cant be found. views.py from .models import Account, Order from django.db import connection def account(request): # Retrieve the currently logged in user user=request.session.get("user_id") if user is not None: # Retrieve the user's orders using a SQL join with connection.cursor() as cursor: cursor.execute(''' SELECT a.Username, a.Email, o.Name, o.Surname, o.part FROM Account a INNER JOIN "Order" o ON a.Username = o.Username WHERE a.id = %s ''', [user]) rows = cursor.fetchall() orders = [] for row in rows: order = { 'Username': row[0], 'Email': row[1], 'Name': row[2], 'Surname': row[3], 'Part': row[4], } orders.append(order) print(orders) # Render the orders template with the orders data return render(request, 'orders.html', {'orders': orders}) else: return redirect(reverse("home")) the Account in line 11 is giving the error #models.py class Account(models.Model): #Only one id can be created id = models.AutoField(primary_key=True) #Uses … -
Django - HTML Select not staying selected
I am trying to keep the selected object selected in html after submitting form. Below is my view and html select form. Tried all solutions on stack overflow and all combinations when referring to object in template and making changes to my view, but no success in keeping the selected object selected. views.py def profile(request,pk): posts = Post.objects.filter(active=True, owner=request.user) comments = Comment.objects.filter(post_owner=request.user) filter_post = request.GET.get('filter_post') if filter_post: comments = Comment.objects.filter(post_owner=request.user, post__exact=filter_post) ### Tried post_id, post__id, instead of post__exact return render(request, 'profile.html', {'posts':posts, 'comments':comments, 'filter_post':filter_post}) profile.html <form method="GET"> <select class="form-select" id="filter_post" name='filter_post'> <option value=""{% if value == "" %}selected {% endif %}> Select post </option> {% for post in posts %} <option value="{{post.id}}" {% if post.id == filter_post %} selected="selected" {% endif %}> {{post.title}} - {{post.created}} </option> {% endfor %} </select> </form> What am I doing incorrectly? -
Find filter entries from django whose sum is match with given amount
I have the following entries in my database code amount created_date is_used A 10 20/02/2023 0 B 10 20/02/2023 0 C 50 20/02/2023 0 D 50 20/02/2023 0 E 100 20/02/2023 0 I want to find out the entries from the above table in descending order by the amount that will match the sum of the amount with a given amount Example User enters 150 amount Expected result code amount created_date is_used E 100 20/02/2023 0 D 50 20/02/2023 0 I tried following but I want only required entries only queryset = MyModel.objects.filter(is_used=0).order_by('-amount', '-created_date') amount = 150 finalized_amount = [] for q in queryset: if amount == 0: break elif amount == q.amount: finalized_amount.append(q) amount -= q.amount elif q.amount < amount: finalized_amount.append(q) amount -= q.amount elif q.amount > amount: amt = q.amount - amount if amt <= 50 : finalized_amount.append(q) amount = 0 I know this is not a good solution. Please let me know if there is any to get these entries from the database in filter queryset only -
Djagno - custom User model with two factor auth - invalid credentials leads to creating a new user in database, valid credentials work, 2FA also
I have a django project, where i have custom user model stated as below : class CustomUserModel(AbstractUser): # MAKING email field mandatory email = models.EmailField(unique=True) # KEEP TRACK OF USER'S PASSWORD CREATION DATE TO ENFORCE 3MONTH MAX VALIDITY password_created_date = models.DateTimeField(default=timezone.now, null=False, blank=False) # WHICH DEPARTMENT IS USER MEMBER OF department = models.ForeignKey(Department, on_delete=models.PROTECT, default=1, null=False, blank=False) # WHICH TEAM IS USER MEMBER OF team = models.ForeignKey(Team, on_delete=models.PROTECT, default=1, null=False, blank=False) # USER TYPE - DETERMINES SOME ATTRIBUTES FOR USER - I.E. MAX AMOUNT OF ACTIVITY user_type = models.ForeignKey(UserType, on_delete=models.PROTECT, default=1, null=False,blank=False) # FIRST NAME - REQUIRED FIELD first_name = models.CharField(max_length=30, blank=False, null=False) # LAST NAME - REQUIRED FIELD last_name = models.CharField(max_length=30, blank=False, null=False) # OVERRIDE DEFAULT SAVE METHOD FOR USER THAT EMAIL IS REQUIRED ELSE - ValueError def save(self, *args, **kwargs): if not self.email: raise ValueError("Email field is required") super().save(*args, **kwargs) # OVERRIDE DEFAULT SAVE PASSWORD METHOD SO THAT DATE OF CREATION IS ALSO CREATED def set_password(self, raw_password): super().set_password(raw_password) self.password_created_date = timezone.now() self.save() In my settings.py i have included AUTH_USER_MODEL = 'attendance.CustomUserModel' here is error flow: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/login/ Django Version: 4.1.7 Python Version: 3.9.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'attendance', 'services', …