Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to order django models according decimal points
I have created model where I am ordering by feature_req_no Feature_req_no is in the form of: 1, 1.1, 1.1.1, 2, 2.1, 10, 10.1, When I try to do Ordering using feature_req_no the ordering is as follows: 1, 10, 10.1, 1.1, 1.1.1, 2, 2.1 Expected output: 1, 1.1, 1.1.1, 2, 2.1, 10, 10.1 -
use toggle to switch django boolean field
I have a bootstrap toggle and I would like every time I switch to activate or deactivate a boolean field within my model. html <div class="form-check form-switch"> <input class="form-check-input" {% if slide.attivo == True %} checked {% endif %} type="checkbox"> </div> model class Slide(models.Model): attivo = models.BooleanField(default=True) -
Django does not open the form for taking inputs instead returns directly the final page mentioned in views.py
[Here is the views.py instead of reading inputs from the user after opening the form it jumps directly to index.html line and returns it[][1]1 -
Filter field based on tenant on Django default administration template
Good afternoon, given 2 django models: class Person(TenantAwareModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) full_name = models.CharField(max_length=200) personal_car= models.ForeignKey(Car, on_delete=models.SET_NULL , null=True, blank=True) ... def __str__(self): return self.full_name class Car(TenantAwareModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) car_name = models.CharField(max_length=200) ... def __str__(self): return self.car_name I simply want , working on Template and Form in administration register, that WHEN I 'am going to edit an "Person" object, I can only SELECT, from the "personal_car" dropdown, the "Car" that is of the Tenant of that Person. Cause with default tenant implementation I can select ALSO Car that is of another Tenant... and this is wrong. Actual ""admin.py"" settings, I would reach this goal only work on this file: class PersonAdminForm(forms.ModelForm): class Meta: model = Person fields = "__all__" def __init__(self, *args, **kwargs): super(PersonAdminForm, self).__init__(*args, **kwargs) self.fields['personal_car'].queryset = Car.objects.filter() #this empty filter return all personal_car objects... also from other tenants.. can't filter here... class PersonDedicatedTemplate(admin.ModelAdmin): list_display = ('tenant','full_name','personal_car') list_filter = ('tenant') full_path=None form=PersonAdminForm super_admin_site.register(Person,PersonDedicatedTemplate) thank you ! -
Is context processor only wawy to access global variable in in Django?
I am creating a website and i have to access golbal variables for the footer section and i found the context processor one way to access global variable and my question is that Is context processors one and only way to access global variable in django ? -
Django model order and duplicate
I have two models with a manytomany relationship. class Exercise(models.Model): BODYPART_CHOICES = ( ('Abs', 'Abs'), ('Ankle', 'Ankle'), ('Back', 'Back'), ('Biceps', 'Biceps'), ('Cervical', 'Cervical'), ('Chest', 'Chest'), ('Combo', 'Combo'), ('Forearms', 'Forearms'), ('Full Body', 'Full Body'), ('Hip', 'Hip'), ('Knee', 'Knee'), ('Legs', 'Legs'), ('Lower Back', 'Lower Back'), ('Lumbar', 'Lumbar'), ('Neck', 'Neck'), ('Shoulders', 'Shoulders'), ('Thoracic', 'Thoracic'), ('Triceps', 'Triceps'), ('Wrist', 'Wrist'), ) CATEGORY_CHOICES = ( ('Cardio', 'Cardio'), ('Stability', 'Stability'), ('Flexibility', 'Flexibility'), ('Hotel', 'Hotel'), ('Pilates', 'Pilates'), ('Power', 'Power'), ('Strength', 'Strength'), ('Yoga', 'Yoga'), ('Goals & More', 'Goals & More'), ('Activities', 'Activities'), ('Rehabilitation', 'Rehabilitation'), ('Myofascial', 'Myofascial') ) EQUIPMENT_CHOICES = ( ('Airex', 'Airex'), ('BOSU', 'BOSU'), ('Barbell', 'Barbell'), ('Battle Rope', 'BattleRope'), ('Bodyweight', 'Bodyweight'),('Bands', 'Bands'), ('Cables', 'Cables'), ('Cones', 'Cones'), ('Dumbbells', 'Dumbbells'), ('Dyna Disk', 'Dyna Disk'), ('Foam Roller', 'Foam Roller'), ('Kettlebells', 'Kettlebells'), ('Leg Weights', 'Leg Weights'), ('Machine', 'Machine'), ('Medicine Ball', 'Medicine Ball'), ('Plate', 'Plate'), ('Power Wheel', 'Power Wheel'), ('Ring', 'Ring'), ('Sandbag', 'Sandbag'), ('Stick', 'Stick'), ('Strap', 'Strap'), ('Suspension', 'Suspension'), ('Swiss Ball', 'Swiss Ball'), ('Theraball', 'Theraball'), ('Towel', 'Towel'), ('Tubbing', 'Tubbing'), ('Wobble Board', 'Wobble Board'), ) name = models.CharField(max_length=200) photograph = models.ImageField(null=True, upload_to=exercise_image_file_path) body_part = models.CharField(max_length=50, choices=BODYPART_CHOICES) equipment = models.CharField(max_length=200, choices=EQUIPMENT_CHOICES) equipment_two = models.CharField(max_length=200, choices=EQUIPMENT_CHOICES, blank=True, null=True) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) workout_tip = models.TextField(max_length=3000, blank=True) cmf_url = models.URLField(max_length=400, blank=True) # exercise_id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) def … -
Django: filter results using Primary Key
In my data.html I need both information from the File Model and the Week Model. Using colors = File.objects.filter(user=request.user.userdata).filter(pk=pk) I can get all the information that I need of the file with the right PK when I open the html without problems, but data = list(Week.objects.filter(user=request.user.userdata).filter(pk=pk).values_list())[2:] is giving me back just a blank variable. How can I access all the values in my field based un pk for te data variable? Thank you MODEL class File(models.Model): user = models.ForeignKey(UserData, on_delete=models.CASCADE) docfile = models.FileField(upload_to=path) color = models.CharField(max_length=250) class Week(models.Model): user = models.ForeignKey(UserData, on_delete=models.CASCADE) file_doc = models.OneToOneField(File, on_delete=models.CASCADE) monday = models.PositiveIntegerField(null=True) tuesday = models.PositiveIntegerField(null=True) wednesday = models.PositiveIntegerField(null=True) thursday = models.PositiveIntegerField(null=True) friday = models.PositiveIntegerField(null=True) saturday = models.PositiveIntegerField(null=True) sunday = models.PositiveIntegerField(null=True) VIEW def week_data(request, pk): colors = File.objects.filter(user=request.user.userdata).filter(pk=pk) labels = [f.name for f in Week._meta.get_fields()] data = list(Week.objects.filter(user=request.user.userdata).filter(pk=pk).values_list())[2:] context = { 'labels': labels, 'data': data, 'colors': colors } return render(request, 'data.html', context) HTML <!DOCTYPE html> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="doughnut-chart" width="800" height="450"></canvas> new Chart(document.getElementById("doughnut-chart"), { type: 'doughnut', data: { labels: [{% for label in labels %} '{{ label|capfirst }}', {% endfor %}], datasets: [ { label: "Population (millions)", backgroundColor: [{% for color in colors %} '{{ color }}', {% endfor %}], data: [{% for value … -
overwrite save django method
I need to override Django's method save so when the purchase is made by a certain cpf, it is saved with "Approved" status. Can someone help me? Follow the models.py class Purchases(TimeStampedModel): APROVADO = "AP" EM_VALIDACAO = "VA" STATUS_CHOICHES = ( (APROVADO, "Aprovado"), (EM_VALIDACAO, "Em validação"), ) values = models.DecimalField(decimal_places=2, max_digits=10, default=0) cpf = BRCPFField("CPF") status = models.CharField(max_length=20, choices=STATUS_CHOICHES, default=EM_VALIDACAO) -
Why CORS headers does not concern http requests from the browser
I want to understand in depth CORS. If we consider the definition of https://developer.mozilla.org/: Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. So my question is quite simple : Its normal if CORS policy is triggered if we use fetch() from a website hosted on a separate server (separate ip). But the question is, why when we make a HTTP request from a browser to a particular website the CORS policy is not triggered ,knowing that the source of the request comes from a different ip from that of the server hosting the website ? Thanks in advance -
Facing errors while using Django post office setup for sending mails
Issue Error is due to attachments folder(post_office_attachments) not being able to generate on linux server. Error TypeError at /dev/generate_request/ Object of type 'TypeError' is not JSON serializable Request Method: POST Django Version: 2.2.3 Exception Type: TypeError Exception Value: Object of type 'TypeError' is not JSON serializable Exception Location: /usr/lib/python3.6/json/encoder.py in default, line 180 Python Executable: /usr/bin/python3 Related Code try: html = template.render(context) email_message = EmailMultiAlternatives(subject, html, from_email, [to_email]) email_message.attach_alternative(html, 'text/html') template.attach_related(email_message) email_message.send() return "success" except Exception as e: return "Error: unable to send email due to" + e Which piece of code is causing the error template.attach_related(email_message) -
Django: Changing the model field in the database when the button is clicked
I am creating a web application for a pizzeria. You need to add an action: when you click on the "Order delivered" button, the order status should change to "Order completed". How to do it? It is necessary that when you click on the button, the status field in the order changes models.py: from django.db import models from django.db.models.fields import DecimalField, NullBooleanField import decimal from django.utils import timezone from django.db.models.signals import pre_save from django.dispatch import receiver class Product(models.Model): title = models.CharField(verbose_name='Название продукции', max_length=100) count = models.DecimalField(verbose_name='Кол-во на складе', max_digits = 10, decimal_places=4) price = models.DecimalField(verbose_name='Цена', max_digits = 10, decimal_places=4) date = models.DateField(verbose_name='Дата обновления', default=timezone.now()) def __str__(self): return self.title class Meta(): verbose_name = 'Продукты' verbose_name_plural = 'Продукция' class Technology_card(models.Model): title = models.TextField(verbose_name='Название ТК',default='Технологическая карта для пиццы') pizza_box = models.DecimalField(verbose_name='Коробки пиццы',max_digits = 10, decimal_places=4, default=1) napkins = models.DecimalField(verbose_name='Салфетки',max_digits = 10, decimal_places=4, default=6) dough = models.DecimalField(verbose_name='Тесто',max_digits = 10, decimal_places=4, default=0) flour = models.DecimalField(verbose_name='Мука',max_digits = 10, decimal_places=4, default=0) tomato_sauce = models.DecimalField(verbose_name='Соус томатный',max_digits = 10, decimal_places=4, default=0) cream_sauce = models.DecimalField(verbose_name='Соус сливочный', max_digits = 10, decimal_places=4, default=0) olive_oil = models.DecimalField(verbose_name='Оливковое масло', max_digits = 10, decimal_places=4, default=0) mozzarella_cheese = models.DecimalField(verbose_name='Сыр Моцарелла', max_digits = 10, decimal_places=4, default=0) parmesan_cheese = models.DecimalField(verbose_name='Сыр Пармезан', max_digits = 10, decimal_places=4, default=0) dor_blue_cheese = … -
Declaring an app label error for django oauth2_provider package
I am trying to upgrade my apps django version from 1.8 to 3.2. my root URL config is defined as: ROOT_URLCONF = 'clickwork.urls' in settings.py inside the urls file, I have this imports: from django.conf import settings import oauth2_provider.views as oauth2_views from django.contrib import admin admin.autodiscover() the ouath2provider import statement is throwing app_label error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Here is what I have tried to resolve the issue: Upgrading the oauthprovider package to the latest version 1.5, it supports Django 2.2+ as per their docs. https://github.com/jazzband/django-oauth-toolkit Adding apps.py file in the root directory and adding the path to the project config in INSTALLED_APPS in settings, this is mentioned in the Django 3.2 release notes: https://docs.djangoproject.com/en/3.2/ref/applications/#configuring-applications-ref I went through the django.contrib.contenttypes.models.ContentType class code and added an app label, it was not there before: class ContentType(models.Model): app_label = models.CharField(max_length=100) model = models.CharField(_('python model class name'), max_length=100) objects = ContentTypeManager() class Meta: verbose_name = _('content type') verbose_name_plural = _('content types') db_table = 'django_content_type' unique_together = [['app_label', 'model']] Doing step3 solves the problem but obviously changing the code in the package is dumb. Can anyone guide me on what I am doing … -
Can permissions mixin be used in some other model rather than the auth user model?
In my web application, a single user can have many accounts, but user has to login only once. However, different accounts can have different permissions. Each account has its own session and the request.user will change depending on which account the user has logged in to. And there will be two types of login, the first type is when user logs into the website, and the other type is when user logs in into any of his account. I used the django auth user model to store the user's email and password and use it only for first type login and it does not inherit the permissions mixin. And for accounts, I have an account model which does inherit permissions mixin. It is used for second type log in and relating each account to its set of permissions. After doing this I am facing issues, since third party libraries like django-rules still refer to the auth user model for permissions when calling request.user.has_perm('some_perm_string') So is it a good practice to have permissions mixin used in some other model rather than the auth user model? If not then permissions is available in Django as a mixin? -
Deserialize to get an object instance
I would like to deserialize django rest framework serialized data to get back an object, i.e to do something like Modelname.objects.get(**serialized_data). However when I try the following, I get validation error because drf is attempting to create a new instance and it already exists. I only need to retrieve existing object. How can I do that without resorting to manually getting each field parameter from the dict? My code: clinic = biovardata['linkedclinic'] print("\n Deserializing clinic..") print("Clinic:", clinic) clinicserializer = ClinicSerializer(data=clinic, many=False) if clinicserializer.is_valid(): print("Clinic Serializer is valid") cl = Clinic(clinicserializer.validated_data) print("Clinic is ", clinic) else: print("Clinic Serializer is not valid") print(clinicserializer.errors) My output: Deserializing clinic.. Clinic: {'clinicid': 21, 'name': "Clinic name", 'label': 'joelper'} Clinic Serializer is not valid {'name': [ErrorDetail(string='clinic with this name already exists.', code='unique')], 'label': [ErrorDetail(string='clinic with this label already exists.', code='unique')]} -
How to inner join tables based on ManyToManyField and group by a parameter and get latest one in Django?
I have two models with ManyToManyField relationship: class Education(models.Model): title = models.CharField(default=None, max_length=100) content = models.TextField(default=None) price = models.ManyToManyField(Price) class Price(models.Model): cost = models.CharField(default=None, max_length=20) created_at = models.DateTimeField(auto_now=True, null=True, blank=True) I can fetch all rows like this: result = Education.objects.filter(price__in=Price.objects.all()).select_related('Price')/ .values_list('title', 'content', 'price__cost', 'price__created_at') But now i want to group by education.id and the cost parameter should be latest parameter that inserted(based on created_at). So i want to have list of all Education with latest cost that inserted for every education. -
How to add signals with atomic transaction?
I have some api which will create User model and I have a post_save signal which will do some database update. I want to apply transaction.atomic but is it required when using signal ? Does signals handle atomic transaction? If not how can I make it ? @receiver(post_save, sender=User) def some_signal(sender, instance, using, **kwargs): # some database transaction if instance: ..... class User(AbstractUser): .... # api User.objects.create() -
How to convert the last number of Str = (2021GC110) in Int on Python
I'm begginer in Django and i trying convert Str where the base for this is (2021(year) - CG(product name) - 1(ID product) -101 (var the product). But I need the last number for variable. exemple: product 1: 2021CG1101 product 2: 2021CG1102 this is my view.py if serialNumberForm.is_valid(): os = serialNumberForm.save(commit=False) Produto.numeroSerie = NumeroSerie.id os.numeroSerie = id lastProduct = NumeroSerie.objects.last() if lastProduct == None: prefix = datetime.date.today().year fix = product.nome[3:6] sufix = Produto.id var = 10 os.serialNumber = str(prefix) + fix + str(sufix) + str(var) elif int(lastProduct.serialNumber[0:3]) != datetime.date.today().year: prefix = datetime.date.today().year fix = product.nome[3:6] sufix = Produto.id var = 10 os.serialNumber = str(prefix) + fix + str(sufix) + str(var) else: prefix = datetime.date.today().year fix = product.nome[3:6] sufix = NumeroSerie.produto(os) var = (lastProduct.serialNumber[-1]) =+ 1 os.serialNumber = str(prefix) + fix + str(sufix) + str(var) os.save() -
Multiple table in a same Row using Python-docx?
I want to create two separate tables starting at the same line. I already tried WD_TABLE_DIRECTION, WD_TABLE_ALIGNMENT it works only for a different line or a level different line. ''' from docx.enum.table import WD_TABLE_DIRECTION table = document.add_table(3, 3) table.direction = WD_TABLE_DIRECTION.RTL or table.direction = WD_TABLE_DIRECTION.LTR ''' from docx.enum.table import WD_TABLE_ALIGNMENT table = document.add_table(3, 3) table.alignment = WD_TABLE_ALIGNMENT.CENTER or LEFT or RIGHT ''' -
How to add a custom method to a model field in Django?
I have two models that will use the same CardNumberField() to store credit card numbers. How can I add a custom method to the field to mask the card numbers? I have created the CardNumberField() which inherits from models.Charfield: # CARD NUMBER FIELD class CardNumberField(models.CharField): description = _('card number') def __init__(self, *args, **kwargs): kwargs['max_length'] = 19 super().__init__(*args, **kwargs) The CardNumberField() is then imported and used in my customers/models.py: # CARD MODEL class Card(models.Model): number = CardNumberField() ... def __str__(self): return 'Card [{number}]'.format(number=self.number) ...and in my transactions/models.py: # TRANSACTION MODEL class Transaction(models.Model): card_number = CardNumberField() ... def __str__(self): return 'Transaction ...' So, how can I add the following method to my CardNumberField() to be used by both of my models? def masked_number(self): # display masked card number number = self.number return number[-4:].rjust(len(number), '#') Also, how will I grab this field method in a DRF serializer class? -
Issue while deploying django site on AWS (TemplateSyntaxError)
I manage to deploy my site on AWS using NGINX and Gunicorn. The site was working fine but not I noticed there's an error when I visit the page. Can anyone guide me on what went wrong? here's the live site link: http://ec2-3-16-152-98.us-east-2.compute.amazonaws.com/ -
DRF-Yasg - blank page when trying to enter swagger ui view
This is my urls.py code, which is similar to the code provided in the documentation. from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns += [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] When I'm trying to enter /api/swagger/ I see nothing more than a blank page with two links. I'm pretty sure I should see something more... colorful. Another try: /api/swagger.json leaves me with some JSONs with endpoints, parameters, status codes, etc. -
VSCode debugger not running inside virtual environment
I'm trying to debug my Django application within VSCode, but for some reason VSCode isn't running inside my virtualenv. I've tried multiple ways for it to work, but still no luck. I've set pythonpath to the path of the Pythonfile inside my virtualenv: "python.pythonPath": "/Users/username/documents/programmering/bq/env/bin/python3" I've tried selecting the Python file inside my virtual environment as the interpreter in VScode I've added the following line to my launch.json: "env": { "PYTHONPATH": "${workspaceRoot}"} If I run the debugger and print sys.version and sys.path I'm getting the following prints: SYS VERSION: 3.9.7 (default, Oct 13 2021, 06:44:56) [Clang 12.0.0 (clang-1200.0.32.29)] SYS PATH: ['/Users/username/Documents/Programmering/bq/project/projectile', '/Users/username/Documents/Programmering/bq/project', '/usr/local/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/usr/local/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/usr/local/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/site-packages'] This is what my interpreters looks like, not that I've got pyenv installed and have run "pyenv global 3.9.7" to set a global version for python as well ass "pyenv local 3.6.9" inside my project folder, to have the latter python version active for my project. Interpreters in VSCode What I'm a bit puzzled about is that in the directories for the interpreter the path is to the pyenv version of python, and not the actual python version in the virtual environment, perhaps that can be the cause for the issue? How would I … -
How can I solve attempted relative import beyond top-level package
I try to integrate django with scrapy my directoly is like this djangoproj / djangoproj / settings.py / urls.py / myapp / models.py ( it has the class named DjangoModel ) / views.py / scrapyproj / myscrapyapp / google.py / pipelines.py / items.py I go to the djangoproj/scrapyproj and exec like this scrapy crawl google Now I want to access the django model from pipelines.py So, my piplines.py from itemadapter import ItemAdapter from datetime import datetime import os from ..myapp.models import DjangoModel However, error occurs attempted relative import beyond top-level package -
Django: Add result from second queryset to first queryset
I have two models from two different databases (one read-only) without ForeignKey between the two models (did not get that working, as far i found it isn't possible). In the main model I store the ID from the second model (read-only DB). I want to display multiple records/rows on one view (like al table) There for I want to get the content of the second model with the id from the main model. and combine it to one row. Normal you can get it by the ForeignKey but did won't work with 2 different databases. What i got (simplified): model.py class Overeenkomst(models.Model): park = models.IntegerField(blank=False, null=False, default='0') object = models.IntegerField(blank=False, null=False, default='0') # ID from model second database date_start = models.DateField() date_end = models.DateField() class Object(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. nummer = models.IntegerField(db_column='NUMMER', blank=True, null=True) # Field name made lowercase. omschrijving = models.CharField(db_column='OMSCHRIJVING', max_length=50, blank=True, null=True) # Field name made lowercase. idobjectsoort = models.IntegerField(db_column='IDOBJECTSOORT', blank=True, null=True) # Field name made lowercase. idobjecttype = models.IntegerField(db_column='IDOBJECTTYPE', blank=True, null=True) # Field name made lowercase. (.....) class Meta: managed = False db_table = 'OBJECT' unique_together = (('nummer', 'idpark', 'id'), ('id', 'idpark', 'idobjecttype', 'idobjectsoort', 'dubbelboeking'), ('code', 'id'),) def __str__(self): return … -
serializing only certain fields from a queryset in django serializer class
I have a queryset which I obtain from get_queryset(). What we know is, the returns of queryset gives the list of objects which contains all the fields of the model. Now I don't want to serialize all the fields from the model and show all of them in the response. I want to serialize only few fields and show in the api response. for eg: def get_queryset(self): """"" filtering happens here on the query parameters. """ abc = self.request.GET.get('abc',None) Now I have a defualt list function where I have to call serializer class only with the specific fields. def list(self, request, *args, **kwargs): queryset = self.get_queryset() # data ={ # "name":queryset. # } # serializer = ExampleSerializer(data,many=True) #serializer = serializers.serialize("json",queryset=queryset,fields=['id','name','address']) return Response(serializer, status=status.HTTP_200_OK) When I do print queryset it gives complex queryset and when I do print(type(queryset)),it gives the following <class 'django.db.models.query.QuerySet'> Now how to serialize name and address fields only to the exampleserializer class?? I did some digging and tried to do the following #serializer = serializers.serialize("json",queryset=queryset,fields=['id','name','address']) but it does not give the output in the required format not like regular json. Also it gives model: Example in the response of every object.