Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to buffer exception objects with its traceback to be inspected later
I have a user submitted data validation interface for a scientific site in django, and I want the user to be able to submit files of scientific data that will aid them in resolving simple problems with their data before they're allowed to make a formal submission (to reduce workload on the curators who actually load the data into our database). The validation interface re-uses the loading code, which is good for code re-use. It has a "validate mode" that doesn't change the database. Everything is in an atomic transaction block and it gets rolled back in any case when it runs in validate mode. I'm in the middle of a refactor to alleviate a problem. The problem is that the user has to submit the files multiple times, each time, getting the next error. So I've been refining the code to be able to "buffer" the exceptions in an array and only really stop if any error makes further processing impossible. So far, it's working great. Since unexpected errors are expected in this interface (because the data is complex and lab users are continually finding new ways to screw up the data), I am catching and buffering any exception … -
ERR_CONNECTION_TIMED_OUT error is returned in the site after deploing a Django application to Heroku
I just re-deployed an application in the new Eco Dyno and provisioning a new PostgreSQL datbase, however after deploying successfully, when I try to open the application, this HTTP error is returned ERR_CONNECTION_TIMED_OUT and the application never opens. I also updated the stack from heroku-20 to heroku-22 and it is not working on both. Is there any additional configuration that I need to complete? This is the log from the latest deploy 2023-01-30T22:13:55.000000+00:00 app[api]: Build started by user farmacia@aselsi.org 2023-01-30T22:14:32.846408+00:00 app[api]: Deploy c6f350bc by user farmacia@aselsi.org 2023-01-30T22:14:32.846408+00:00 app[api]: Release v23 created by user farmacia@aselsi.org 2023-01-30T22:14:33.126404+00:00 heroku[web.1]: Restarting 2023-01-30T22:14:33.141734+00:00 heroku[web.1]: State changed from up to starting 2023-01-30T22:14:34.066230+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2023-01-30T22:14:34.109732+00:00 app[web.1]: [2023-01-30 22:14:34 +0000] [4] [INFO] Handling signal: term 2023-01-30T22:14:34.109979+00:00 app[web.1]: [2023-01-30 22:14:34 +0000] [9] [INFO] Worker exiting (pid: 9) 2023-01-30T22:14:34.110205+00:00 app[web.1]: [2023-01-30 22:14:34 +0000] [10] [INFO] Worker exiting (pid: 10) 2023-01-30T22:14:34.310286+00:00 app[web.1]: [2023-01-30 22:14:34 +0000] [4] [INFO] Shutting down: Master 2023-01-30T22:14:34.461478+00:00 heroku[web.1]: Process exited with status 0 2023-01-30T22:14:35.372879+00:00 heroku[web.1]: Starting process with command `gunicorn aselsi.wsgi` 2023-01-30T22:14:36.441571+00:00 app[web.1]: [2023-01-30 22:14:36 +0000] [4] [INFO] Starting gunicorn 20.1.0 2023-01-30T22:14:36.441910+00:00 app[web.1]: [2023-01-30 22:14:36 +0000] [4] [INFO] Listening at: http://0.0.0.0:54892 (4) 2023-01-30T22:14:36.441956+00:00 app[web.1]: [2023-01-30 22:14:36 +0000] [4] [INFO] Using worker: sync … -
Django rest framework unsupported media type with image upload
this is my first time trying to upload image to django rest framework, i am using svelte for my front end and using the fetch api for requests. i am have an error that i cannot solve. all requests containing images return an unsupported media type error. Back End i have added these line to my settings.py # Actual directory user files go to MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'mediafiles') # URL used to access the media MEDIA_URL = '/media/' my simplified views.py @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) @parser_classes([FormParser, MultiPartParser]) def products(request): if request.method == 'POST' and isPermitted(request.user, 'allow_edit_inventory'): serializer = ProductSerializer(data=request.data) serializer.initial_data['user'] = request.user.pk if serializer.is_valid(): serializer.save() return Response({'message': "product added"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my urls.py from django.contrib import admin from django.urls import path, include from rest_framework.authtoken import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include("API.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and finally my models.py def product_images_upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class Product(models.Model): name = models.CharField(max_length=200) image_url = models.ImageField(upload_to=product_images_upload_to, blank=True, null=True) Front End my file upload component in svelte, the exported image variable is what get used in the request in the following code. export let avatar, fileinput, image; const onFileSelected = (e) => { image … -
Django Admin: search_fields with an optional null value
I have a Django Admin model as such. class ImportedItemAdmin(admin.ModelAdmin): autocomplete_fields = ["author"] search_fields = ("author__username",) The problem here is that the Author might be nil which causes a 'NoneType' object has no attribute 'username' error. Is there a way to support both nil authors and still search by username? -
File upload using Django framework
I need insights on how to upload a file on click of a save button.I have to upload a file and also capture user selections and save them(user selections) in a file when I click on "save". And then once the file uploaded successfully run button should get enabled and when I click on run button , uploaded file should get processed as per the user inputs. I have created a simple form and a view to upload a file on click of a submit button,but I dont know how to have a save button before submit. My View: def projects_upload(request): print(settings.MEDIA_ROOT) if request.method=='POST': upload_request=UploadFile() upload_request.file=request.FILES['file_upload'] upload_request.save() Form: <form action="uploadProject" method="post" enctype="multipart/form-data"> {% csrf_token%} <input type="file" name="file_upload" id="choose_upload_file" value="" accept=".zip,.rar,.7z,.gz,"></br> <input type="submit" class="btn btn-secondary btn-block" value="upload" id="file_upload1"> </form> -
Django - Postgres connection
I am super beginner, but want to learn super fast building web application. I am right now developing an Income-Expense web app on Django Framework (Python, js and Ajax). I am now stuck with the server and get different errors. Anyone can support me ? ERROR "django.db.utils.OperationalError: connection to server on socket "/tmp/.s.PGSQL.5432" failed: fe_sendauth: no password supplied" I think I shut down everything not properly and when a came back my virtual environment was not working. Thank You Don't know what to try more -
Django CustomUser
I extended default User model as follow: class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length = 100, blank = False) last_name = models.CharField(max_length = 100, blank = False) ... USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'username','password'] Now when creating a new superuser the prompt for password is not hidden $ python manage.py createsuperuser Email address: user1@coolapp.com First name: John Last name: Smith Username: cool_username Password: fancy_p4$$w0rd Superuser created successfully. Is there any way it can be hidden? -
Create model for schema of csv file
I need to create model for schema which consists of name and columns. Users can build the data schema with any number of columns of any type. Each column also has its own name (which will be a column header in the CSV file), type and order (just a number to manage column order). The problem is that I have to create schema at one time with columns, but I don't know how to do this. My current models: SCHEMA_TYPE_CHOICE = ( ('Full Name', 'Full Name'), ('Job', 'Job'), ('Email', 'Email'), ('Company', 'Company'), ('Phone Number', 'Phone Number'), ('Address', 'Address'), ('Date', 'Date'), ) class Schema(models.Model): title = models.CharField(max_length=100, unique=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Column(models.Model): name = models.CharField(max_length=100) type = models.CharField(max_length=100, choices=SCHEMA_TYPE_CHOICE, default='Full Name') order = models.PositiveIntegerField(default=1) schema = models.ForeignKey(Schema, on_delete=models.CASCADE, related_name='column_schema') def __str__(self): return self.name Form that I have to realize: enter image description here -
Best backend language for full stack development
What should I use - Node.js(Javascript) Or Django(Python) , If I want to become a full stack Developer? I'm a beginner in this. So please give suggestion regarding this. -
Django prefilled Admin Tabular Inline
My goal is that the first column of my tabular inline sheet is filled with data from another table. I've attached a screenshot where you can see that for tablename=game I want to insert the game number (eg. 1), the metric (e.g time), the player_names and the values (-> scores) per player. Number and metric applies to the hole game. Each game within Table=Game shall contain number metric player_1:name and score player_2:name and score ... and so on. The player names are stored in a table called players. Is there a way to pre-fill the first row of my tabular inline with my player_names. Otherwise i have to write it down for each game. Django admin panel_tabularInline I've created several models in models.py: class Game(models.Model): player_name = models.CharField(max_length=30) class Game (models.Model): NUMBER = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)) METRIC = ( ('Kills', 'Kills'), ('Time', 'Time'), ('Deaths', 'Deaths') ) number = models.BigIntegerField(default=1, choices=NUMBER) metric = models.CharField(max_length=30, choices=METRIC) class GameItem (models.Model): value = models.CharField(max_length=30) game = models.ForeignKey(Game, on_delete=models.CASCADE) def __str__(self): This is my admin.py file: from django.contrib import admin from .models import * class GameItemInline(admin.TabularInline): model = GameItem extra = 6 #I've got 6 … -
Get jwt token to pass it to unit test
I'm trying to retreive jwt access token to pass it to unit test but everytime I try to get it I receive 'not authorized' error. User is created in database with factory #factories.py class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = "test_user" password = "test123" date_of_birth = "2000-01-22" email = "tests@test.ru" role = "moderator" class AdFactory(factory.django.DjangoModelFactory): class Meta: model = Ad name = "test" author_id = factory.SubFactory(UserFactory) price = 100 description = "None" is_published = "FALSE" category = factory.SubFactory(CategoryFactory) image = None And I', trying to get jwt access token in fixtures.py # fixtures.py import pytest @pytest.fixture @pytest.mark.django_db def user_token_jwt(client): username = "test_user" password = "test123" response = client.post( "/user/token/", {"username": username, "password": password}, format="json" ) print(response.data) return response.data["access"] Finally, the test function itself. Please help me to understand how to retrieve a jwt access token in Django with such project architecture? @pytest.mark.django_db def test_create_ad(client, ad, user_token_jwt): # user_token_jwt = client.post( # "/user/token/", # {"username": "test_user", "password": "test123"}, # content_type="application/json" # ) expected_response = { 'id': ad.pk, 'name': 'test', 'author_id': ad.author_id_id, 'author': ad.username, 'price': 100, 'description': 'None', 'is_published': 'FALSE', 'category_id': ad.category_id, 'image': None } data = { "name": "test", "price": 100, "description": "None", "author_id": ad.author_id, "category": ad.category_id, } response … -
How to show value of Count Function on my template. Django
I would like to show the total number of employees registered in my database. Using the count function. My views.py: def home(request): return render(request, 'dashboard.html') def return_total_employees(request): return_total = Employees.objects.aggregate(total=Count('EmployeeCard'))[ 'total' ] return render(request, 'dashboard.html', {'return': return}) My template: <h1> {{ view.return_total_employees }} </h1> -
check for exact presence in a queryset django, jinja 2
in my case, I have a question to check if the exact string name of a model does exist in a query set. here is my code: views.py: if Despiking.objects.filter(user=request.user).exists(): filtered_projects = Despiking.objects.filter(user=request.user) context.update({ 'filtered_projects': filtered_projects.__str__(), }) template.html: {% if info.project_name in filtered_projects %} <!-- some HTML elements --> {% else %} <!-- other HTML elements --> {% endif %} in my code, there is no difference between "my project" and "project" as info.project_name model. because of that the "project" word exists in the query set when I have only the "my project" in it. so using {% if info.project_name in filtered_projects %} works the same (the condition of if will be True) because that "project" word exists in the query set because of the "my project". what can I do to check the exact string in it? -
Django context isn't passing information to template
I try to pass information to an html template from a view function. Every time I try to call the variable from the html template it doesn't show anything. Here is my configure_peplink.html: {% extends "base_generic.html" %} {% block content %} <h1>Configure Peplink</h1> <p>Configure a Peplink router from the web. This was designed by <em>Valorence LLC</em></p> {% if peplink %} <p>Serial Number: {{ peplink.serial_number }}</p> <p>IP Address: {{ peplink.ip_address }}</p> <p>Mac Address: {{ peplink.mac_address }}</p> <p>Name: {{ peplink.name }}</p> {% else %} <p>No Data Found Off Device</p> {% endif %} {% endblock %} Here is the view function configure_peplink: def configure_peplink(request, peplink): selected_peplink = PeplinkDevice.objects.get(serial_number=peplink) print(selected_peplink.ip_address) print(selected_peplink.serial_number) print(selected_peplink.mac_address) context = { 'peplink': selected_peplink } return render(request, 'configure_peplink.html', context=context) Here is the url line to call the view: re_path(r'^configurepeplink/(?P<peplink>.*)/$', views.configure_peplink, name='configurepeplink') I've tested to make sure that the context has data in it (as seen with the print statements). Even though the context variable has data and is getting past the if statement in the html template it still doesn't display any data. I have tried clearing my cache on the browser and restarting all my services (django, celery, redis-server). Here is a picture of the webpage: -
Django-widget-tweaks Email address can't be entered error
I'm using Django-widget-tweaks. I am getting an error that prevents me from entering my Email address. What is the solution? html {% extends 'app/base.html' %} {% load widget_tweaks %} {% block content %} <div class="card card-auto my-5 mx-auto"> <div class="card-body"> <h5 class="card-title tex-center">ログイン</h5> <form method="post" class="form-auth"> {% csrf_token %} <div class="form-label-group"> {% render_field form.login class='form-control' placeholder='Email' %} </div> <div class="form-label-group"> {% render_field form.password class='form-control' placeholder='Password' %} </div> <div class="buttton mx-auto"> <button class="btn btn-lg btn-primary btn-block mx-auto" type="submit">Login</button> </div> </form> </div> </div> {% endblock %} I can't enter my email address. -
django - overriding save method with super returns unique contraint error when creating object
Overriding save method with super returns unique contraint error when creating object. How to solve it? def save(self, *args, **kwargs): if self.pk is None: super(IntoDocumentProduct, self).save(*args, **kwargs) # some logic # more logic super(IntoDocumentProduct, self).save(*args, **kwargs) self.full_clean() Below is the error that appears in the console. It directs specifically to the save() method in the model. I don't know what is wrong with it. After all, I can't use self.save(), because there will be a recursive loop. Traceback (most recent call last): File "W:\projects\foodgast\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python311\Lib\contextlib.py", line 81, in inner return func(*args, **kwds) ^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\src\wms\api\views.py", line 183, in post serializer.save() File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\serializers.py", line 212, in save self.instance = self.create(validated_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
meal, created = Meal.objects.get_or_create(name=meal_data.get('name', '')) AttributeError: 'str' object has no attribute 'get'
this is django rest_framework api I created this api for restourant. This is menu api . I want to save menu.json's data to my database, but I could not. Can you give any advice to save json data to my models. I got this error: File "C:\Users\OSMAN MERT\Desktop\menu\menu_core\api\models.py", line 36, in store_json_data meal, created = Meal.objects.get_or_create(name=meal_data.get('name', '')) AttributeError: 'str' object has no attribute 'get' How can I solve it? I need your help? models.py from django.db import models import json # Create your models here. class Meal(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) is_vegetarian = models.BooleanField(default=False) is_vegan = models.BooleanField(default=False) class Ingredient(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) groups = models.CharField(max_length=100) class Option(models.Model): id = models.AutoField(primary_key=True) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) name = models.CharField(max_length=100) quality = models.CharField(max_length=100) price = models.FloatField() per_amount = models.CharField(max_length=100) class MealIngredient(models.Model): id = models.AutoField(primary_key=True) meal = models.ForeignKey(Meal, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) path = r"C:\Users\OSMAN MERT\Desktop\menu\menu_core\menu.json" def store_json_data(json_data): for meal_data in json_data: meal, created = Meal.objects.get_or_create(name=meal_data.get('name', '')) if not created: meal.is_vegetarian = meal_data.get('is_vegetarian', False) meal.is_vegan = meal_data.get('is_vegan', False) meal.save() for ingredient_data in meal_data.get('ingredients', []): ingredient, _ = Ingredient.objects.get_or_create(name=ingredient_data.get('name', ''), meal=meal) for option_data in ingredient_data.get('options', []): option, _ = Option.objects.get_or_create(quality=option_data.get('quality', ''), ingredient=ingredient) option.price = option_data.get('price', 0) option.save() def load_json_file(path): … -
i cant run local server. What shoud me do?
Traceback (most recent call last): File "C:\Users\Zet\PycharmProjects\pythonProject1\web\manage.py", line 22, in main() File "C:\Users\Zet\PycharmProjects\pythonProject1\web\manage.py", line 13, in main raise ImportError( 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? Установил django, попробовал запустить локалный сервак, чтобы убедится, что это всё работает. IDE PYcharm. И если, что я новичок. Сразу говорю пытался устанавливать через pip3, удалял всё, и один раз сработало, но потом опять перестало работать. И виртуальное окружение скачивал. -
python-telegram-bot in django application
I’m trying to start python-telegram-bot in a web application with the django framework. To do this, I follow any example from the Telegram library and end up calling the method application.run_polling(). I know it’s not the best option because this blocks my web server, and I want to replace it with a better one, but I can’t find it. According to official documentation, there is a tip that indicates the following: When combining python-telegram-bot with other asyncio based frameworks, using this method is likely not the best choice, as it blocks the event loop until it receives a stop signal as described above. Instead, you can manually call the methods listed below to start and shut down the application and the updater. Keeping the event loop running and listening for a stop signal is then up to you. And then I find the following section: See also initialize(), start(), stop(), shutdown() telegram.ext.Updater.start_polling(), telegram.ext.Updater.stop(), run_webhook() I’ve tried to understand the methods in the list, but I can’t figure out how to run python-telegram-bot in the background and not affect my main server. Are there any links or documents that expand the information or detail the steps to follow in these cases? … -
How to return ordered objects from django CBV(ListView) when you click a button or link in the template
So I'm building an e-commerce store with Django(First project after learning). I need to click on Sort in the template, and have the CBV return an object that's ordered by either, price, or whatever field I specify in the request. This is what I have so far Template Sort by Lowest Price View class ClotheListView(ListView): model = Clothe paginate_by = 8 def get_filter_param(self): # Grab the absolute url and then retrieve the filter param filter_param = self.request.path.split("/")[-1] return filter_param def get_queryset(self): filter_param = self.get_filter_param() if(filter_param != ""): queryset = self.model.objects.filter(cloth_gender=filter_param) else: queryset = self.model.objects.all() return queryset return clothes_filtered_list.qs def get_ordering(self): ordering = self.request.GET.get('ordering', '-cloth_price') return ordering def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context Url.py urlpatterns = [ path('', views.ClotheListView.as_view(), name="clothe_list"), path('<slug:slug>', views.ClotheListView.as_view(), name="clothe_list_category"), path('<int:pk>/', views.ClotheDetailView.as_view(), name="clothe_detail") ] -
Django Form ChoiceField pass parameter for database query
I want to create a Django Form ChoiceField. The choices will be queried from an external database and should be filtered by a parameter {company_id}. How to pass this parameter? views.py if request.method == 'GET': company_id = 1 site_id = 3 return render(request, 'sites/new-column.html', { 'company_id': company_id, 'site_id': site_id, 'form_newcolumn': NewColumn(company_id), }) forms.py class NewColumn(forms.Form): def __init__(self, *args, **kwargs): company_id = kwargs.pop('company_id') super(NewColumn, self).__init__(args, kwargs) self.company_id = company_id # Add it as an instance variable engine = db.engine("Database") connection = engine.raw_connection() cursor = connection.cursor() cursor.execute(f"SELECT * FROM table WHERE id = '{company_id}' ; ") all_rows = cursor.fetchall() choices = forms.ChoiceField( choices=[(row[0], row[1]) for row in all_rows], help_text='Make your Choice' ) How to pass {company_id} to query only the necessary choices? -
7. Add number of expenses per category row in category list
I'm working in Django ORM, I have two classes and 2 forms. I want the values from the queryset from the ExpenseListView(ListView) class to be displayed in the CategoryListView(ListView) class, and then in the category_list.html form from django.contrib.admin import filters from django.db.models import Sum, Count, Max, Q from django.db.models.functions import ExtractYear, ExtractMonth from django.views.generic.list import ListView from . import models from .forms import ExpenseSearchForm from .models import Expense, Category from .reports import summary_per_category class ExpenseListView(ListView): model = Expense paginate_by = 20 # how may items per page def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None else self.object_list form = ExpenseSearchForm(self.request.GET) if form.is_valid(): name = form.cleaned_data.get('name', '').strip() fromdate = form.cleaned_data.get('fromdate', '') todate = form.cleaned_data.get('todate', '') category = form.cleaned_data.get('category', '') order_by = form.cleaned_data.get('order_by', '') sort_descending = form.cleaned_data.get('sort_descending', '') filters = {} if name: filters['name__icontains'] = name if fromdate and todate: filters['date__range'] = [fromdate, todate] if category: filters['category__in'] = category queryset = queryset.filter(**filters) if order_by: if sort_descending: queryset = queryset.order_by(order_by).reverse() else: queryset = queryset.order_by(order_by) total_amount_spent = queryset.aggregate(Sum('amount')) total_summary_per_year_month = queryset.annotate(year=ExtractYear('date'), month=ExtractMonth('date')). \ values('year', 'month').annotate(sum=Sum('amount')).order_by('year', 'month') return super().get_context_data( form=form, object_list=queryset, summary_per_category=summary_per_category(queryset), total_amount_spent=total_amount_spent, total_summary_per_year_month=total_summary_per_year_month, **kwargs ) class CategoryListView(ListView): model = Category paginate_by = 5 How to download data from one … -
Django admin page is missing CSS
I am actually following a youtube tutorial for learning Django and admin site is not showing properly. The admin tab in the video looks like this: My admin tab however looks like this: An answer in stack overflow suggested to put DEBUG = True in settings.py file. But it is already set to that in my case. -
How do i rewrite my code with Routers? Django rest framework
I have this REST API: urlpatterns = [ path('admin/', admin.site.urls), path('users/', UserViewSet.as_view({'get': 'list', 'post': 'create', 'delete': 'delete'})), path('users/<uuid:pk>/video/', UserViewSet.as_view({'post': 'video'})) ] How can i rewrite this with routers? Default router with register method creates API different from current. Or, maybe, in this situation it would be more correct to use my code? -
uwsgi only sending stdout logs to GCP in Kubernetes Engine
I have a django application for which I want to send logs to GCP. Locally, everything works fine using django dev server and Cloud Logging for Python. I see the logs on my GCP dashboard with the right level, I can also see the json structured logs when I use them. It also works well when I'm using gunicorn in a local docker instead of the django dev server. However, as soon as I'm using uwsgi locally, I can't find any trace of my logs in the GCP dashboard. When I deploy my docker image in Kubernetes Engine, all the logs are only displayed as info and they are not json structured anymore. I noticed that the logger name is stdout in my log explorer. I'm supposing that somehow uwsgi don't use my python logging config and only logs to stdout that is automatically sent as info by some internal gcp process. Here's my uwsgi.ini: [uwsgi] chdir=xxx module=xxx http = 0.0.0.0:8080 vacuum = true enable-threads = true listen = 128 # socket-timeout, http-timeout and harakiri are in s socket-timeout = 180 http-timeout = 180 harakiri = 180 harakiri-verbose = true py-autoreload = false processes = 4 memory-report = false master …