Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Does it make sense to point to same table twice on django model
I have this Tables class Category(models.Model): name = models.CharField(max_length=20) class Rule(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) next_page = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) # ... other fields Obviously, I am no database or Django expert, the need for next_page and category are different The Rule table is supposed to be used to set the page that comes next after certain condition are met/performed by the user. My general question is there a better way to do this? -
How to exclude objects connected via ForeignKey Django?
class AnimalX(models.Model): my_animal = models.ForeignKey('animals.MyAnimal', on_delete=models.CASCADE, null=False, blank=False, related_name='animals') class MyAnimal(models.Model): name = models.CharField(max_length=256) I'd like to get all the MyAnimal instances that do not have AnimalX instance. Do you have any idea how can i achieve this? I thought about doing MyAnimal.objects.all().exclude(AnimalX.objects.all()) but it doesnt work. -
How to make a request in the database Django
class A(models.Model): name_A = models.CharField(max_length=200) class B(models.Model): name_B = models.IntegerField() relate_a = models.ManyToManyField(A) class C(models.Model): name_C = models.CharField(max_length=100) relate_b = models.ManyToManyField(A) We have name_C from C and name_B from B. How to make a queryset that gets name_A from tables C and B, and compare them. -
How to use HTML date type with Django and HTMX
I am trying to get date from a picker and trigger an hx-get when the date is changed. The code below produces and text input field with a datepicker pop up. When I pop up the datepicker and change the date, the hx-get is not triggered. If I then click in the text input area the hx-get is triggered with the picked date. So how do I get the trigger to activate when I select the date from the picker? I tried both the TextInput and DAteInput widgets but they both act the same way. I played a bit with django-bootstrap-datepicker-plus but found it did not work well with my forms which use both HTMX and Crispy forms helper layouts. Thanks datedue = forms.DateField(initial=timezone.now().date(), label="On or before", widget=forms.TextInput(attrs={'type': 'date', 'hx-get': reverse_lazy('change-priority'), 'hx-target': '#tasklist', 'hx-include': '[name="priority"], [name="status"],[name="assigned"], [name="iscomplete"]', 'hx-trigger': 'click change' }) ) -
Django-Tenant Application using Cpanel
I have devloped a Django-Tenant Application with Postgresql and is ready for deployment. could not find much info about deploying a Django-Tenant Application. confused and stuck at this point. Want to know if it is possible to deploy on Cpanel hosting with postgres support and Shared Hosting Plans. If so how? Second, does Heroku support Django-Tenant Application with Postgresql. any suggestions please. -
Django QA forms with sections
I am stuck and I try to explain to you what I am trying to accomplish. I am creating an application to create, organize and respond to operational checklists. I have a structure like: checklist -> section -> question -> answer type -> answer Each question can have a different and configurable answer type, for example: the fire extinguisher is in the correct place: Yes / No what state is the main switch in: On / Off I have create models/views/forms for managing and sorting "checklist -> section -> question -> answer type -> answer" and it works. Here is the model.py class Checklist(models.Model): class Meta: verbose_name = "Checklist" verbose_name_plural = "Checklists" name = models.CharField(max_length=64) Description = models.CharField(max_length=64) def __str__(self): return self.name class Section(OrderedModel): class Meta: ordering = ('order',) verbose_name = “Section” verbose_name_plural = “Sections” name = models.CharField(max_length=64) description = models.CharField(max_length=64) checklist = models.ForeignKey( Checklist, on_delete=models.CASCADE, blank=True, null=True, default=None, related_name=‘section_rel') def __str__(self): if self.checklist: return self.checklist.name + " - " + self.name else: return self.name class AnswersValue(models.Model): class Meta: verbose_name = "Answers Value" verbose_name_plural = "Answers Values” name = models.CharField(max_length=16, unique=True) value = models.CharField(max_length=16, unique=True) def __str__(self): return self.name class AnswerType(models.Model): class Meta: verbose_name = "Answer Type" verbose_name_plural = "Answer … -
How to make keyword field in django model
I'm trying to have my django model automatically create a slug of the model name, but I get this error: AttributeError: 'str' object has no attribute 'slugify' This is my code: from django.db import models from django.utils.text import slugify class school (models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=750) location = models.CharField(max_length=19, choices=location_choices) picture = models.URLField(max_length=200, default="https://i.ibb.co/0MZ5mFt/download.jpg") slug = models.SlugField(unique=True, default=name.slugify(), editable=False) -
image.url returns twice https
I just implemented s3 bucket and all the static assets work fine but when I try to get a file I get the following link https://https//mybucket.s3.eu-central-1.amazonaws.com/static/media/thumbnails/Northern_Lights-1.jpeg What is the problem? settings.py AWS_ACCESS_KEY_ID = AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY AWS_STORAGE_BUCKET_NAME = AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_S3_CUSTOM_DOMAIN = 'https://mybucket.s3.eu-central-1.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATIC_URL = 'https://mybucket.s3.eu-central-1.amazonaws.com/static/' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') STATIC_ROOT = os.path.join(BASE_DIR, 'static/') -
How to convert a List of objects to a queryset in Django
I've used chain from itertools to join more than a single queryset into 1 list. but after that when I try to use the generated list. it fails with the error : AttributeError: 'list' object has no attribute 'all' Here is how I do this : def formfield_for_foreignkey(self, db_field, request, **kwargs): parent = self.get_parent_object_from_request(request) home_team_object = parent.home_team away_team_object = parent.away_team if db_field.name == "team": kwargs["queryset"] = Team.objects.filter( Q(away_team_team=parent) | Q(home_team_team=parent)) if db_field.name == "player": parent = self.get_parent_object_from_request(request) print(parent) away_team_players = away_team_object.players.all() home_team_players = home_team_object.players.all() cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id)) result_list = list(chain(away_team_players, home_team_players, cap_objects)) print(result_list) kwargs["queryset"] = result_list if db_field.name == "assistant": parent = self.get_parent_object_from_request(request) print(parent) away_team_players = away_team_object.players.all() home_team_players = home_team_object.players.all() cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id)) result_list = list(chain(away_team_players, home_team_players, cap_objects)) print(result_list) kwargs["queryset"] =result_list return super().formfield_for_foreignkey(db_field, request, **kwargs) Here is where I tried to call 3 different querysets from the same Model than tried to merge them into 1 query set : away_team_players = away_team_object.players.all() home_team_players = home_team_object.players.all() cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id)) result_list = list(chain(away_team_players, home_team_players, cap_objects)) -
How to setup frontail with Django and Docker
I am trying to setup Frontail to access the logs for a Django application deployed using Docker locally. Has anyone done this before? There is very little documentation or other information online. -
Django Admin Configure Column ConfigurableColumnsMixin Display list
By making ConfigurableColumnsMixin I can display all the columns by default i can view all the column. How not to make the columns as default , so that usercan select which column hecan select and then display those coulmns. admin.py class ProductAdmin( TimestampedModelAdminMixin, ConfigurableColumnsMixin, admin.ModelAdmin ): list_display = [ "id", "comment", "active", ] -
How can I load css and js files faster and does storing these files in your media directory affect load time?
So I have a django app and I'm hosting it on heroku, everything works fine.I am storing the images(for now) in my media directory Same for js and css file, however they're going to be there forever but i don't know if thats a good practise, should i host it somewhere online also. Also how can i load css and js faster (get the resources).I have a function that add a load screen so the website gets to load all resources but whenever the files arent loaded it the function is basically useless since it's in the js file and for some reason this problem mostly occurs when i open the website through a mobile browser Here is the code for the function, although i don't think its needed: base.js const loader = document.querySelector(".loader"); document.addEventListener('readystatechange', function checkResources(){ let socials = document.getElementById("nav-socials"); alert(`readystate: ${document.readyState}`); if(document.readyState == "complete"){ //remove a social nav sinces it also has a z-index:100 and will still be seen socials.style.display = "block" alert("page ready, remve") return loader.classList.add("hidden") }else{ loader.classList.remove("hidden") socials.style.display = "none"; } }); Note: i have a base template which is used in almost all the pages. Here is how my django template server the css and … -
I'm trying to view a file I uploaded django FileField but it's not work
Hi friends I got stuck in problem while trying to view a pdf file in my page which I uploaded have this models: class HomeWork(models.Model): nameFile = models.CharField('Name File',max_length=30) file = models.FileField('File',upload_to="files",null=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE, null=True) i make this field because i want to upload pdf files. file = models.FileField('File',upload_to="files",null=True) in the settings.py i make this: MEDIA_ROOT = BASE_DIR / 'static/upload' MEDIA_URL = "/upload/" here i have the html file that i want to see my upload file Whenever I try to access to: <iframe src="{{hw.file.url}}" frameborder="10"></iframe> it's not show me the pdf. {% block content %} <h1>{{course.name_course}}</h1> {% if user.is_authenticated %} <a href="{% url 'Category:u-f' course.id user.id%}">Upload FILE</a> {% endif %} {% if homeworks %} <div class="row"> {% for hw in homeworks %} <div class="col-md-4"> <br> <div class="card"> {{hw.file}} <iframe src="{{hw.file.url}}" frameborder="10"></iframe> <div class="card-body"> <h4 class="card-title text-center"> <a class="Course" href=""><b>{{hw.nameFile}}</b></a></h4> <h5 class="card-title"></h5> </div> <div class="col text-center"> </div> <br> </div> </div> {% endfor %} </div> {% endif %} {% endblock content %} here some photo how its look like in html But whenever I make that line: <iframe src="{{hw.file.url}}" frameborder="10"></iframe> to static like that: <iframe src="{% static 'upload/files/avl_fib_proof.pdf' %}" frameborder="10"></iframe> It looks like this: -
how to add menu item in side list in django with jazzmin?
I added one menu item in django admin panel.when i clicked that, all othe app and their model disappears.I am using jazzmin in admin panel.How to send all side menu list in my template? -
Table Data with sort, search query, pagination pass to different component in Angular
I will try to explain as simple as possible. There is a table which in start gets first 30 rows of n rows and has sorting, search using mat-table. So even if it is sorted only the first 30 rows will be sent and when the user goes to next page it gets the next 30 rows from backend each time making a new request. Now each row has a button that will take it to another component which will get some detailed data about the specific row. This component has a previous and next feature that will get the detailed view of the next or previous row data in the same order that is displayed in the table(sorted, search Result, page number). Currently the table rows are made again in backend(Django) with all the sort, search and other parameters then find the current row and send the next and previous row (will take minimum 5 hits on DB). Hence it very slow. In Frontend I can only pass the data of only that page, which will have problem in next or previous page. How to properly tackle this... -
sign vs sign_object in Django
Who can explain me the difference between .sign() and .sign_object() in Django Signer class? (from django.core.signing import Signer) I know what the .sign() method do in Django 3. Is .sign_object() a new method in Django 4? Is these same signer = Signer() signer.sign('My string') signer = Signer() signer.sign_objects('My string')