Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ManyToMany validation in model layer
I have model with manytomany field and the task is to make an validation in model layer. I did research and in every other cases they recommended to create validation in Form layer. But problem with this, is when i will create object in djangoadmin or with seeder, saved data can cause problems. So i decided to make validation in model layer. Here is my model: class Position(models.Model): pos_id = models.BigAutoField(primary_key = True) pos_name = models.CharField(max_length=80) level = models.IntegerField(default=1) def __str__(self) -> str: return self.pos_name class Meta: verbose_name = 'Position' verbose_name_plural = 'Positions' class Boss(models.Model): boss_id = models.BigAutoField(primary_key=True) boss_position = models.ForeignKey(Position, null=True, on_delete = CASCADE) subordinates = models.ManyToManyField(Position,related_name='bosses') def __str__(self) -> str: return self.boss_position.pos_name @property def position(self): return self.boss_position def clean(self) -> None: subordinates_list = self.subordinates.objects.all() if self.boss_position in subordinates_list: raise ValidationError(_('Boss cant be boss in his subordinate list')) class Meta: verbose_name = 'Boss' verbose_name_plural = 'Bosses' thanks in advance for your reply -
Why am I being referred to by http://127.0.0.1:8000/admin/login/?next=/admin/
I tried to go to the django admin panel, but when I enter a request for 127.0.0.1:8000/admin I am referred to http://127.0.0.1:8000/admin/login/?next=/admin/ and the screen is displayed this: "A server error occurred. Please contact the administrator." This is my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apple.apps.AppleConfig' ] TEMPLATES = [ { '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', ], }, 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, }, ] urls.py in project folder from django.contrib import admin from django.urls import path, include from apple.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', include("apple.urls")), ] P.S. I've done everything that's written in the documents of the django admin site, but it still doesn't work. -
How to hide fields that belong to the model I'm inheriting from in django admin panel
I have these 2 models in my models.py class Student(AbstractBaseUser): date_of_birth = models.DateField(null=True) phone_number = PhoneNumberField(null=True) class Teacher(Student): bio = models.TextField(null=True) image = CompressedImageField(null=True, blank=True, default="default.png") student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) Now in admin panel when i go to edit the Teacher instance I display only bio image and student. The issue is that also display those fields when I try to edit Teacher instance but entering from Student model. So is there a way for that? P.S the models and fields may not make sense because they are examples. -
how to persist sqlite3 DB data in heroku django application
This app is a django web site. I inserted a record using django admin function from admin web page. After inserting, I closed the admin web page, and I could see the record shown on the normal web page. But after one hour later, the record disappeared (I could not see in my normal web page and admin web page when I browsed again.). I upgraded this app(c9-django-mblog-ho) and another app(django-mblog-ho) from heroku-16 to heroku-20 yesterday(2022-4-19 08:00 UTC+8 Asia Taipei time). Both app have the same problem. I did not have the problem on heroku-16 stack. Please help me to solve the problem: Keep sqlite3 DB data persistent! Thank you very much! -
TypeError: module() takes at most 2 arguments (3 given) Django manage.py runserver
I tried running manage.py runserver manage.py makemigrations and manage.py migrate but they all give me a TypeError The error is Traceback (most recent call last): File "/Users/William/Documents/Start over/Simple/perputer/manage.py", line 22, in <module> main() File "/Users/William/Documents/Start over/Simple/perputer/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/William/Documents/Start over/Simple/perputer/words/models.py", line 4, in <module> class Word(models): TypeError: module() takes at most 2 arguments (3 given) I haven't changed my manage.py and my models.py that's causing the error: from django.db import models # Create your models here. class Word(models): <-- error word = models.CharField(max_length = 26) meaning = models.TextField(help_text = "A definition for the word attached to it.") language = models.CharField(max_length = "20", … -
How can i array to grid table in Django HTML?
I can send my model to the html page and bring it to the array structure, but I cannot integrate this array into the grid table. Does anyone know how I can do this? views.py def tests(request): resultQueryet = ResultsModel.objects.all() requests = serialize('json', resultQueryet) context = { "requests" : requests } return render(request, 'admin/tests.html', context=context) html {% block content %} <div class="card-body"> <div id="table-card" class="table-card"></div> </div> {% endblock %} {% block extra_js %} <script> var model = {{requests|safe}}; console.log(model) document.getElementById("table-card") && new gridjs.Grid({ columns: ["Name", "Surname", "Date", "Amount", "Result", "Details"], sort: !0, pagination: { limit: 5 }, data: [ [ {% for x in model %} {{x.name}}, {{x.surname}}, {{x.date}}, {{x.amount}}, {{x.result}}, {{x.details}}, {% endfor %} ], ], }).render(document.getElementById("table-card")) </script> <script src="{% static 'libs/prismjs/prism.js'%}"></script> <script src="{% static 'libs/gridjs/dist/gridjs.umd.js'%}"></script> <script src="{% static 'js/pages/gridjs.init.js'%}"></script> {% endblock extra_js %} I can view the model as array on the console screen, but I cannot print it to the table via a for loop. -
how to gather logs in django with aws autoscaling (ecs or beanstalk or simple autoscaling)
Im wondering if there is a feature in aws to gather logs of application such as django when autoscaling is enabled? Do I need to do it manually with bashscript and a storage or is it available in aws monitoring tools? Thanks a lot. Best, -
How to Configure a column not to visible by default in django admin
I want to hide one column and make the column visdible but if user want the user view the column, i tried this way but did not worked forr me. admin.py class ProductAdmin(TimestampedModelAdminMixin, ConfigurableColumnsMixin, admin.ModelAdmin): list_display = [ "id", "comment", "active", ] I tried with this way but did not worked. def get_form(self, request, obj=None, **kwargs): form = super(ProductAdmin, self).get_form(request, obj, **kwargs) del form.base_fields["comment"] return form -
Uploading a csv file and assigne it to the user - django
I want to create a project an I need to upload an csv file to an user, but from some reason, it's not loading correctly (is uploading for the first created user, and I try do to this from others accounts). In my view, I have something like this: def FileViewUpload(request): form = CsvFileForm(request.POST, request.FILES) print(request.user) userId = request.user.id print(userId) print(request.user.email) if form.is_valid(): form.save() form = CsvFileForm() obj= CsvFileModel.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: date = row[0] user = AccountUser.objects.get(contact_user = userId) print(user) ContactUser.objects.create( date=date, message= row[1] user=user, ) obj.activated=True obj.save() return render(request, 'uploadFile.html', { 'importFile': form }) For this lines: print(request.user) print(userId) print(request.user.email) it display the good thing, the correct id and email for that specific user. But when I press the button for upload, it's loading in the field for the first user created. The problem, I think that is in this line: user = AccountUser.objects.get(contact_user = userId), but I don't know why, if in the beginning, at the first prints, it's show me correctly. The model for ContactUser: class ContactUser(models.Model): user = models.ForeignKey(AccountUser, related_name='contact_user', on_delete=models.CASCADE) date = models.CharField() message = models.CharField() def __str__(self): return f"{self.user}" -
Django 3.2+: case-sensitive string comparisons within MySQL tables
Django documentation (3.2 to 4.0) states: In MySQL, a database table’s collation determines whether string comparisons (such as the expression and substring of this function) are case-sensitive. Comparisons are case-insensitive by default. from 3.2 on, there is mention that it is now possible to define at the level of the CharField the collation to use: https://docs.djangoproject.com/en/3.2/ref/databases/#collation-settings but I find nowhere what value I should use for db_collation to enable case-sensitive string comparisons for a given CharField: case_sensitive_collation = ??? name = models.CharField(max_length=50, db_collation=case_sensitive_collation) Just found this gist to do the contrary: CreateCollation and db_collation to implement a case-insensitive Charfield with Postgres > 12 https://gist.github.com/hleroy/2f3c6b00f284180da10ed9d20bf9240a can somebody help me out? -
how to display a nested list
I have a recursive table, of which I want to present the main elements and their sebelements id name parent order 1 Menu A 1 2 Menu B 2 3 Menu a 1 1 4 Menu b 2 1 5 Menu C 3 6 Menu D 4 7 Menu a 6 1 8 Menu b 6 2 And what I want to present respecting the order of the main Menu, and within each menu its submenu with the assigned order View menus = Menu.objects.values('id', 'name', 'icon', 'parent').filter(estado=1).order_by('order') I'm using the regroup tag but it doesn't even group it by parent I think the change must be in values but I can't find the solution TEMPLATE {% regroup menus by parent as menu_list %} {% for parent in menu_list %} {{parent.grouper}} {{parent.id}}, {{parent.name}} {% for submenu in parent.list %} {{submenu.id}}, {{submenu.name}} {% endfor %} {% endfor %} Desired result Menu A Menu a Menu B Menu b Menu C Menu D Menu a Menu b -
How can i use django template tag to view some thing that i have created in database?
When i create multiple product i can see my <div class='card'> content in browser. But i can not see the values that i have submited in my database fields. For example i have created a product in admin page with number of 1 since i have specified {{pr.number}} in my template. how can i see the values of database fields that i added in admin page in my templates? template: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> </head> <body> {% for i in pr%} <div class='card'> <div class="number">{{pr.number}}</div> <img src="{% static '3307209.jpg'%}"> <span class="prname">{{pr.name}}</span> <p id="id">{{pr.description}}</p> <button><span class="price"> {{pr.price}}</span> <img id='add'src="{% static 'add.png'%}"> Add to cart</button> </div> {%endfor%} </body> </html> models: from django.db import models # Create your models here. class product(models.Model): number=models.IntegerField() name=models.CharField(max_length=20) description=models.CharField(max_length=150) price=models.IntegerField() views: from django.shortcuts import render from .models import product # Create your views here. def a (request): db=product.objects.all() return render (request,'main page.html',{'pr':db}) -
ForeignKey and ManyToManyField in a list of all obejcts
Despite my consultation of the documentation I can't find my solution. I want to show in my templates the values linked by ManyToManyField and ForeignKey. I have this model: class Adresse(models.Model): libelle = models.fields.CharField(max_length=100) numero = models.fields.IntegerField(null=True) street = models.fields.CharField(max_length=100) code = models.fields.IntegerField(null=True) city = models.fields.CharField(max_length=100, null=True) country = models.ForeignKey(Country, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.libelle}' class Trip(models.Model): title = models.fields.CharField(max_length=100) traveller = models.ManyToManyField(Character) date_start = models.DateField(default=date.today) date_end = models.DateField(default=date.today) def __str__(self): return f'{self.title}' class Activity(models.Model): trip = models.ForeignKey(Trip, null=True, blank=True, on_delete=models.SET_NULL) adresse = models.ForeignKey(Adresse, null=True, blank=True, on_delete=models.SET_NULL) date_start = models.DateField(default=date.today) date_end = models.DateField(default=date.today) class Meta: verbose_name_plural = "Activities" and this view to display the total list of trips: from django.shortcuts import render # Create your views here. from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, redirect, render from travel.models import Trip, Adresse, Activity from profiles.models import Character @login_required def travel_list(request): travels = Trip.objects.all() travellers = Character.objects.all() template = 'travel/travel_list.html' context = { 'travels' : travels, 'travellers' : travellers, } return render(request, template, context) @login_required def travel_detail(request, travel_id): travel = get_object_or_404(Trip, id=travel_id) activities = Activity.objects.filter(trip_id=travel_id) travellers = travel.traveller.all().order_by("last_name", "first_name") template = 'travel/travel_detail.html' context = { 'travel': travel, 'activities' : activities, 'travellers' : travellers, } return render(request, template, context) et … -
Create Hierarchical Category Tree In Django
I have a large CSV (27k + rows) that I want to import into a model and from there create a hierarchical tree in a template. Example The child categories go up to 9 levels deep. I was thinking MPTT would maybe be the way to go because of the size of the dataset, but the tutorial doesn't talk about large imports and I can't extrapolate how to use their example in a large set. I'm not married to mptt, I'd be fine even doing this with multiple tables and somehow relate them like a many to one. That brings me to my question: How do you relate the child to the parent in a large set you can't hand type in? Category Screenshot mptt tutorial example from myapp.models import Genre rock = Genre.objects.create(name="Rock") blues = Genre.objects.create(name="Blues") Genre.objects.create(name="Hard Rock", parent=rock) Genre.objects.create(name="Pop Rock", parent=rock) Things I've Tried I know this is wrong on multiple levels. That is not a good use of time/space on a large set. def show_categories(request): categories = Categories.objects.all() parents = {} children = {} for cat in categories: if cat.cat_parent_id == 0: parents[cat.cat_name] = cat.category_id if cat.cat_parent_id > 0: children[cat.cat_name] = cat.cat_parent_id return render( request, "amazon_niche_finder/categories.html", { … -
Django How to fix UnboundLocalError in Models.py
I am getting the following error in models.py, "except Balance.DoesNotExist: UnboundLocalError: local variable 'Balance' referenced before assignment". How can I fix this error? I am trying to create a book keeping website. I have created three classes within my models.py file Models.py class Residents(models.Model): house_number = models.CharField(max_length=100,unique=True,primary_key=True) name = models.CharField(max_length=100) contact_number = PhoneNumberField() def __str__(self): return self.house_number + " " + self.name class Balance(models.Model): primary_key=True) residents = models.OneToOneField(Residents, on_delete=models.CASCADE, primary_key=True) date = models.DateTimeField(default=timezone.now) previous_balance = models.DecimalField(max_digits=1000, decimal_places=2 , null=True) transaction = models.DecimalField(max_digits=1000, decimal_places=2, null=True) def save(self, *args, **kwargs): current_balance = self.previous_balance + self.transaction class Transaction(models.Model): transaction_id = models.CharField(primary_key=True,max_length=100,unique=True) residents = models.ForeignKey(Residents, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) updated = models.DateTimeField(auto_now=True) transaction_Amount = models.DecimalField(max_digits=1000, decimal_places=2) date = models.DateTimeField() def save(self, *args, **kwargs): if self.created is None: self.created = timezone.now() try: last_bal = Balance.objects.filter(pk = self.residents).get() except Balance.DoesNotExist: Balance, Created = Balance.objects.update_or_create(residents = self.residents,date=datetime.date.today(), previouse_balance=last_bal.current_balance, transaction=self.transaction_Amount) else: Balance.objects.create(residents = self.residents, date=datetime.date.today(), previouse_balance=0.00, transaction=0.00) Whenever a new transaction is made I would like the system to first check if the resident have made a transaction yet, if the resident did I would like to update the balance ,else create a new Balance Error except Balance.DoesNotExist: UnboundLocalError: local variable 'Balance' referenced before assignment -
Django: list object is not callable in forms.py
I’m trying to add a RegexValidator validator to a contact form (forms.py) to prevent spammers from adding http:// and https:// links in the message. I’ve included from django.core.validators import RegexValidator at the top of forms.py. This example of general_message works fine when not using the validator: general_message = forms.CharField(label='General message*', required=True, widget=forms.Textarea( attrs={'class': 'form-control', 'maxlength': '1000', 'rows': 8} )) But I get the error 'list’ object is not callable in the example below: general_message = forms.CharField(label='General message*', required=True, widget=forms.Textarea, validators=[RegexValidator(regex=r'http(s)?|HTTP(s)?', message="No http or https allowed", code="invalid")] ( attrs={'class': 'form-control', 'maxlength': '1000', 'rows': 8} )) It appears I have my brackets and parentheses correct. What causes the error? -
Turning CharField and DateField into slug in models.py is giving me 'djangodbmodelsfieldscharfield-djangodbmodelsfieldsdatetimefield'
I made this to make a slug of each blog post, from the title: from django.db import models from django.utils.text import slugify class post (models.Model): title = models.CharField(max_length=200) post = models.CharField(max_length=75000) picture = models.URLField(max_length=200, default="https://i.ibb.co/0MZ5mFt/download.jpg") show_date = models.DateTimeField() slug = models.SlugField(unique=True, default=slugify(f"{title} {show_date}"), editable=False) The thing is, this is the slug I get: http://127.0.0.1:8000/blog/blog/djangodbmodelsfieldscharfield-djangodbmodelsfieldsdatetimefield/ How can I get it to be http://127.0.0.1:8000/blog/blog/slug-of-title-and-date? -
Django context processors available globally to templates in ALL apps
I am new to Django/Python, and am trying to figure out the best way to have global constants in my project that are available to templates in ALL APPS in the project. Basic globals like Company name, Phone number, url, social links, etc. After quite a bit of searching, the best answer I have found is to create custom context processors, but the way I am understanding it would require me to create a custom content_processors.py file in each app, and add a reference to each one in the main project’s settings.py. This seems to violate the DRY concept, and I am assuming I must be missing something basic. So here is what I have now. My project is called www and one of the apps is called home. In www/settings.py I have a line as follows: COMPANY_NAME = ‘My Company Name’ I created this file home/context_processors.py with the following contents: from django.conf import settings def www(request): return { 'company_name': settings.COMPANY_NAME } In the TEMPLATES/OPTIONS/content_processors section of my www/settings.py, I added: ’home.context_processors.www’ And my homepage template in /home/templates has {{ company_name }} This works perfectly, but now when I create another app called products, it seems as though I need … -
using opclasses in GinIndex in django is throwing this error TypeError: __init__() got an unexpected keyword argument 'opclasses'
I am trying to use indexing for using icontain lookup in query, have come across many answers in stackoverflow only which suggests to use GinIndex these are the stackoverflow answers I was looking to I was trying answer 6 in the above link but it is throwing this error : File "/home/salvi.rawat/venv/transcend/store/models.py", line 53, in Meta GinIndex(fields=['name'], opclasses=['gin_trgm_ops']) TypeError: init() got an unexpected keyword argument 'opclasses' I am using django version 1.11 maybe that could be the reason, but need help in this case. thankyou. -
Django Logging user id
hi I'm wondering if there's any way to log user id in django logging and I want to store logs only for one view requests (store in database). -
django query set returns irrelevant result
in a django project I send a query set to database by ID but gets the answers but index. for example I need the query for ID 1 and 2 but gives me the result for index 1 and 2.. any hints? -
Django Template login.html does not exist Okta Auth
I've been trying to implement Okta Auth for authentication on my Django web application. Currently I am running into the following error: django.template.exceptions.TemplateDoesNotExist: okta_oauth2/login.html. Here are the relevant settings.py: AUTHENTICATION_BACKENDS = ("okta_oauth2.backend.OktaBackend",) OKTA_AUTH = { "ORG_URL": "https://{org}.okta.com/", "ISSUER": "https://{org}.okta.com/oauth2/default", "CLIENT_ID": os.getenv('okta_client_id'), "CLIENT_SECRET": os.getenv('okta_secret_id'), "SCOPES": "openid profile email offline_access", # this is the default and can be omitted "REDIRECT_URI": "http://localhost:8000/accounts/oauth2/callback", "LOGIN_REDIRECT_URL": "/", # default "CACHE_PREFIX": "okta", # default "CACHE_ALIAS": "default", # default "PUBLIC_NAMED_URLS": (), # default "PUBLIC_URLS": (), # default "USE_USERNAME": False, # default } .... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'django.template.context_processors.request', ], }, }, ] Directory structure: root -- > app1 --> templates --> app1 --> several HTML files (django is able to find these templates). root -- > okta_oath2 --> templates -- > okta_oath2 --> login.html I have tried placing the login.html in several different places but can't seem to figure out where it should go. The debug log keeps giving me the same error. -
How to hide column if userwants to hide it, Django Admin
I want to hide one column and make the column visdible but if user want the user view the column, i tried this way but did not worked forr me. admin.py class ProductAdmin( TimestampedModelAdminMixin, ConfigurableColumnsMixin, admin.ModelAdmin): list_display = [ "id", "comment", "active", ] I tried with this way def get_form(self, request, obj=None, **kwargs): form = super(ProductAdmin, self).get_form(request, obj, **kwargs) del form.base_fields["comment"] return form -
AttributeError: 'str' object has no attribute 'strftime' when changing H:M:S format to H:M [closed]
here my time is 15:00:00 i need it as 3pm and 15:00 both formats in python3 i have tried is job = Job.objects.get(id=3) time = job.time.strftime('%H:%M) i am getting this error AttributeError: 'str' object has no attribute 'strftime' How i make to print in format of 15:00 and 3pm -
Django ORM: Get maximum value of a field with corresponding other fields values
I have this Table (Counters): I want to get the specific date_time value of the maximum traffic (which is calculated based on the the fields tftralacc, tfnscan, thtralacc and thnscan) for every cell_id. I've managed to get this maximum value for every cell_id by using the annotate() and group_by() functions of the Django's QuerySet API: result = Counters.objects.filter( date_time__gte = date_start, date_time__lte = date_end ).annotate( # calculate the traffic for each row. traffic = Case( When(Q(tfnscan=0) or Q(thnscan=0), then=0), default = Round((F('tftralacc')*1.0/F('tfnscan')) + (F('thtralacc')*1.0/F('thnscan')), 2), output_field=FloatField() ) ).order_by('cell_id').values( # Group by cell_id. 'cell_id' ).order_by().annotate( # calculate the max traffic for the grouped Cells. max_traffic = Max('traffic') ) The calculated traffic for every date_time is demonstrated here: My code successfully returns the maximum traffic for every cell_id: But my goal is to get the Corresponding date_time value for every max value. like this: or Because that max value is just a mean to get the date_time and not the goal. Note: There is this question that describes my problem, but its answer refers to a work-around solution, which is not possible with my problem. SO Question