Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Operation not permitted error when uploading a file DJango
I have a API based on Django REST working properly over Azure Web Service but it fails when trying to upload a file into the container's mount volume. I´m doing the upload process by a POST request and in my local environment it's works with no trouble. The model I used to upload the file to the DB is this: from app.controllers.users.models import User class QueueJob(models.Model): class Tasks(models.TextChoices): COLLABORATORS_UPDATE = 'CB_UPDATE' WITHDRAWALS_UPDATE = 'WD_UPDATE' EXPATS_UPDATE = 'EP_UPDATE' class Statuses(models.TextChoices): PENDING = 'PENDING' PROCESSING = 'PROCESSING' DONE = 'DONE' FAILED = 'FAILED' user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=20, choices=Tasks.choices, blank=False, null=False) file = models.FileField(upload_to=r'reports/', null=False) extra_data = models.CharField(max_length=1024, blank=False, null=True) execution_comment = models.CharField(max_length=255, blank=False, null=True) status = models.CharField(max_length=20, choices=Statuses.choices, null=False, default=Statuses.PENDING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Queue Job' verbose_name_plural = 'Queue Jobs' ordering = ['created_at'] class QueueJobSerializer(ModelSerializer): class Meta: model = QueueJob exclude = ['id', ] The weird thing is that the file actualy loads up and I can access to it over the volume as you can see here but still failing when it runs the save() method when creating the DB record with the serializer returning the next error: [Errno 1] Operation not … -
What is the difference between permission_classes and authentication_classes in django rest framework generic API Views
I know what permissions and authentication means. Authentication identifies the user and permissions decide what action can be done by the user. I have implemented a token authentication in django rest framework. The problem is when i specify both permission_classes and authentication_classes in ListAPIView i cant log in to the account in browsable page. It only works when i delete authentication classes in the view. The following view doesn't raise any exception, but gives { "detail": "Authentication credentials were not provided." } response. Also not logging in. class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (permissions.IsAdminUser,) authentication_classes = [TokenAuthentication] But after deleting the authentication_classes = [TokenAuthentication] the page works. PS: curl and httpie works without any problem. So what could be the issue here? What is the difference between those two classes? -
Procfile not declared Django Heroku
Procfile not getting delacared Not Declared File Location -
Get the real name of saved file (Model) after upload - Django
I'm trying to get the real name of the uploaded file in Django. It turns out that if a file name already exists inside the Model, the Django will create another name aleatory. For example, if 'abc.xls' is inside the Model database and I try to upload 'abc.xls' again, Django will create a file called 'abc_123456.xls'. That's not the problem! My question is: how can I get this name ('abc_123456.xls') inside my view.py? def index(request): if 'GET' == request.method: form = DocumentForm() return render(request, 'auditoria_app/index.html', {'form': form}) else: form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() # I'd like to get the correct file name here! mediaFolder = settings.MEDIA_ROOT fileName = f"{mediaFolder}/SAE/{form.cleaned_data['file'].get_alternative_name}" # .xlsm (Excel file) splitFileName = fileName.split('.') zipFileName = f"{splitFileName[0]}.zip" # .zip My model: from django.db import models from django.core.validators import FileExtensionValidator class Document(models.Model): file = models.FileField(upload_to='SAE/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.file) -
How to take limited amount of related (many to one ) objects. django
So I have these three models: class Database(models.Model): fields... class DatabaseFieldsToCheck(models.Model): data_base = models.ForeignKey(Database, on_delete=models.CASCADE, related_name="sql_requests_to_check") class DatabaseMonitoring(models.Model): sql_request = models.ForeignKey(DatabaseFieldsToCheck, on_delete=models.DO_NOTHING, related_name="sql_request_results") class Result(models.Model): result = models.ForeignKey(DatabaseMonitoring, on_delete=models.CASCADE, related_name="results") so my relation looks like this database ---many---> DatabaseFieldsToCheck ---many--> DatabaseMonitoring -->result So in my view i want to get for each database only last 10 results. how can i do it? should i try raw sql ? or mby write some data transfer objects ? -
Is it possible to override a SerializerMethodField for an inherited Serializer?
Is it possible to override a SerializerMethodField from an inherited Serializer? E.g. # serializers.py class BaseSerializer(serializers.ModelSerializer): custom = serializers.SerializerMethodField() class Meta: model = Item fields = ["pk", "custom"] def get_custom(self, obj): return "Base"; class ExtendedSerializer(BaseSerializer): custom = serializers.SerializerMethodField() class Meta: model = Item fields = ["pk", "custom"] def get_custom(self, obj): return "Extended"; Obviously the above code doesn't work. I've currently had to create another Serializer and declare a new SerializerMethodField for the inheriting Serializers: # serializers.py class DefaultSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ["pk"] class BaseSerializer(DefaultSerializer): custom = serializers.SerializerMethodField() class Meta: model = Item fields = ["pk", "custom"] def get_custom(self, obj): return "Base"; class ExtendedSerializer(DefaultSerializer): custom = serializers.SerializerMethodField() class Meta: model = Item fields = ["pk", "custom"] def get_custom(self, obj): return "Extended"; But it would be neater for my use case if I could just override an existing SerializerMethodField as in my first code block. -
HTML not linking to CSS file django
I know there are so many questions on this but I'm yet to find a solution. I have the below folder structure for my django app: I then reference the styles.css file from my index.html page, like so: <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> {% load static%} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> but no matter what I change in my css file it doesn't affect my webpage. css file if useful: .form-details { text-align: center; color: Tomato; background-color: red;} -
Count objects in queryset by value in a field. Django
Imagine I have a model which looks something like following: class Car(models.Model): TYPE_CHOICES = [ (1: 'Hatchback') (2: 'Saloon') type = models.CharField(choices=TYPE_CHOICES, ...) color = models.CharField() owner = models.ForeignKey(User, ...) And I want to count objects by specific values. Say black saloons owned by Johns or white hatchbacks owned by Matts. The best what I came up so far is: Car.objects.annotate( black_saloons_owned_by_John=Count( 'type', filter=( Q(type=2) & Q(owner__first_name='John') ) ) ).aggregate( aggregated_black_saloons_owned_by_John=Sum( 'black_saloons_owned_by_John' ) ) Is there a better way to get the desired result? Thanks. -
cPanel: Django Admin Portal not loading Static/CSS files
I'm trying to deploy my Django App on cpanel and the static files for django admin page won't show up but its working fine for the rest of the project. I even tried to run python manage.py collectstatic but it just gives me an error that something's wrong with my manage.py A little help would be appreciated. Thank you! -
Corsheaders in django admin
I'm using django-cors-headers and it's working fine with django rest, but in Django admin doesn't. In Django I've a model: class Animation(models.Model): code = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=500, default='') time = models.DecimalField(default=0.0, max_digits=6, decimal_places=2) animation = models.CharField(max_length=500) The animation field has the URL of a Lottie animation, and in the admin template has: {% if adminform.form.instance.animation %} <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script> <lottie-player id="animationPlayer" src="{{ adminform.form.instance.animation }}" background="transparent" speed="1" style="width: 300px; height: 300px;" loop controls autoplay> </lottie-player> {% endif %} I'm having CORS problems inside django admin because the admin is in https://example.com/admin and the animation in https://static.example.com/animation.json -
How can I add placeholders to Djangos default authentication form's input fields (username and password)?
So I use Django's built-in authentication form for the user login. How can I adjust this form so I will have placeholder attributes for the html input objects? <form method="post" action="."> {% csrf_token %} <div class="email-wrapper field-wrapper"> <div class="input">{{ form.username }}</div> </div> <div class="password-wrapper field-wrapper"> <div class="input">{{ form.password }}</div> </div> <button class="login-button" type="submit">Log in</button> </form> path('login/', views.LoginView.as_view(template_name='userprofile/login.html'), name="login"), Couldn't find any example in the official docu. However, it states authentication_form: A callable (typically a form class) to use for authentication. Defaults to AuthenticationForm. So do I have to define an entire new form? -
add group into AbstractUser
I use AbstractUser to verify email and it success but I have problem with adding groups inside class customuser class CustomUser(AbstractUser): is_email_verified=models.BooleanField(default=False) so how i can add group inside that class -
How do i implement real time consultation on my app?
Within the past few days, i have learnt how to connect django and react to create a full stack application, the problem is that all the coding tutorials ive seen dont handle real time applications. seeing as my app is an online doctor consultation platform, i need to know how to allow the patient and the doctor communicate in real time. Any suggestion to go about it? -
django cannot create model with sufficient data
models.py class QuestionReply(models.Model): reply_user = models.ForeignKey(cUser, on_delete=models.CASCADE) reply_question = models.ForeignKey(Question, on_delete=models.CASCADE) reply = models.TextField() votes = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) views.py class AddQuestionReply(APIView): def post(self, request, id): try: reply = request.data.get('reply') reply_user = request.data.get('reply_user') reply_to_question = models.QuestionReply(reply_user=reply_user, reply_question=id, reply=reply) reply_to_question.save() return Response({'OK': 'Reply added'}, status=status.HTTP_200_OK) except: return Response({'400': f'QuestionReply has invalid data'}, status=status.HTTP_400_BAD_REQUEST) urls.py path('questions/question-reply/add/<int:id>', views.AddQuestionReply.as_view(), name='add-question-reply') data sent { "reply_user": "1", "reply": "Hello, world" } I have a model with 2 foreign keys, a TextField and 2 default fields, I sent the needed data to the url(reply_question comes from the url) but for some reason the model doesnt get created and an error occurs. -
Django how to filter a foreign key object only with specific value
I have two tables. Table Product id | name | Table Discount id | product_id | is_deleted product_id is the foreign key of product table's id, and is_deleted is a boolean field. How can I filter all products only with is_deleted discount? Notice those two tables may be large, so .exclude() is not fit for this case. -
Django change my migration write in migrations
I want to change my previous migration - in models I have this field: number = models.CharField('Number', max_length=8, unique=True, blank=True, editable=False, validators=[ MinLengthValidator(8), RegexValidator( regex=r'^[А-ЯҐЄІЇ]{2}-\d{5}$', message='Example TP-00001', ), ]) I want that my field looks like this: number = models.CharField('Number', max_length=11, unique=True, blank=True, editable=False, validators=[ MinLengthValidator(11), RegexValidator( regex=r'^[А-ЯҐЄІЇ]{2}-\d{8}$', message='Example TP-00000001', ), ]) That in regex I changed count of digits from 5 to 8. In my migration file I have this: migrations.AlterField( model_name='book', name='number', field=models.CharField(blank=True, editable=False, max_length=8, unique=True, validators=[django.core.validators.MinLengthValidator(8), django.core.validators.RegexValidator( message='Example: TP-00001', regex='^[А-ЯҐЄІЇ]{2}-\\d{5}$')], verbose_name='Number'), ), ] I tried to write func before this which change my migration: def update_number(apps, schema): Book = apps.get_model('library', 'Book') for bb in Book.objects.all(): bb.number = bb.number(regex='^[А-ЯҐЄІЇ]{2}-\\d{8}$') bb.save(update_fields=['number']) Here I tried to change number from 5 to 8 .What I am doing wrong?Please help? -
Getting "The current path, X didn’t match any of these." even though utls.py are configued
I have a weird problem with django not finding my file. Should be basic, but I cannot figure that out. If my app name is convers and the the file convers/urls.py (same folder as where settings.py is) reads: form django.contrib import admin from django.urls import path,include from django.views.generic import RedirectView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('c/',include('convers_app.urls')), path('conversapp/',include('convers_app.urls')), path('',RedirectView.as_view(url='conversapp/')), ] + static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) the urls.py in my convers_app folder reads from django.urls import path from .import views urlpatterns = [ path('',views.index, name='index'), path('timer', views.timer, name='timer') ] and in my views.py folder I have def timer(request): return render(request, 'timer.html') I also have the timer.html in my templates folder. What am I missing? Why won't django locate my timerview? -
gTTS.say(text) takes string
I am trying to create a website using Django which will take some text as input and convert it into audio. I created an empty array that should store the value of the input and convert it into audio. But when I run the server, it gives me an error saying - gTTS.say(text) takes string. My views.py #An empty array called textForTts textForTts = [] class UploadFileForm(forms.Form): tts = forms.CharField(label = "Convert text to audio here") def index(request): if request.method == "POST": form = UploadFileForm(request.POST) if form.is_valid(): tts = form.cleaned_data["tts"] textForTts.append(tts) obj = say(language='en-us', text= textForTts) return render(request,'demo/website.html',{ "form" : UploadFileForm(), 'obj':obj }) my index.html: {% block body %} {% load gTTS %} <form method="post"> {% csrf_token %} <audio src = "{{obj}}" controls ></audio> {{form}} <input type = "submit"> </form> {% endblock %} This is my first time trying out Django. What should I do to fix my errors? Thanks in advance. -
Django global variables with threading
I'm building a web-app to control some hardware connected to a Raspberry Pi. The goal: On server startup do some tasks once and store information globally (open COM Ports and store as objects) On POST/GET call from a view start a thread with the serialports from 1) plus some data (names as Strings) from the POST/GET call. This thread is some game logic for the hardware and runs for around one hour each Have possibility to terminate this thread anytime from a view and from within the thread Have possibility to get variables from thread and display on web-app At the moment I'm struggeling with the general design of this task. I'm new to threading and Django and can't quite tie these together. My Implementation right now only has a simple endless loop which should print out some debugging info if a global variable has changed. On startup of the server, I'm starting a runner script in a new thread. The global var is stored in cfg.py and imported in apps.py and views.py. All three files are in the root directory of the app. cfg.py RUNNING = False views.py from django.shortcuts import render from .models import Player from . import … -
How, when selecting a category, display both the elements of this category and the elements of all its subcategories?
I am new to django, and in python too, now I am practicing on creating an online store and faced the problem that it would be logical, when choosing a category, to also display products from all its subcategories. Google, unfortunately, did not help ... I think that you need to somehow correctly filter the product in the views, but how? skills are not enough to understand. Using Django-mptt for the category tree (fewer database queries) models.py class Category(MPTTModel): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Meta: ordering = ('name',) verbose_name = 'Категория' verbose_name_plural = 'Категории' def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) def __str__(self): return self.name views.py def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True).order_by('-created') if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/shop.html', {'category': category, 'categories': categories, 'products': products}) html <div class="category_conteiner"> {% recursetree categories %} <div class="sub_menu_category"> <a href="{{ node.get_absolute_url }}" class="subcatbtn">{{ node.name }}</a> {% if not node.is_leaf_node %} <div class="subcat_content"> <div class="subcat_column"> {{ children }} </div> </div> {% endif %} </div> {% endrecursetree %} For example, there are such categories: -Clothing --- Jackets --- Hats If … -
I need to check an aws server for the existence of a file, if it does I need to save it to a django object
So, I am currently attempting to port data into a new system. We have a simple file system that uses an Image model with a file field connected to S3Boto3Storage. What I need to do is check the existence of a file with a known path, and if it is there, save an Image object in Django connected to that file. Im not even sure where to start, I thought about using Django Fixtures to load a bunch of image files based on a certain path, but I worry about the safety of doing that on a production branch. Has anyone encountered this kind of issue? -
Django master-slave data sync
I've just started to learn about Master-slave architecture and I have some questions: The data added to master db not sync to the slave db, is it correct? When I try to add a foo object to masterdb, and try to read it from slavedb, there is nothing. If it not so when we will use this architecture? Thank you all. -
REST API for a Facemask detection neural network model
a model has already been trained for the purpose of facemask detection using yolov5 while using react as a frontend. rest api is to be used for connecting the frontend and the ML MODEL for accessing the webcam is there any help one can get to implement the api,the frontend has a button to request live stream which should access the function of the ML model to project the webcam and state facemask detection but having problem with using django rest api. -
Cannot resolve keyword 'approve_moderator' into field. Choices are: id, user, user_id
Problem Synopsis: I am implementing a login logic that checks if the user is registered and in the MODERATOR group (a user is automatically added to the MODERATOR group on registration) with the status of "approve_moderator" set to True. The field "approve_moderator" is False by default. Now during login, I check if the user is a registered user and is approved before redirecting them to the moderator dashboard views.py def is_moderator(user): '''check if registered and in moderator group''' return user.groups.filter(name='MODERATOR').exists() def afterlogin_view(request): if is_student(request.user): messages.success(request, 'successfully logged in as ' + request.user.username) return redirect('student-dashboard') elif is_moderator(request.user): approval_status = Moderator.objects.all().filter(user_id=request.user.id, approve_moderator=True) if approval_status: return redirect('moderator-dashboard') else: return redirect('moderator-wait-approval') elif is_admin(request.user): return redirect('admin-dashboard') else: return redirect('login') def register_moderator_view(request): if request.user.is_authenticated and request.user.is_moderator: return redirect('moderator-dashboard') else: form = RegistrationForm() if request.method == 'POST': form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): user = form.save(commit=False) user.is_moderator = False user.save() moderator = Moderator.objects.create(user=user) moderator_group, created = Group.objects.get_or_create(name='MODERATOR') moderator.user.groups.add(moderator_group) messages.info(request, 'Registration successful!') return redirect('login') # else: # messages.warning(request, 'Form invalid!') form = RegistrationForm() return render(request, 'accounts/register.html', {'form': form }) models.py class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) phone = models.CharField(max_length=150, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) profile_picture = models.ImageField(default='images/student.png', upload_to='profile_picture/', null=True, blank=True) is_student = models.BooleanField(default=False) is_moderator = … -
How to make Django load profile image files form "media" directory
I have a directory '/media/profile_image' where profile images uploaded by users are saved. In the template I built the url by using the user object <img id="profile_image" src="{{ request.user.profile_image.url }}"></div> which creates the correct url to the desired directory. But it doesn't show the image, why's that?