Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filer : specifying the path for the image filer field
I'm using django-filer. All works fine, but it generates a random folder and filename. I want to specify the path by myself. It will be something like this: class ExampleModel(models.Model): image = FilerImageField(null=True, blank=True, on_delete=models.CASCADE, upload_to="myimage/") I know it's not possible to add "upload_to", but is there any method that similar to this? I have read the documentation (https://django-filer.readthedocs.io/en/latest/settings.html#filer-storages), but still do not understand how to do that. Thanks. -
facing problems with 'if' statement for Django templates and Django Models
I have been working on a price comparison site but I am facing a problem when I try to write a if statement for different products so they show their own details rather than showing all detail fields in every product. views.py from django.shortcuts import render, get_object_or_404 from .models import Category, Product, Brand, Smartphone_detail def index(request): products = Product.objects.all() return render(request, 'core/home.html', {'products': products}) def categories(request): return { 'categories': Category.objects.all() } def product_detail(request, slug): product = get_object_or_404(Product, slug=slug, in_stock=True) return render(request, 'core/products/detail.html', {'product': product}) def category_list(request, category_slug): category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) return render(request, 'core/products/category.html', {'category': category, 'products': products}) models.py from django.db import models from django.urls import reverse from django.db.models import Case, Value, When class Category(models.Model): name = models.CharField(max_length=120, verbose_name='category name') slug = models.SlugField(max_length=150, verbose_name='category url') class Meta: verbose_name_plural = 'categories' def get_absolute_url(self): return reverse("core:category_list", args={self.slug}) def __str__(self): return self.name class Brand(models.Model): name = models.CharField(max_length=120, verbose_name='name of the brand') slug = models.SlugField(max_length=120, verbose_name='brand url') image = models.ImageField(upload_to='images/', verbose_name='brand image') description = models.TextField(verbose_name='brand moto or tagline') class Meta: verbose_name_plural = 'brands' def __str__(self): return self.name class Smartphone_detail(models.Model): name = models.CharField(max_length=220, verbose_name=("product name")) brand = models.CharField(max_length=120, verbose_name=("product brand")) ram = models.IntegerField(verbose_name=("ram")) storage = models.IntegerField(verbose_name=("storage")) camera = models.CharField(verbose_name=("camera"), max_length=150) processor = … -
SerializerMethodField not showing all fields of serializer when no FK relationship exists
Desired result I have a nested API response as shown below: { "subject": { "name": "math", "teacher": <uuid>, "teacher_name": "John" }, "grade": 1, } teacher_name is a custom field which uses teacher. It works when subject and grade is set. But when the FK subject is null, I get this response Unwanted result { "subject": { "name": "", "teacher": null, }, "grade": 1, } Question: I would want teacher_name to also appear. I have tried setting it up as a serializers.CharField teacher_name= serializers.CharField( source="teacher.name", read_only=True, allow_blank=True, default=None, ) and a serializers.SerializerMethodField teacher_name= serializers.SerializerMethodField() def get_subject_teacher(self, obj): return obj.teacher.name But to no success. Here is my serializer for the nested API class StudentSerializer(serializers.ModelSerializer): subject = serializers.SerializerMethodField() def get_subject(self, obj): filtered_obj = getattr(obj, "subject", None) return SubjectSerializer(filtered_obj).data class Meta: model = Student fields = ( "subject", "grade", ) class SubjectSerializer(serializers.ModelSerializer): teacher_name= serializers.CharField( source="teacher.name", read_only=True, allow_blank=True, default=None, ) class Meta: model = Subject fields = ( "name", "teacher", "teacher_name", ) -
Get the specific value of filter in Django
I know this is common to ask but I wondered if is there's any way to convert the object value to specific value like Integer , The out put of the filtered query is card_tbl object (1) but I want to get the specific value of this which is 1 cardId = 1 card_tbl = card_tbl.objects.get(id=cardId) print(card_tbl) The Print returns instead of specific value example. 1 card_tbl object (1) Then my second question is there any way to Query the object to another table like this? cardId = 1 card_tbl = card_tbl.objects.get(id=cardId) cat1 = category1_tbl.objects.get(id=card_tbl) Thanks in advance! -
Using Google Tag Manager for Django Sites
I'm running a django site. However, when I use the preview in Google Tag Manager, it does not connect to the server. I need help from other people running the Django site. The preview page exposes the following message. "Could not connect to aaa.com" "A timeout occurred while attempting to connect to https://aaa.com/" And the opened preview page exposes the following message. "Tag Assistant Not Connected error" "Could not connect to Tag Assistant" -
django_auth_adfs: get JWT token for the client on successful authentication
I have a Django application that doesn't have MVC pages and most of the data is served/posted via restful API powered by django-rest-framework. My userbase is in Azure single tenant AD, so I am trying to get the SSO going for them. I am using django_auth_adfs to authenticate users against the Azure AD. Most of the stuff seems to work and the module takes care of the redirects and establishing the Django sessions for the client. Specifying the right permission_classes for the API ViewSets will make sure only authenticated users can access it it works fine via browser with proper django session cookie. What I can't figure out is how to get the JWT token that I can give the UI client so that it could interact with the django-rest-framework API by supplying the JWT bearer and not relying on the session. The documentation is not very specific on these details (besides the password grant that isn't quite relevant for my scenario). -
After applying Auto scale, fail to get object from django restframework model
I deploying Django Restframework API using Github to Azure app service. One of my view get object from django model and show it as json format. It worked well before applying Auto scale. Since my app service uses a lot of CPU, I applied Auto scale. After that it seems my view returned empty json sometimes even though there are records in model. Anyone know why it is happening and how to fix it? -
DRF - Serializers = I want json data for my Parent Child Relationship, How?
I want to create a TreeMenu in my react component so I am using this parent-child relationship - model.py class ProductCategory(models.Model): parent = models.ForeignKey(to='ProductCategory', blank=True, null=True, related_name="sub_cats", on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=False, null=False) desc = models.TextField(blank=True, null=True, db_column='description') def __str__(self): return self.name serializers.py class ParentCategorySerializer(ModelSerializer): parent = serializers.PrimaryKeyRelatedField(required=False, read_only=False, queryset=ProductCategory._default_manager.all()) sub_cats = SubCategorySerializer(many=True, required=False, read_only=False) class Meta: model = ProductCategory fields = ('id', 'parent', 'name', 'desc', 'sub_cats') getting my data as [ { "id":1, "parent":null, "name":"Electronics", "desc":"All kinds of electronics items comes in this category", "sub_cats": [ { "id":2, "name":"Mobiles", "desc":"Category for Smartphones, Features-Phone, etc.", "parent":1 }, { "id":3, "name":"Laptops", "desc":"Category for different - 2 types of laptops.", "parent":1 } ] }, { "id":2, "parent":1, "name":"Mobiles", "desc":"Category for Smartphones, Features-Phone, etc.", "sub_cats":[] }, { "id":3, "parent":1, "name":"Laptops", "desc":"Category for different - 2 types of laptops.", "sub_cats":[] } ] How can i make it better or what need to be done to make a tree menu? -
How do i use Task Errors exponential backoff in django-background-tasks?
I was trying out django-background-tasks on one of my projects and I have a case where I would like to retry a function if it throws an error after an hour. The documentation has details about Task error and using exponential backoff. But I am not sure how and where to provide it. Task errors Documentation -
Cannot access User last_name, first_name attributes through foreign key
Not sure what I am doing wrong here. I basically want to show the last_name and first_name from auth.User. Here is the model: class StudentItem(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT) last_updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, related_name="+", null=True) In the template, I am trying to reference the last_name as follows: {{student_item_details.created_by.last_name}} {{student_item_details.created_by}} works just fine which shows the username. I would rather not go through the exercise of overriding str on User or creating a custom User model if this is an easy fix. Thank you. -
Websockets, React + Django
I'm curious if there's a definitive answer on using Websockets, React and Django. From what I've read (1) the preferred way to link React with Django is to use Django Rest Framework (DRF.) (2) The preferred way to leverage websockets in Django, it would seem is through Django Channels. (3) And the preferred way to use websockets in React is through Socket.io. So it seems that linking all three is rather difficult. I see two possible solutions, which neither might be valid. React uses Socket.io and passes communicates w/ the backend via DRF. React is rendered through a Django template and websockets are leveraged via Channels. I imagine that #2 is the path with more headaches as Django is very opinionated framework. Is there a definitive answer on how Websockets, React and Django should be used together? (This question got virtually no traction.) Edit Less preferred option 3: Use React, Node & Express for most of the application, including websockets and DRF solely for the things that python really shines (ex ML pipelines.) -
Django Database Routers
I have set up routers in my django project, but the tables do not seem to be populating in any of the databases. Each time I run 'python manage.py makemigrations HealthcareProject4' I can see that the migration file is being created successfully. However when I run 'python manage.py migrate --database=default nothing appears to populate in any of the databases I have set up. db_routers.py from HealthcareProject4.settings import DATABASE_ROUTERS from HealthcareProject4.Conditions.models import * class AuthRouter: route_app_labels = ['auth', 'contenttypes', 'admin',] def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return model._meta.app_label return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == app_label return None class EducationRouter: route_app_labels = ['EducationProject'] def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return model._meta.app_label return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == app_label … -
Django - Using multiple databases for single project
I'm working on a booking system with the Django framework. Requirements are that i need to create two projects (the Website and an admin site for staff on-boarding and booking system management). I want to use SQLite3 for session details and other Django required tables/data and use a MySQL database to link the to projects together. Basically I want to be able to set available dates for booking via Admin site, which then will be able to be shown on the Website for people to be able to make the booking. I have tried multiple different ways to do this, but nothing seems to be working for me. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'theRock_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'theRock', 'USER': '<Database Username>', 'PASSWORD': '<Database User Password>', 'HOST': '<Database Host>', 'PORT': '<Database Port>', } } DATABASE_ROUTERS = ['routers.db_routers.theRockRouter',] db_routers.py class theRockRouter: route_app_labels = ['theRockAdminAccounts',] def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'theRock_db' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'theRock_db' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): … -
How to write regular expressions in JavaScript
I am using Django formset to enter values in multiple forms on one page. The 'date' field uses the 'datetimepicker' jquery, but the datetimepicker is not applied separately to each 'date' field of the 3 forms. In my opinion, each input has a unique name, so I need to create a regular expression using it. What do I need to fix? $( ".date" ).datetimepicker({ format: 'Y-m-d H:i' }); <input type="text" name="form-0-date" id="date" autocomplete="off" class="form-control col-sm-12 date"> <input type="text" name="form-1-date" id="id_form-1-date" autocomplete="off" class="form-control col-sm-12 date"> -
Django - unit test AssertionError: 302 != 200, decorator problem
I'm trying to write tests for my django app. The tests are failing because I'm getting 302 errors. For CBV I used have a decorator.py file that checks that the user is_teacher. I believe that this is what is causing the problem. view @method_decorator([login_required, teacher_required], name='dispatch') class ClassroomList(ListView): model = Classroom def get_queryset(self): return Classroom.objects.filter(user=self.request.user).order_by('classroom_name') model class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) def __str__(self): return self.username test.py class GradebookTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='tester', email='tester@email.com', password='tester123' ) self.user.is_active = True self.user.is_teacher = True def test_classroomgradebook(self): self.client.login(username='tester', password='tester123') response = self.client.get(reverse('gradebook:gradebookstart')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Choose the gradebook') self.assertNotContains(response, 'Enter') self.assertTemplateUsed(response, 'gradebook/classroom_list.html') decorator.py def teacher_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_teacher, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator If I remove the @method_decorator... from the view, the test passes. -
I can't find this error AttributeError at /register/ 'function' object has no attribute '_meta'
I'm not sure what does it mean by 'function' object has no attribute'_meta' error in my code if I try to click the register page it throws this error. On the other hand, it should create a new user. I think I have missed something and I can't seem to figure out what was that thing. Thank you Blockquote views.py from asyncio import tasks from dataclasses import field, fields from http.client import HTTPResponse from multiprocessing import context from pyexpat import model from re import template from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView from django.urls import reverse_lazy from base.models import Task from .models import Task from django.contrib.auth.views import LoginView from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login from django.contrib.auth.mixins import LoginRequiredMixin class CustomLoginView(LoginView): template_name ='base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('task') class RegisterPage(FormView): template_name = 'base/register.html' form_class =UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('task') def form_valid(self, form): user = form.save if user is not None: login (self.request, user) return super(RegisterPage, self).form_valid(form) class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) context['count'] = context['tasks'].filter(complete=False).count() return context class … -
project wit React, Rest API with python, Sql database
I have a project for school and they want me to create schedule app with: React as Frontend Rest API with python(i chose django rest framework) SQL database (i chose SQLite as default of django) But i have no idea to how to connect them to each other, i am all open to new ideas please help me. My main question is; Do i have to use fetch method to get the data in react or just django functions Thank you. -
Django: Transfer group permissions from one database to another
I have customized groups with custom permissions on my development server via the Django admin. I would like to transfer/migrate these groups along with their permissions to a production server. How would you suggest completing this task? Example of a group I would like to transfer it to production with these specific permissions -
Django aggregate sum of manytomany is adding up everything in its field instead of the ones selected
2 Classes involved in question class Appointment and class Service appointmentApp.models class Service class Service(models.Model): service_name = models.CharField(max_length=15, blank=False) service_time = models.IntegerField(blank=False) def __str__(self): return self.service_name class Meta: verbose_name_plural = "Services" appointmentApp/models.py class Appointment class Appointment(models.Model): service_chosen = models.ManyToManyField(Service, blank=False) total_time = models.IntegerField(blank=False, null=False, default=0) #will add up the amount of time needed for each service def save(self, *args, **kwargs): self.total_time += Service.objects.all().aggregate(total_time=Sum('service_time'))['total_time'] super(Appointment, self).save(*args, **kwargs) def __str__(self): return self.client_dog_name Services are chosen through a multiplechoice field and on save the service_chosen's service_time are added up but what my save function is doing instead is adding up all the existing service.service_time instead of the ones selected, why is this happening? -
Can I use React.js to create a presentation tool?
I'm trying to create a simple web tool that displays a moving object to 2 browsers/users at the same time. It also needs to allow User A to control the moving object (speed, direction). Any changes User A makes should be reflected in both User A's and User B's browser. Can I accomplish this with JavaScript and the React library? Or would I be better or using a framework like Angular? Or perhaps Python/Django? -
selecting some form inputs and show it to the user
I want to be able to select only required fields and show it to my frontend, this is the html template. {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> <div class="row"> <div class="col-6"> {{ field }} </div> </div> {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} I did something like {{ field.first_name }} but this does not show first name form input but if I use {{ field }} all the fields are shown up even the ones I don't want the user to see. How can I select only the fields I want to return to the user? -
Issues With Python Request using django
Am trying to Consume an API by sending a post request This is my code below def sendpostrequest(request): form = RechargeForm (request.POST or None) if form.is_valid(): mobile_number = form.cleaned_data['mobile_number'] amount = form.cleaned_data['amount'] network_id = form.cleaned_data['network_id'] plan_id = form.cleaned_data['plan_id '] if request.method == "POST": url = "https://exampleapi/api/topup/" payload = "{\"network\": network_id,\n\"mobile_number\": \"09037346247\",\n\"plan\":plan_id}" headers = {'Authorization': 'Token s66666vbbbbbbbb5c891fe9e7bbe3f9a0a8742d','Content-Type': 'application/json'} response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) info = response.json() info['mobile_number'] = mobile_number info['network_id'] = network_id info['amount'] = amount return render(request, 'data_api_recharge_successful.html', { 'info':info, 'mobile_number':mobile_number, 'network_id':network_id ,}) ERROR status_code = 400( The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing). error = response.text error = {"non_field_errors":["Invalid data. Expected a dictionary, but got str."]} . Error Clarification After this request is been sent i got Status Code=400 when i do status_code = response.status_code and response.text gave me {"non_field_errors":["Invalid data. Expected a dictionary, but got str."]} . status_code = response.status_code Request For Help Can someone Help me fix this because am very sure am doing something wrong to be … -
How can I call field level validation methods defined on both child and parent serializers?
I have a scenario where I have 3 serializers that each have a set of the same fields, as well as their associated serializer.validate_field methods: class Serializer1(serializers.Serializer): same_field_1 = serializers.BooleanField() same_field_2 = serializers.BooleanField() ... validate_field_1() validate_field_2() ... class Serializer2(serializers.Serializer): same_field_1 = serializers.BooleanField() same_field_2 = serializers.BooleanField() ... validate_field_1() validate_field_2() ... class Serializer3(serializers.Serializer): same_field_1 = serializers.BooleanField() same_field_2 = serializers.BooleanField() ... validate_field_1() validate_field_2() ... NOTE: each class contains other fields and validate methods that aren't shared with the other serializers as well. I would like to bring the common fields and validate methods up into a parent class, then have each of these child classes inherit from that parent class. The issue then becomes, how do I run the validation defined on the child and the parent? I don't see any specific documentation discussing how we can run the is_valid() cycle on the parent class as well as the child class. -
Django: custom Action with date parameter not working
I have the following code in Python Django: @action(detail=True, methods=['get'], url_path=r'by_date') def get_meal_by_date(self, request, meal_date=date.today): print(meal_date) meals_by_date = Meal.objects.filter( owner=self.request.user, mealTimestamp__day=meal_date.day, mealTimestamp__month=meal_date.month, mealTimestamp__year=meal_date.year ) serializer = self.get_serializer(meals_by_date, many=True) return Response(serializer.data, status=status.HTTP_200_OK) That Code works on call it like this: http://localhost:8000/meals/by_date/ My problem is how can I enrich the method to gets data back with date parameter. For example with this call: http://localhost:8000/meals/by_date/2022-03-16T21:30:45.290Z/ -
Django CBV use Values from Modelform to Calculate other Model Fields
I am trying to make a warehouse management system with Django 3.2 based on this models: class itemtype(models.Model): item_id = models.IntegerField(primary_key=True) item_name = models.CharField(max_length=100) group_name = models.CharField(max_length=100) category_name = models.CharField(max_length=100) mass = models.FloatField() volume = models.FloatField() used_in_storage = models.BooleanField(default=False, null=True) class Meta: indexes = [ models.Index(fields=['item_id']) ] def __str__(self): return '{}, {}'.format(self.item_id, self.item_name) class material_storage(models.Model): storage_id = models.AutoField(primary_key=True) material = models.ForeignKey(itemtype, on_delete=models.PROTECT) amount_total = models.IntegerField(null=True) price_avg = models.FloatField(null=True) order_amount = models.IntegerField(null=True) order_price = models.IntegerField(null=True) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return '{}, {} avg.: {} ISK'.format(self.material, self.amount, self.price) "itemtype" defines basically the possible objects which could be stored and "material_storage" shows what is in stock. I tried to combine the total amount of every item as well as the average price paid for it and the amount and price for a single order in the same database row. The idea is to get the last record for the chosen item/material when a new order happens, add the amount of that order and recalculate the avg price. Theoretically this could be split up on two tables, but I don't see a reason to do so at the moment. However, I am not able to figure out the actual function code to do …