Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to style Django forms according to html theme
Here is the scenario iam trying style default django select form field as my html select field. But the output is different how can fix this. This is how i need my output This is what iam getting Html code <select class="selectpicker" data-live-search="true" data-width="100%"> <option>Select</option> <option data-tokens="Convertible">Convertible</option> <option data-tokens="Coupe">Coupe</option> <option data-tokens="Hatchback">Hatchback</option> <option data-tokens="Sedan">Sedan</option> <option data-tokens="SUV">SUV</option> </select> My Django form code fromPlace = forms.ModelChoiceField(queryset=Place.objects.order_by('name'),widget=forms. Select(attrs={'class': 'selectpicker'})) -
Django select_related()
i have a problem with my Queryset. class Category(models.Model): name = models.CharField(max_length=50, unique=True) class Outlay(models.Model): category = models.ForeignKey( Category, models.PROTECT, related_name='outlay_set', null=True, blank=True) name = models.CharField(max_length=50) price= models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) I tried to get from Category model price for the every category using relations with ForeignKey. I've created this : queryset = Outlay.objects.all().prefetch_related('category') and get: <QuerySet [<Outlay: 2022-10-03 Forage 175.00>, <Outlay: 2022-10-03 Wodka 232.00>]> Mayby someon will help me how i can pull out only prices?? -
How you manage the output values is a string in django
In my Django backend db, results are stored in result column, and result itself looks like this: result = [ {"pod_name": "kafka-9", "resolution_ms": 60000,"value": 420.85}, {"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0}, ... ] When I do the get_results from the filter results = DjangoCeleryResultsTaskresult.objects.filter(task_id=taskname).values('result') just_res = list(results)[0].values() just_res is a dictionary values, dict_values(['[{"pod_name": "kafka-9", "resolution_ms": 60000, "value": 420.85}, {"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0}]']) However, I want my just_res is a list of nested dictionary, like it is stored in db. I tried: service_results = list(just_res)[0] but this only convert me a string, and convert that string to a list is another nightmare, cannot just use list() method. Can you help me figure out either? convert the values of string(just_res) into a list? or A way to pull django results as a list from db? In all, not sure why django filter objects values(), I can only get results as a string, not the original datatype. Am I using it wrong or another other approach? Thanks! -
Change URL for wagtail blog index page
I currently have a website where the home page at www.mysite.com is the wagtail blog index page I wish to move the blogindex page to another url I can easily have a different homepage by amending my urls.py file: #original path("", include(wagtail_urls)) #new path( "", TemplateView.as_view(template_name="pages/newhomepage.html"), name="newhomepage", ), However I would like the blogindex page available at e.g. myste.com/blog but I am not sure how to go about this. Adding the following to urls.py does not do it path("blog/", include(wagtail_urls)) -
Python & Django: Cannot Retrieve Defaults From 2 Layer Deep Foreign Key Relationship
I found this trick, which might be a hack, to set default values when the field is a foreign key to another database: class House(models.Model): name = models.CharField(max_length=100, unique=True) address = models.CharField(max_length=300, null=True, blank=True) def __str__(self): return name @classmethod def get_default(cls): return cls.objects.filter(address="5360 Wallaby Lane").first().pk class Meta: ordering = ["name"] When constructing another class that references this field, we can set a default as follows: class Neighborhood(models.Model): favourite_house = models.ForeignKey("civilization.House", on_delete=models.PROTECT, default=House.get_default()) name = models.CharField(max_length=100, unique=True) @classmethod def get_default(cls): return cls.objects.filter(name="Upper Snootington").first().pk This works fine. As long as this function referencing a second layer isn't called by another default field for a table, Django doesn't complain. Once I tie this in as a default to another model, however: class City(models.Model): favourite_neighborhood = models.ForeignKey("civilization.Neighborhood", on_delete=models.PROTECT, default=Neighborhood.get_default()) Django throws exceptions "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.". It seems this is pretty specific to that second layer of default retrieval. The best I can surmise is that Django is trying to interact with the models while it builds the models with that second layer referencing another model. Something tells me this is a hack and there's a better way... -
Custom permission not working Django/REST
from rest_framework import permissions class UserButEmailVerified(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return True def has_object_permission(self, request, view): if request.user.email_is_verified: return True return False == Persmission class from .permissions import UserButEmailVerified @api_view(["POST"]) @permission_classes([UserButEmailVerified]) def sendMessage(request): print(request.user.email_is_verified,"emai") == also gets called even if email_is_verified returns False=? I got the feeling that UserButEmailVerified isnt called at all, print statements are not getting executed, if I try to login unauthorized at all, I do not get access.... I know i could achive this without the permission class, but I want to learn it, so what am I doing wrong? -
Error when running custom manage.py command
I'm building a multitenant app based on this page https://www.section.io/engineering-education/implement-multitenancy-with-multiple-databases-in-django/#use-middlewares-for-tenant-specific-database-routing. It asks to create a custom manage.py (named myapp_manage.py) to create a superuser, so that way i can point the database that i want to run the command like this: python myapp_manage.py databasename createsuperuser --database=databasename Everything was ok, i could run the command without problems, but now, when i try to run it, it gives me an error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't understand why this error is showing because the environment in custom manage.py is configured exactly like the standard manage.py. Custom manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys from myapp.middleware import set_db_for_router if __name__ == "__main__": """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'al_project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc # new from django.db import connection args = sys.argv db = args[1] with connection.cursor() as cursor: set_db_for_router(db) del args[1] execute_from_command_line(args) Standard manage.py: … -
Server-Side Data table Error Due to URL Length
I'm currently working on a django project that uses server-side data tables. When I try to generate a table with less than 18 columns, it would work. However, when I choose to have more than 18 columns in my table, I get the error 404 - File or directory not found. I think this may be due to the length of the URL. Just to give an idea, the URL generated for 31 columns contains over 1K characters. I would appreciate some insight on what I could change to resolve this problem. Below is a part of my code for the data table: var table = $('#example').DataTable( { "initComplete": function(settings, json) { table.buttons().container().appendTo( $('div.column.is-half', table.table().container()).eq(0)); }, scrollX: true, scrollY: "500px", lengthChange: false, pageLength:5000, buttons: [ 'excel'], serverSide: true, sAjaxSource: "(insert address here)" }) -
How to pass variables between class based Views in Django?
I've created url-shorter service using Django. For creating short link i use CreateView: class LinkCreate(CreateView): form_class = CreateLink template_name = "index.html" success_url = reverse_lazy('users_links') def form_valid(self, form): if self.request.user.is_authenticated: form.instance.creator = self.request.user self.link_short = generate_short_link() self.request.session["new_link"] = self.link_short form.instance.link_short = self.link_short return super().form_valid(form) # Showing last 5 shorted links on the page def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_list'] = URL.objects.all().order_by('-id')[:5] return context After creating new link user is redirected to page "users_links" where he should see new shotred link. For this reason in template i use something like that: {% if request.session.new_link %} <div> Your new link: request.session.new_link </div> {% endif %} The problem is user see that 'div' all the time till the end of session. I think this is wrong decision to using session variables in this case, but i don't know how to pass variable between views in another way. I'm newbie in Django, can you please give me advice how to do it in the right way? -
Django queryset does not return for repeated value
payments_modes=Payment.objects.filter(content_type=content_type,content_id__in=content_id).values_list('payment_mode',flat=True) order_ids = payments_modes.filter().values_list('content_id',flat=True) ledger_name = Order.objects.filter(id__in=order_ids,seller=user.company,status__in = [ORDER_STATUSES.DELIVERED,ORDER_STATUSES.COMPLETED]).values_list('buyer__name',flat=True) -
Django does not log in custom superuser with correct password and username [closed]
I know this is a recurrent question but my case is pretty weird. I am working with a partner and on his laptop (with Linux) everything is going well. However, I tried to run the same code two times: one on Windows and the other one on Archlinux and in both of them I am not able to log in with the correct username and password. The superuser was created with 'python manage.py createsuperuser' the there weren't errors in the console. Superuser with its password (hashed) is correctly written in PostgreSQL database, so I suspect that the problem is in the reading or with the desencryptation. I copy below the relevant parts of models.py and admin.py. #models.py class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): values = [email] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise … -
Modelling complex django model relations efficiently
I am programming a django website for oragnizing events where I need to be able to store information about which attendees will stay for meals. I have currently got it working in a way which I think is really not optimal, and I would like to improve it. I would be glad to hear any ideas about how you would go about it. What I need So, for each event (which can have a duration of a variable number of days) I need to be able to display what I call a meals table. This table will hold information about each day's meals. Each day has three meals (breakfast, lunch and dinner). Each meal needs to contain information about the number of people that are staying for that meal plus the dish that each of those people are going to have from the menu. The menu also contains a variable number of dishes that can be modified by the administrator of that event (the menu is the same for every meal). So, the general concept diagram would be something like this: Event |_ Meal Table |_ Day 1 |_ Breakfast \_ Dish 1 -> Nº of people \_ Dish 2 … -
Auth Management with Django Rest Framework, Next.JS and?
I want to get my head down into a small community website using Django Rest Framework as a backend and Next.JS as a frontend. I am struggling with the authentication module. What is best practice? I thought about using Firebase as an auth provider but the implementation is quite hard - or at least I could not find good documentation. I am now thinking of using the Djoser library to have django handle all authentication and user management. My question is: What would you recommend to use? The official DRF website has a ton of third-party packages on this topic but I just can decide which one to use (https://www.django-rest-framework.org/api-guide/authentication/#third-party-packages) Thank you -
Type object 'Book' has no attribute 'objects'
I am getting error AttributeError: type object 'Book' has no attribute 'objects' while running my django project. Models.py from django.db import models # Create your models here. """Create or Save Model Instance. """ class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title) return book """Book Model""" class Book(models.Model): title = models.CharField(max_length=100, verbose_name="Book_Title") """Str Display. """ def __str__(self): return self.title """To Save Model Instance. """ object = BookManager() views.py from django.views import View from .models import Book from django.http import HttpResponse # Create your views here. """Default View """ class default_view(View): def get(self, request): queryset=Book.objects.all() return HttpResponse(queryset) def post(self, request): # Getting Value of title title = request.POST.get('title') """Creating Book Instance. """ book = Book(title=title) book.save() return HttpResponse('saved') Error Internal Server Error: /model_instance Traceback (most recent call last): File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\lib\site- packages\django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Model\category\Model_Instance\Instance_method\views.py", line 9, in get queryset=Book.objects.all() AttributeError: type object 'Book' has no attribute 'objects' [04/Oct/2022 19:36:17] "GET /model_instance HTTP/1.1" … -
Is there a way to dynamically annotate value from JSONField using another annotation in Django?
What I have is a following annotation: member_qs = RoomMember.objects.filter(room_id=OuterRef('id'), ...) qs = Room.objects.annotate( person_role=Case( When(Exists(member_qs), then=Subquery(member_qs.values_list('role', flat=True))), default=Value(request.user.global_role) ), person_permissions=Case( When(Q(person_role='creator'), then=F('role_permissions__creator')), When(Q(person_role='moderator'), then=F('role_permissions__moderator')), When(Q(person_role='member'), then=F('role_permissions__member')), When(Q(person_role='authenticated'), then=F('role_permissions__authenticated')), default=F('role_permissions__anonymous') ), can_chat=F('person_permissions__chat_send'), can_add_videos=F('person_permissions__queue_extend'), ) ... where role_permissions is a JSONField in this form: {"role_name": {"permission_name": true|false}} This works but results in an ugly and very slow SQL. What I want is to simplify annotation of person_permissions or get rid of it completely, but I can't use person_role directly because F is hard-coded. -
IntelliJ python debugger `ModuleNotFoundError: No module named 'logging.handlers'; 'logging' is not a package`
While using IntelliJ with python I cannot make the debugger work while testing because it always appear: ModuleNotFoundError: No module named 'logging.handlers'; 'logging' is not a package Checking the Traceback I encountered the problem shown in the image below but I do not know if it really points in some direction to solve the issue: I tried installing logging separately without any effect. On the other hand logging works perfectly in the python console. -
Infinate migration for an intact model
util class UploadTo: def __init__(self, folder, filename_suffix=""): self.folder = folder self.filename_suffix = filename_suffix def _get_filename(self, instance, filename): _, file_extension = os.path.splitext(filename) result = str(instance.a_uuid) if self.filename_suffix: result += "-{}".format(self.filename_suffix) result += file_extension return result def save_path(self, instance, filename): tmp_filename = self._get_filename(instance, filename) result = "{}/{}".format(self.folder.value, tmp_filename) return result model class Sound(UuidMixin, PhraseMixin, CommentMixin): british_sound = models.FileField(blank=True, null=False, default="", upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_SOUND_FOLDER, filename_suffix="british").save_path) american_sound = models.FileField(blank=True, null=False, default="", upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_SOUND_FOLDER, filename_suffix="american").save_path) Message Migrations for 'vocabulary_sounds': vocabulary_sounds/migrations/0009_alter_sound_american_sound_alter_sound_british_sound.py - Alter field american_sound on sound - Alter field british_sound on sound Migration class Migration(migrations.Migration): dependencies = [ ('vocabulary_sounds', '0008_alter_sound_american_sound_alter_sound_british_sound'), ] operations = [ migrations.AlterField( model_name='sound', name='american_sound', field=models.FileField(blank=True, default='', upload_to=general.model_aux.UploadTo.save_path), ), migrations.AlterField( model_name='sound', name='british_sound', field=models.FileField(blank=True, default='', upload_to=general.model_aux.UploadTo.save_path), ), ] Copy Snippet Edit Snippet Wordwrap class Sound(UuidMixin, PhraseMixin, CommentMixin): british_sound = models.FileField(blank=True, null=False, default="", upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_SOUND_FOLDER, filename_suffix="british").save_path) american_sound = models.FileField(blank=True, null=False, default="", upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_SOUND_FOLDER, filename_suffix="american").save_path) Migrations for 'vocabulary_sounds': vocabulary_sounds/migrations/0009_alter_sound_american_sound_alter_sound_british_sound.py - Alter field american_sound on sound - Alter field british_sound on sound class Migration(migrations.Migration): dependencies = [ ('vocabulary_sounds', '0008_alter_sound_american_sound_alter_sound_british_sound'), ] operations = [ migrations.AlterField( model_name='sound', name='american_sound', field=models.FileField(blank=True, default='', upload_to=general.model_aux.UploadTo.save_path), ), migrations.AlterField( model_name='sound', name='british_sound', field=models.FileField(blank=True, default='', upload_to=general.model_aux.UploadTo.save_path), ), ] Whenever I carry out makemigrations, … -
"detail": "Authentication credentials were not provided." when I want to signup user
when I want to post data and create a new teacher it gives me this error and I don't know what to do please help me this is my models.py this is my views.py this is my serializer.py -
Django all auth create userprofile with signup form
I am trying to create a user profile. The database row gets created, also the ID is correct (one-to-one relation). All other data is not being stored. For example: The counter_announcements_approved cell is always filled with NULL, instead of 222. Why is that? class CustomSignupImmobilienbetreiber(SignupForm): first_name = d_forms.CharField(max_length=128, required=True, label="Vornamen") last_name = d_forms.CharField(max_length=128, required=True, label="Nachnamen") company_name = d_forms.CharField(max_length=128, required=True, label="Firma/Unternehmen") telephone_number = d_forms.CharField(max_length=128, required=True, label="Telefonnr.") street = d_forms.CharField(max_length=128, required=True, label="Straße") city = d_forms.CharField(max_length=128, required=True, label="Stadt") state = d_forms.ChoiceField(choices=STATE_CHOICES, label="Bundesstaat", required=True) gewerbeanmeldung = d_forms.FileField() def custom_signup(self, request, user): #profile, created = Immobilienbetreiber.objects.get_or_create(user=user) user.user_type = 1 user.is_active = 0 user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.company_name = self.cleaned_data['company_name'] user.telephone_number = self.cleaned_data['telephone_number'] user.street = self.cleaned_data['street'] user.city = self.cleaned_data['city'] user.state = self.cleaned_data['state'] profile = user.immobilienbetreiber_profile profile.gewerbeanmeldung = self.cleaned_data['gewerbeanmeldung'] profile.counter_announcements_approved = 222 user.save() profile.save() return user -
Django - Using a complex query
I've read almost all of the related questions and still can't figure out how to execute the following query in Django. Using the Django standard tables for Auth I've added a group called 'approvers'. I need to query to return all approvers. In SQLite designer I developed the following sql: select auth_user.email, auth_user.first_name, auth_user.last_name from auth_user, auth_user_groups where auth_user.id = auth_user_groups.user_id and auth_user_groups.group_id in ( select auth_group.id from auth_group where auth_group.name = "approvers") It seems that I should be able to do this by using the raw method on the models, but would like to understand how to use the Django ORM to access this if it's a better more acceptable approach. -
Django signals @receiver POST_SAVE not working on PROD (ok on DEV)
Getting nuts ... On dev, my signals (for sending an alert by mail) works for all save (create + update) and delete. But on prod, only delete action sends an email. I didn't notice at once delete signals were working so I spent much time looking for an issue caused by firewall (blocked email outgoing). Post Save @receiver(post_save, sender=Navette) def alerte(sender, instance, created, **kwargs): ref = instance.ref user = instance.user.username if created: alert(pour=['tintin@gmail.com'], sujet=f'Nouvelle navette pour la référence {ref} créé par {user}') else: alert(pour=['tintin@gmail.com'], sujet=f'Mise à jour de la navette pour la référence {ref} par {user}') Post Delete @receiver(post_delete, sender=Navette) def alerte(sender, instance, **kwargs): ref = instance.ref user = instance.user alert(pour=['tintin@gmail.com'], sujet=f'La navette pour la référence {ref} a été supprimée par {user}') just for info : alert.py def alert(**kwargs): #ref = kwargs.get('ref', 'noref') de = kwargs.get('de', 'toto@gmail.com') pour = kwargs.get('pour', 'tintin@gmail.com') sujet = kwargs.get('sujet', 'Sujet Général') contenu = kwargs.get('contenu', 'cf. objet du mail') fichier = kwargs.get('fichier', '') host = 'smtp.gmail.com' port = 465 user = settings.EMAIL_HOST_USER passw = settings.EMAIL_HOST_PASSWORD msg = EmailMessage() msg['Subject'] = sujet msg['From'] = de msg['To'] = pour msg.set_content('HTML uniquement') msg.add_alternative(contenu, subtype='html') with smtplib.SMTP_SSL(host, port) as smtp: smtp.login(user, passw) smtp.send_message(msg) As said almost everywhere, I declared my … -
PyCharm: Django templates don't seem to be working?
I am trying to use Django in PyCharm, but the Django templates are not working. For example {% block %} elements and {{variable}} references are not treated specially and when I view the page preview, it just displays it as text? -
How to get product count from parent in django rest framework
a'm new in django, I have one model like this class Category(models.Model): title = models.CharField(max_length=200) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') Parent - foods subparent - Italian food, French food and other pizaa, Polenta, Lasagna Parent - drinks subparent - juice, alkohol water, tea, leamon tea Can i count in serializer foods count - 3 drinks count - 4 -
How to compare and validate form values before sending in Django Admin?
In my admin panel, users can edit a dropdown to set values for one or more lines before saving the changes. When 2 or more lines are edited at once, I would like to check if the values set by the user are coherent. Here is an example. These two rows should not have 2 different values. I have tried overriding the clean() methods in the model but I need to validate the data before this is triggered, preferably right after the form is sent. Is this possible? Official Django Documentation mostly describes data validation form in the model, but this would not allow me to compare rows between them. -
How can I deal with the Problem while the Tutorial of Django
I'm trying to make a code for administraion with Django. But unfortunatley it doesn't work well like what the tutorial said. Here is the code that I used from django.contrib import admin from .models import Question admin.site.register(Question) and the errormesseage shows and also here is the datalist in my labtop can someone please give me any advice, how can I fix this problem? thank you