Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Integrating Django Admin with Firebase
I'm working on a mobile application where the backend is done by Dango but all the authentication and real-time database are in firebase is there any way to integrate a Django admin with firebase instead of using firebase admin? if not, can firebase admin be used with python to create an admin role and has the same permissions which Django gives to admin? and how to introduce the created role if possible to Django? -
Django Vue.js PasswordResetView posted with Axios gets Error 403 Forbidden CSRF Token
I am trying to create a custom Email Restore page in the frontend with Vue.js. There, I am trying to send input with an email with Axios through /api/v1/accounts/password_reset/, so basically I am trying to use the original ResetPasswordView and instead of using its template, I am using it as an endpoint. When I submit the value, the console returns Error 403 Forbidden CSRF Token, like below. What can be done to avoid it? Forbidden (CSRF cookie not set.): /api/v1/accounts/password_reset/ [07/Sep/2021 16:32:55] "POST /api/v1/accounts/password_reset/ HTTP/1.1" 403 2864 /Users/IvanStepanchuk/Desktop/web-project/web-backend/core/settings.py changed, reloading. Watching for file changes with StatReloader Performing system checks... This is my ResetPassword.vue: <template> <div id="login"> <div class="w-100 d-flex justify-content-center" id="home__screen"> <div class="col-sm col-lg-4 text-center align-self-center decorator__spacing"> <div class="card bg-white p-4"> <h1 class="fs-3 pb-3">Recover your account</h1> <form @submit.prevent="passwordReset"> <div class="mb-3"> <input type="email" class="form-control" id="username" v-model="email" aria-describedby="emailHelp" placeholder="Email con el cual se ha registrado"> </div> <div class="alert alert-primary d-flex flex-column" role="alert" v-if="errors.length"> <span v-for="error in errors" v-bind:key="error">{{error}}</span> </div> <button type="submit" class="btn btn-primary mb-3">Enviar</button> </form> </div> </div> </div> </div> </template> <script> import axios from 'axios' export default { name: 'ResetPassword', data() { return { email: '', errors: [] } }, components: { }, mounted() { document.title = 'Company | Recover Account' }, … -
how to access external postgresql database and other services network server in side docker container
'''docker version: '3.9' services: web: build: . command: gunicorn --chdir DjangoRestApi build.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app - static_volume:/app/static ports: - 8000:8000 env_file: - ./.env networks: - services nginx: build: ./nginx volumes: - static_volume:/app/static ports: - 1234:80 depends_on: - web networks: - services client: build: client/ command: python client.py volumes: - ./client:/client depends_on: - web - nginx networks: - services volumes: networks: new: external: true ''' -
Get number of registers by prefetch_related, created before 45 minutes, in Django
It is dificult to explain, I am going to try. I have a table whateverA and table whateverB. They are joined by a ForeingKey. whateverB have the foreingkey. I need to get the registers in whateverA where whateverB_created (is the field with date create) is less than 45 minutes. less45 = datetime.datetime.today() - timedelta(minutes=45) b=whateverA.objects.prefetch_related('whateverB_set').filter(whateverB__created__lt = less45).count() Obviously, this query is not correct, because I have to get the register in whateverB with the last date in whateverB_created, and then, compare it with less45. I know that it is with annotate(max(whaterverB__created)) but when I do not know how compare with less45, because I can not apply _lt and I can not use <>. -
convert this format Tue Sep 07 2021 08:34:00 GMT+0530 (India Standard Time) to YYYY-MM-DD HH:MM:SS in python or django
I am trying to convert this format or any timezone format to YYYY-MM-DD HH:MM:SS. format needed to be converted is - Tue Sep 07 2021 08:34:00 GMT+0530 (India Standard Time). can anyone help ? -
How to create a field in the model that does not require to be filled
how should I create a field in Django with a parameter that doesn't require to be filled for example i want to create a 'newprice' field that if i don't fill it,it doesn't give me an error if you know pls answer,thank you -
Best way to add third attribute to Django models choices
As the title suggests, what would be the best way to go about adding a third attribute to Django's model enum choice so that I could access the property in the same manner as value or label. For instance, let's call this third attribute text what I want: class Vehicle(models.Model): class VehicleType(??): HONDA_CIVIC = 1, _("New car"), _("Vroom vroom") FORD_MODEL_T = 2, _("Old car"), _("not so fast") type = models.IntegerField(choices=VehicleType.choices, default=VehicleType.FORD_MODEL_T) vehicle = Vehicle.objects.create() vehicle.type.text >>> not so fast Is this possible without overwriting the base ChoicesMeta? I've tried a version as outlined in the python enum docs by updating __new__ however this doesn't seem to work. (And yes, I know I could change it to models.TextChoices and nix the int value, but I'm curious if this is easily possible) -
Using the url path data to pre-load fields in my HTML template
Short story on my project: I'm working on an app for work orders. A work orders consist of serial different momentums, called operations. Each work order have different operations depending on the type of work to complete. For each operations you can report your working time as instances. So to start a new instance you need to define workorder, operation, user and start time. In the databases there will be several thousand work orders and each one will have 3-10 different operations. So to simplify start (and then in the other end stop) a work instance I had an idea to try to utilize url for the workorder and then use the workorder to filter the query set of operations. But with my limit knowledge I'm stuck. I've been looking for hints and tried out different solutions for several days now. I have been able to solve it with a AJAX dynamic filtering, but I wanted to see if there was a way to solve it at the instance of rendering the page. to make it simpler I have reduced my app to the parts related to this question. My models.py from django.db import models from django.urls import reverse #Work … -
Custom registration form in django is not working correctly
The form fills in successfully even when a short numeric password is entered. I want the form not to be able to set short passwords only consisting of numbers. #forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label='Адрес электронной почты') password1 = forms.CharField(label='Пароль', widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label='Пароль повторно', widget=forms.PasswordInput, help_text='Введите тот же самый пароль ещё раз для проверки') captcha = CaptchaField(label='Введите текст с картинки ', error_messages={'invalid': 'Неправильный текст'}, generator='captcha.helpers.math_challenge') def clean_password(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 and password2 and password1 != password2: errors = {'password2': ValidationError( 'Введённые пароли не совпадают', code='password_mismatch')} raise ValidationError(errors) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user class Meta: model = AdvUser fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name', 'photo', 'description', 'captcha') How can I solve this problem? -
Send sms at a specific date and time in flask-restful?
I have an API using flask restful that stores user information like mobile number,message,date and time etc. I have to create a function that send sms to every users on their own date and time. Is there any way to do that? What are the best practices if there is more user? -
base64 to image using Django Rest Framework (DRF)
I am writing API, which accepts base64-encoded string and saves it as an image. It is trivial to do using standard library tools, such as base64, but how can I do it using viewsets.ModelViewSet? Which field should I modify? (I also have been trying to do it using custom middleware, but it is prohibited, since querydict cannot be modified) -
Is it worth to use `select_related()` when using just one instance of a model instead of a queryset?
I'll keep it short. Say we have this database structure: class Bird(models.Model): name = models.CharField() specie = models.CharField() class Feather(models.Model): bird = models.ForeignKey(Bird) And then we have some simple lines from an APIView: feather_id = request.query_params['feather'] feather = Feather.objects.get(pk=feather_id) bird_name = feather.bird.name # a lot of lines between bird_specie = feather.bird.specie Does it make any difference using: feather = Feather.objects.select_related('bird').get(pk=1) instead of: feather = Feather.objects.get(pk=1) in this scenario? I saw some people using select_prefetch() in this way and i wonder if it makes any difference, if not, which one should you use? Normally i agree that select_prefetch() is useful for optimization when using querysets to avoid querying each instance individually, but in this case, is it worth using it when you have just one instance in the whole APIView? In my opinion the only difference is that another query is just made later on, but when talking about performance, it's the same. Thanks in advance.