Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Storing a users name after clicking on a link to display
I'm building a ticketing system using the django framework. Whenever a ticket is filled out and submitted, the support group will go into the support app and see the information on what ticket number, customer name, summary, date created, etc. The ticket number is a link to the details of that ticket. What I would like to do is, whenever a user clicks that link, the ticket is automatically assigned to that user. This helps keeps users from being able to pick and choose which tickets they want to do. The way I have it now is whoever updates the ticket to change the status of the ticket, that person is assigned. I feel my options here with django are limited so if you've got any JS ideas, please feel free to share. -
Display fields based on the request in django-rest-framework serializer
I have a Post model in my Django project. I want to display description field when the user receives the list of posts, and when he receives a post instance, display the body field instead. (Both fields exist separately in the model) here is my Post serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'title', 'image', 'description', 'slug'] lookup_field = 'slug' this is my view: class posts(viewsets.ModelViewSet): queryset = Post.published.all() serializer_class = PostSerializer lookup_field = 'slug' I want when the user gets the posts list in /posts/ url, see something like this: [ { "id": 31, "title": "hello-world", "image": { ... }, "description": "post description", "slug": "hello-world" }, ... ] and when get a post instance, see something like this with additional body field and exclude the description field: { "id": 31, "title": "hello-world", "image": { ... }, "body": "post body ...", "slug": "hello-world" } -
raise OSError('No translation files found for default language %s.' % settings.LANGUAGE_CODE) Ubuntu Django
I've created another language (IN-te) on Django application, it is working perfectly fine on my dev machine (MacOS) but when I host it to Ubuntu server, it is giving me following error raise OSError('No translation files found for default language %s.' % settings.LANGUAGE_CODE) OSError: No translation files found for default language IN-te. I have local folder with all necessary files what might be issue here? -
Django - query more than one row returned by a subquery used as an expression error
I have a query and I need to add field using annotate Employees.objects.filter( /* filtering here */ ).annotate( group_ids=Subquery( EmployeesGroups.objects.distinct() .select_related("groups") .values_list("id", flat="True") ) ) I get the next error : Django query more than one row returned by a subquery used as an expression. When I print result of subquery it is something like this: <Queryset [10, 55]> How can I fix this problem? -
Can't change built-in template Django admin
I want to add a button next to the table, by clicking on which a new url will open. I have already written the function itself, but the problem is that I can not make this button. I looked at many answers on this forum, tried many options, but could not solve my problem. My project struct: python_backend ├── cms | └──admin.py | ├── templates | └── cms | └──csv_upload.html | └──emaillisttosends | └──change_list.html └──main_settings └──settings.py My csv_upload.html code: {% extends "admin/change_list.html" %} {% load static %} {% block content %} <a href="upload-csv/">Upload a csv file</a> {{ block.super }} {% endblock %} I want to see this: But i have this: -
Django get manytomany from classbasedview got <QuerySet []>
I need the Lehrer and Gl Lehrer retrieved from Schulverzeichnis, so that Lehrer and GL Lehrer are from their corresponding Schulverzeichnis, any idea ? class Dashboard (LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all() context['BedarfsBerechnung'] = Bedarfs_und_BesetzungsberechnungTabelle.objects.all() context['JahrgangGebunden'] = JahrgangsgebundenTabelle.objects.all() context['JahrgangUebergreifend'] = JahrgangsuebergreifendTabelle.objects.all() context['FoerderBedarf'] = FoerderbedarfschuelerTabelle.objects.all() context['VorbereitungsKlassen'] = VorbereitungsklassenTabelle.objects.all() context['EinzelIntergration'] = EinzelintegrationTabelle.objects.all() context['SonderPaedagogen'] = SonderpaedagogenbedarfTabelle.objects.all() context['Lehrer'] = LehrerTabelle.objects.all() context['GL_Lehrer'] = GL_LehrerTabelle.objects.all() return context template renders this <QuerySet []> {% for Ansicht in Schulverzeichnis.Lehrer_FK.all %} <li>{{ Ansicht }}</li> {% endfor %} -
Django post_save won't add to ManyToMany Field
I've got these models, and I want to fill an instance of Reporte after it gets saved certain data related to the dates. In the post_save it access the sales made between the dates passed and then it adds them to manytomany field in Reporte but I can't save them to a Reporte instance and I don't understand why class Venta(models.Model): repuesto = models.ForeignKey(Repuestos, models.CASCADE) cantidad = models.IntegerField() fecha_venta = models.DateField() total = models.FloatField(null=True, blank=True) def __str__(self): return f'{self.repuesto} - {self.cantidad} - {self.fecha_venta}' class Reporte(models.Model): fecha_inicio = models.DateField() fecha_fin = models.DateField() ventas = models.ManyToManyField(Venta, null=True, blank=True) estado_de_cuenta = models.FloatField(null=True, blank=True) costo_de_inventario = models.FloatField(null=True, blank=True) deficit_de_productos = models.CharField(max_length=100, null=True, blank=True) @receiver(post_save, sender=Reporte) def guarda_venta(sender, instance, created, **kwargs): if created: vent = Venta.objects.all() ventas_delta = vent.filter(fecha_venta__range=[instance.fecha_inicio, instance.fecha_fin]) instance.ventas.set(ventas_delta) instance.save() Anyone knows what am I doing wrong? -
Django is not imported
I cant understand why is this thing working like that. It can do runserver, but cant do collectstatic, how can i fix it?(I am deploying it) g -
python manage.py collectstatic error: cannot find rest_framework bootstrap.min.css.map (from book 'Django for APIs')
I am reading the book 'Django for APIs' from 'William S. Vincent' (current edition for Django 4.0) In chapter 4, I cannot run successfully the command python manage.py collectstatic. I get the following error: Traceback (most recent call last): File "/Users/my_name/Projects/django/django_for_apis/library/manage.py", line 22, in <module> main() File "/Users/my_name/Projects/django/django_for_apis/library/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 154, in collect raise processed whitenoise.storage.MissingFileError: The file 'rest_framework/css/bootstrap.min.css.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x102fa07f0>. The CSS file 'rest_framework/css/bootstrap.min.css' references a file which could not be found: rest_framework/css/bootstrap.min.css.map Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. I have the exact same settings like in the book in settings.py: STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] # new STATIC_ROOT = BASE_DIR / "staticfiles" # new STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" # new I couldn't find any explanation for it. maybe someone can point me in the right direction. -
ValueError: unable to configure handler 'loggers'
I was writing code in vscode that logs user activity(logins and logouts) using signals on my django website but it keeps showing this error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 565, in configure handler = self.configure_handler(handlers[name]) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 723, in configure_handler klass = self.resolve(cname) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 383, in resolve name = s.split('.') AttributeError: 'NoneType' object has no attribute 'split' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\log.py", line 76, in configure_logging logging_config_func(logging_settings) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 810, in dictConfig dictConfigClass(config).configure() File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 572, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'loggers' The code i was writing was LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(filename)s:%(lineno)s] %(message)s", 'datefmt': "%Y/%b/%d … -
Does Django have a way for ModelViewSet to represent both parent and child models?
I need to have extra fields in response if they are available, but not all objects of that class have this property. So for example we have class Car(models.Model): brand = model.CharField() wheelcount = model.IntField() class Truck(Car): max_load = model.IntField() class Bus(Car): max_people = model.IntField() and a view class CarView(ReadOnlyModelViewSet): serializer_class = CarSerializer queryset = Car.objects.all() Is there a way to either write CarSerializer to somehow serialize child objects differently, or a way to make view class choose a serializer based on class or additional field(like having an enum CarType)? -
Python: create a decorator that combines several others [duplicate]
Imagine we write in Django: @decorator1(p1, p11) @decorator2(p2, p22) @decorator3(p3, p33) def view(request): pass What should be written so I could use: @combined_decorator def view(request): pass And the effect would be the same? I tried: @decorator1(p1, p11) @decorator2(p2, p22) @decorator3(p3, p33) def combined_decorator(view): return view But it didn't work -
Please see the terminal and how to resolve it
Error _ Django I am not able to figure out the error. -
django.db.utils.OperationalError: (1050, "Table ' ' already exists")
I am trying to setup a new project. It has migrations already. I created a new mysql database but while doing migrate I get error like django.db.utils.OperationalError: (1050, "Table ' ' already exists"). Why is that error occurred inside a completely new database ? But the default django app like admin, auth etc. migrated without an issue. DATABASES = { "default": { "ENGINE": "django.db.backends.mysql" "NAME":"mydb", "USER": "myuser", "PASSWORD": "my pwd", "HOST": "localhost", "PORT":3306, "OPTIONS": {"init_command": "SET sql_mode='STRICT_TRANS_TABLES'"}, } } -
Django Heroku Deployment Process
i'am deploying a website built with Django Framework into Heroku and when i try to push my code into the remote after ihad created a Heroku remote with the fallowing command "heroku git:remote -a app-name", after i use "git push heroku master" it return to me this error : === Fetching app code =!= Build failed due to an error: =!= validate step: error converting YAML to JSON: yaml: line 12: could not find expected ':' If this persists, please contact us at https://help.heroku.com/. someone can help me? Thank you! -
Django disable csrf for admin
I need to disable csrf for all admin paths. If I try to import in urls.py from django.views.decorators.csrf import csrf_exempt and then urlpatterns += [path(admin_url, admin.site.urls)] then when I go to admin I get an error TypeError at /core/admin/ 'tuple' object is not callable how to fix it? -
Is there a way to update top level relationship in Django form?
I have below models and form. Brand > Section > Category > Article. I can pull the existing data out of the database however I have hit a wall. I am trying to create a new article or update an existing article but I'm not sure how I can update the brand, then the Section. The Category I can update and it is connected directly to the Article model. I have been thinking about this for a few days now and tried different models but ultimately i can't think of the best way to connect the models and have them update in the model. class Brand(models.Model): def brand_image(instance, filename): return 'uploads/brand/{0}/{1}'.format(instance.title, filename) title = models.CharField(max_length=50, unique=True, blank=True, null=True) image = models.ImageField(upload_to=brand_image, null=True, blank=True) slug = AutoSlugField(populate_from='title', unique_with='title', blank=True, null=True) my_order = models.PositiveIntegerField(default=0, blank=False, null=False) class Meta: ordering = ['my_order'] def __str__(self): return self.title or '' def get_absolute_url(self): return reverse('brand-list', kwargs={'brand_slug': self.slug}) class Section(models.Model): title = models.CharField(max_length=50,unique=True, blank=True,null=True) slug = AutoSlugField(populate_from='title', unique_with='title',blank=True,null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='section', blank=False, null=False) my_order = models.PositiveIntegerField(default=0, blank=False, null=False) class Meta: ordering = ['my_order'] def __str__(self): return self.title or '' def get_absolute_url(self): return reverse('section-list', kwargs={'section_slug': self.slug}) class Category(models.Model): title = models.CharField(max_length=50, blank=True,null=True) slug = AutoSlugField(populate_from='title', unique_with='title',blank=True,null=True) … -
Authentication credentials were not provided - Django REST
I am making IOS app with Django backend, it was working well, but now im getting error {"detail":"Authentication credentials were not provided."} Django Backend settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), } views.py class ColorTagViewSet(viewsets.ModelViewSet): queryset = ColorTag.objects.all() serializer_class = ColorTagSerializer permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) urls.py (in my app) router = routers.DefaultRouter() router.register(r'colortag', views.ColorTagViewSet) urlpatterns = [ path('', include(router.urls)), path('auth/get-token', rest_views.obtain_auth_token), ] Test IOS App ViewController.swift class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("requesting") guard let url = URL(string: "http://192.168.0.171:8000/api/v1/colortag") else { print("URL Error") return } let token = "6a02d8d41a8cf143522a587bcee4be2c8b7d75e5" var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("Token \(token)", forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in print(String(data: data!, encoding: .utf8)) }.resume() } } I also tried using basic auth, that also didnt work usually i dont ask people on Stackoverflow(or any other forums, google is enough), but i have no idea what to do. Can anyone tell me what is the possible reason of facing this error? -
How to use compiled webpack files on local server
I use python manage.py runserver for django and webpack-dev-server --mode=development for template on local development. Now I was ready for deployment on server, so I did webpack --mode=production, It created the dist directory.... then,,,How can I use this ? Just accessing localhost (manage.py runserver) but no templates appears. -
Django annotation does not group output as intended
The following is my model: class Project(models.Model): name = models.CharField(max_length=1000, null=True, blank=True) date_created = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1000, null=True, blank=True) The status field has about 5 different options (Won, Lost, Open, Pending, Cancelled). I need to know how to get the number of projects with x status in each month in a given time range query. I was able to get the correct data shape using the following annotation- but for some reason, the output given delivers an object for every found status within a month. For instance, if there is at least 1 "Won" and 1 "Open" project found in the same month, two separate objects will return for the same month. Additionally, the status options here are hard-coded and would need to be modified if a new status was added. queryset = list(opps.annotate( month=TruncMonth('date_created'), ).values('month').annotate( total=Count('id'), Win=Count('id', filter=Q(status='Win')), Loss=Count('id', filter=Q(status='Loss')), Open=Count('id', filter=Q(status='Open')), Dormant=Count('id', filter=Q(status='Dormant')), Pending=Count('id', filter=Q(status='Pending')), Cancelled=Count('id', filter=Q(status='Cancelled')), )) Here's a sample of my current output. [{'month': datetime.datetime(2022, 5, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'total': 1, 'Win': 0, 'Loss': 1, 'Open': 0, 'Dormant': 0, 'Pending': 0, 'Cancelled': 0} {'month': datetime.datetime(2022, 5, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'total': 1, 'Win': 0, 'Loss': 1, 'Open': 0, 'Dormant': 0, 'Pending': 0, 'Cancelled': 0} … -
Why is my for loop not working in django?
I'm new to Django and I tried to load data into my template using for loop ended up getting the for loop tags written on my template. Views.py from django.shortcuts import render from django.http import HttpResponse from projet.models import Employe # Create your views here. def page(request) : employe = Employe.objects.all() return render(request,'hello.html',{'employe':employe}) Html table template <table class="table"> <tr class="tr"> <th>ID</th> <th>Nom et Prenom</th> <th>Lundi</th> <th>Mardi</th> <th>Mercredi</th> <th>Jeudi</th> <th>Vendredi</th> <th>Samedi</th> <th>Dimanche</th> </tr> { % for i in employe % } <tr> <td>{{ forloop.counter }}</td> <td>{{ i.name }}</td> <td>{{ i.monday }}</td> <td>{{ i.tuesday }}</td> <td>{{ i.wednesday }}</td> <td>{{ i.thursday }}</td> <td>{{ i.friday }}</td> <td>{{ i.saturday }}</td> <td>{{ i.sunday }}</td> </tr> { % endfor % } </table> -
How to find any Django classes' import path
I feel really dumb having to ask this question, but I often find a class I want to use in Django and have a tough time figuring out what its import path is. I end up clicking google result after google result until someone happens to include its path in a question, answer, or comment. Sometimes it's easy and other times it's tough. For example, I was investigating an exception I was seeing about atomic transactions in my unit tests and I learned about a class I wanted to try called TransactionTestCase. My first stop was the Django documentation on the class. You would think that the first thing in the documentation on that class would be where it lives and how to import it, but it's not in the documentation on that page about that class. What does everyone else do? Does there exist a 1-step reliable means of looking up any class's import path? Or does everyone just know it by inference or from reading the paragraphs of documentation and meandering through links in the documentation or use a heuristic by chopping up and searching on components of the camelcase name? What am I missing here? I'm sure … -
Django MultipleChoiceField
I have problem with dynamically executing code for django model with python function exec. My method: def _manage_record(self, record=None, order=None): """Dynamically exec allowed operations to many to many relationship.""" allowed = ("add", "remove") if order is None: raise ValueError("Order for _manage_record can't be None value.") if record is None: raise ValueError("Record to manage can't be None value") if record.__class__ is not self.model: raise ValueError("Record have to be " + str(self.model) + " instance.") if order in allowed: string = "self.partner." + self.relation_name + "." + order + "(record)" exec(string) else: raise Exception("Order " + order + " not allowed.") if i print that string and directly copy it and pass to exec function it will execute properly, but with that string created dynamically nothing happen. Any help? -
filtering objects based on boolean field state
I'm working on a project where a form is filled out. And in that form you have the is_active fields. If the user selects True, it means the account is active and if it is False, it means it is no longer active, and the user can no longer see it. Through the filters I'm trying to present only the forms with the is_active True, but I'm not able to. Follow one of my attempts in my views: class BookingViewSet(viewsets.ModelViewSet): serializer_class = BookingSerializer #queryset = Booking.objects.all() #queryset = Booking.objects.filter(is_active="True") #filter_backends = (filters.DjangoFilterBackend,) #filterset_class = BookingFilter #filterset_fields = ['is_active'] def get_queryset(self): queryset = Booking.objects.all() username = self.request.query_params.get('bookings') if username is not None: queryset = queryset.filter(is_active__username=username) return queryset -
MailInaBox config issue (from expiringdict import ExpiringDict)
So i recently upgraded my mailinabox installation and after that when I try to start the mailinabox service I get this error on the console File "/root/mailinabox/management/auth.py", from expiringdict import ExpiringDict ModuleNotFoundError: No module named 'expiringdict' I have tried and installed the modules manually using pip but it just doesn't work