Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save audio file recored via Javascript/ajax into django media
I am recording voice via mic from front end using javascript and sending it back using ajax. <center> <p> {% csrf_token %} <button class="btn btn-primary py-3 px-5" id=record>Record</button> <button class="btn btn-primary py-3 px-5" id=stopRecord disabled>Stop</button> </p> <p> <audio id=recordedAudio></audio> </p> <h4 id="result" > Result</h4> </center> This is my html template Ajax file $.ajax({ type: 'POST', url: '/demo/audio/', data: fd, dataType: 'text' }) I have not created any model for this. Here is views.py function def audio_demo(request): if request.method=='POST': req=request.POST.get('data') d=req.split(",")[1] file_name='sub_app/media/file_{}.oga'.format(random.randint(0,99)) with open(file_name, 'wb') as f: f.write(base64.b64decode(d)) Though this is saving in media folder, but this is not the right way. I think the right way is to create a model object like we do for file field or image field. But i dont want to upload file like in file field. Instead i want to record it. My ultimate gaol is to store the audio file in media folder which is actually an S3 bucket and then get the file path. The above code snippet is storing file, but in local media folder, not on S3. Just for clarification, my media folder is configured for S3. My images are being uploaded there. -
Python Django - Prevent a booking record form being updated 24 hours before the booking starts
I've not started writing the code as I'm in planning stages for my assignment. I'm creating a booking app where the user selects a date and time. I want to restrict the user from updating their booking 24 hours (1 day) before the booking date. The user will be presented with a pop-up modal instead. Any ideas on how to achieve this please let me know. I'll be using Django, bootstrap for this. Thank you in advance. -
Why does CSS in the same Django project work correctly in Pycharm but does not work in Visual Studio?
I tried to open my django project written in pycharm in visual studio code and got a problem with CSS. In pycharm it works as it should, when I code in .css files it's displaying correctly on the website, but in VS, for example, if I open a project in VS with CSS code already written in in Paycharm, it works, but when I add something to the .css file in VS, nothing happens. Just no changes. The website displays css previously written in Pycharm. What could be the problem? -
how do we send file from django to reactjs where i dont need RESTFRame work?
I am new to ReactJS,I am using a django as backend, React as frontend i need to send a dict/json to reactjs which is locally created by choices not from data base. is there a way to send Data from django to reactjs without restframe work? -
How to use django tags in External js file.?
I want to append the chat popup in the html body from Jquery when the element gets clicked and then I want to show the messages from the database. Following is my code in an external js File, chatPopup = '<div class="message_box" style="right:290px" rel="'+ userID+'"><div class="message_header" rel="'+ userID+'">'+ '<img src="http://127.0.0.1:8000'+pro+'" class="user_icon"><h3 class="username">'+username+'</h3>'+ '<i class="fa fa-times close" rel="'+ userID+'"></i></div><hr><div class="message_content"><div class="messages" rel="'+ userID+'">'+ '{% for chat in thread.chatmessage_thread.all %}'+ '<div class="chat">'+ '{% if chat.user == user %}'+ '<div class="new_messages p2">{{ chat.message }}</div>'+ '{% else %}'+ '<div class="new_messages p1">{{ chat.message }}</div>'+ '{% endif %}</div>{% endfor %}</div><div class="input_box">'+ '<textarea type="text" class="message_input" rel="'+ userID+'" placeholder="Type Message..."></textarea>'+ '<i class="fa fa-arrow-circle-right enter" rel="'+ userID+'"></i></div></div></div>'; if ( $('[rel="'+userID+'"]').length == 0) { $("body").append( chatPopup ); What I know that we can't use the Django tags other than .html files, But is there any way how to send Django variable thread.chatmessage_thread.all (<model_name><related_name>all) look like variable in external file using the trick used in the following answer in link? https://stackoverflow.com/a/7318511/14715170 -
Django don't runserver in docker
I have django project and I want to dockerize it. when I use python manage.py runserver 0.0.0.0:8000 on my system its work: view result picture, but when I try use this command on docker, django server is not running view result picture This is my Dockerfile that used for build docker image: FROM python:3.9 ENV PYTHONUNBUFFERED=1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ -
Serving resized images from backend to frontend
We're making varied size of image when uploading images so that the frontend could use proper size of image depending on their situation(mobile vs desktop, network speed and etc). To do so, I can think of two ways and wonder which one is better than the other and what's the reason for that. option1) the backend just reply back "base_url"(http://sample_image_path.jpg) of image so that the frontend can pick image by appending image size(http://sample_image_path.jpg.small) according to their circumstance. option2) the backend pick and send the image size according to user agent in http request header and the frontend just render whichever returned from the backend. Because there's no way to know the network status in backend side, I thought 1st option is better but wonder if there's any other opinions. Thanks in advance -
Django Formset Form Delete Doesn't Work with Formset Management Form
I am using a formset to dynamically add fields and update the existing data. If I use {{formset}}, form delete buttons work properly, but if I use the formset managementform they don't work. {{formset.management_form}} {% for form in formset %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div id="social-form-list"> <div class="social-form flex"> {{form.social}} {{form.link}} {% if formset.can_delete %} <div class="flex items-center ml-8"><h2>Delete: </h2>{{form.DELETE}}</div> {% endif %} {% endfor %} {% endif %} When I post this form, it sets form-index-DELETE': ['on'] but it doesn't delete the existing data from the database. What can I change to make this work? THis is the post request it sends: <QueryDict: {'csrfmiddlewaretoken': ['token'], 'form-TOTAL_FORMS': ['5'], 'form-INITIAL_FORMS': ['5'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['24'], 'form-0-social': ['1'], 'form-0-link': ['link1'], 'form-1-id': ['25'], 'form-1-social': ['2'], 'form-1-link': ['link2'], 'form-2-id': ['33'], 'form-2-social': ['7'], 'form-2-link': ['link3'], 'form-3-id': ['51'], 'form-3-social': ['15'], 'form-3-link': ['link4'], 'form-4-id': ['67'], 'form-4-social': ['10'], 'form-4-link': ['link5'], 'form-4-DELETE': ['on']}> Thanks in Advance!! Any help is appreciated -
By default, is "transaction.atomic" already applied to the data which is added and changed in Django Admin?
I checked Django repository on GitHub. Then, transaction.atomic(using=using, savepoint=False) and transaction.mark_for_rollback_on_error(using=using) are called in save_base() which is called in save() in class Model(metaclass=ModelBase): as shown below: # "django/django/db/models/base.py" class Model(metaclass=ModelBase): # ... def save( self, force_insert=False, force_update=False, using=None, update_fields=None ): # ... self.save_base( using=using, force_insert=force_insert, force_update=force_update, update_fields=update_fields, ) # ... def save_base( self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None, ): # ... # A transaction isn't needed if one query is issued. if meta.parents: context_manager = transaction.atomic(using=using, savepoint=False) # Here else: context_manager = transaction.mark_for_rollback_on_error(using=using) # Here with context_manager: # ... So, by default, "transaction.atomic" is already applied to the data which is added and changed in Django Admin, right? In other words, when adding and changing data in Django Admin, the data is atomic by default, right? So, in "class Person(models.Model):", if we override "save()" which calls "super().save(*args, **kwargs)" in it as shown below: # "models.py" from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def save(self, *args, **kwargs): super().save(*args, **kwargs) # Here We don't need to put "@transaction.atomic" on "save()" as shown below, right?: # "models.py" from django.db import models from django.db import transaction class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) @transaction.atomic # Don't need def … -
Is there a way filter only selected tags in Django-bleach?
Im trying to use Django-ckeditor with Django-bleach, but Im running into problems where Django-bleach would filter all the tags that Django-ckeditor uses. Is there a way around this? -
No module named django-redis
No module named 'django.core.cache.backends.redis' django-redis installed enter image description here -
How to add HarperDB to a django project?
I have created a django project and I want to use harperDb with it. How can I connect Harper db with my django project? In setting.py the database code looks like this: -
NOT NULL constraint failed: DJANGO Rest Framework
I'm following an udemy tutorial, and all it's going nice until I try to do a POST to create an article on the database. When I send a POST to /api/posts with Multipart form: title: What is Java? description: Java order: 1 I receive the error: NOT NULL constraint failed: posts_post.order I can't find the solution to this specific situation. So I let you the code of my: models.py: from django.db import models class Post(models.Model): title = models.CharField(max_length=255) description = models.TextField() order = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) serializers.py: from rest_framework.serializers import ModelSerializer from posts.models import Post class PostSerializer(ModelSerializer): class Meta: model = Post fields = ['title', 'description', 'created_at'] views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from posts.models import Post from posts.api.serializers import PostSerializer class PostApiView(APIView): def get(self, request): serializer = PostSerializer(Post.objects.all(), many=True) return Response(status=status.HTTP_200_OK, data=serializer.data) def post(self, request): print(request.POST) serializer = PostSerializer(data=request.POST) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=status.HTTP_200_OK, data=serializer.data) I can do a GET request to my api/posts properly. The real problem is the POST request where I should create a new article/post -
Celery "No Nodes Replied within Time Constraint"
I am building a django web application for day-trading and I need to manage many celery workers that'll execute trades for users. Each botting strategy is ran as a task which is then consumed on a celery worker on an external shell window. Celery worker processes are created as a detached shell process using the python subprocess module. In the django app directory I am creating a dummy .sh bash files as targets that will initialize celery workers directly after launching the terminal window. f"celery -A MyDjangoServer4_0_4 worker --pool solo -Q bot{id}_queue -n bot{id} -l INFO -E" begins the celery worker on the terminal and cmd /k at the end prevents the terminal window from immediately closing afterwards for debugging. Each celery worker is getting it's own unique name and unique queue so they should be independently and concurrently operational from one another. I can spawn and create celery workers with new names and even signal tasks to them successfully. But I cannot recreate or reinitialize them using the same target name even after closing the sub process window. I believe I need to shutdown/terminate the node somehow so I can restart/reinitialize the subprocess worker, but I get an error … -
HTTP 400 BAD_REQUEST between dockerised Django and Spring boot service
I am running Django and a Spring boot application as Dockerised services with the same Docker volume and network. For one of the requirement, I am making a request from my Django service to the Spring boot service using Python's request module, as shown below, res = requests.post( f'http://{spring_host}:8080/getTranslatedAsFile/', data={ 'document-json-dump': json.dumps(data), "doc_req_res_params": json.dumps(res_paths), "doc_req_params": json.dumps(params_data), }) Here data, res_paths and params_data are python dicts. data contains keys and values depending on the content of the document. More the content (e.g. more words, sentences) more will be keys & values of data. The request is received by the Spring boot service at the controller as shown below, @PostMapping(value = "/getTranslatedAsFile/") public String getTranslatedAsFile(@RequestParam("doc_req_params") String docReqParams, @RequestParam("doc_req_res_params") String docReqResParams, @RequestParam("document-json-dump") String documentJsonDump) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); Document document = objectMapper.readValue(documentJsonDump, Document.class); ObjectMapper objectMapper1 = new ObjectMapper(); DocumentReqParameters documentReqParameters = objectMapper1 .readValue(docReqParams, DocumentReqParameters.class); ObjectMapper objectMapper2 = new ObjectMapper(); DocumentReqResourceParameters documentReqResourceParameters = objectMapper2 .readValue(docReqResParams, DocumentReqResourceParameters.class); return documentProcessService.translate(documentReqParameters, documentReqResourceParameters, document); } When I make a request for document with less content (< 50000 words), i.e data with less keys and values, I am receiving a HTTP 200 response from Spring boot service and able to process the response data. But … -
Django form not showing
Hi I'm trying to create a form in Django but it is not showing in the browser view.py from django.shortcuts import render, HttpResponse from .forms import FormularioRegistro def registro(request): form= FormularioRegistro() return render(request,'Proyecto_RapiExpress_App/registro.html', {'form': form}) forms.py from django.shortcuts import render, HttpResponse from .forms import FormularioRegistro def registro(request): form= FormularioRegistro() return render(request,'Proyecto_RapiExpress_App/registro.html', {'form': form}) registro.html {% extends "base.html" %} {% block title %} Registro {% endblock %} {% block content %} {{form}} {% endblock %} -
Login django only recognizes the superuser first created in the project
I am doing a web project for a barbershop in which there will be several users, the problem is that the login only enters with the super user created for the first time in the project, if I enter the admin and create more users as estaff or as super users either They enter neither the page login nor the admin login, they only enter with the initial super user. I have already reviewed the models and settings but I have not been able to know what the problem is, as extra information I have the project running in Docker, I do not know if it is a problem with the docker or with the django project. I need urgent help, thank you very much in advance. -
For vvxhid who helped me a lot
I add Chapter to make it easier to find the page How to make it so that when choosing a chapter on the site, linked pages to the chapter dynamically appear? models.py class Page(models.Model): title_title = models.ForeignKey('Book', on_delete=models.PROTECT) chapter_chapter = models.ForeignKey('Chapter', on_delete=models.PROTECT) number_page = models.CharField(max_length=(500)) def __str__(self): return self.number_page class Chapter(models.Model): book_name = models.ForeignKey( 'Book', on_delete=models.CASCADE, null=True) chapter_name = models.CharField(max_length=(500), db_index=True) def __str__(self): return self.chapter_name views.py def Second_page(request, book_slug): page = Page.objects.all() chapter = Chapter.objects.all() page = Page.objects.filter(title_title__slug=book_slug) chapter = Chapter.objects.filter(book_name__slug=book_slug) get_object_or_404(Book, slug=book_slug), return TemplateResponse(request, "second.html", {'page': page, 'chapter': chapter}) second.html {% extends 'index.html' %} {% block content %} <div class="chapter"> <select> {% for c in chapter %} <option value="">{{c.chapter_name}}</option> {% endfor %} </select> </div> {% for p in page %} <ul> <li><p>{{p.number_page}}</p></li> </ul> {% endfor %} {% endblock %} -
How do I get user deleted from Django database when I delete from Auth0 users and vice versa?
I am using Auth0 with my Django App for users login/logout authentication. I want a way that when I delete any User from Auth0, the same user account should be deleted from Django Database, likewise if I delete any user account from Django, the attached user from Auth0 should be deleted as well. How will I achieve this functionality? Any help will be appreciated. -
How to send emails and whatsapp messages to inactive members in django
I would like to send emails and whatsapp messages once a membership expires. I have a management command set up to check if the membership expired and updates it status. However, how do I know which member is being updated? I would like to set up a list of dictionary with name and number and filter through them each day and send out the messages. models.py class Member(models.Model): full_name = models.CharField(max_length=125) email = models.EmailField(max_length=125, blank=True, null=True) phone = models.CharField(max_length=20) image = models.ImageField(max_length= 256, upload_to=upload_to_image_post, null=True, blank=True) date_created = models.DateTimeField(default=django.utils.timezone.now) class Meta: verbose_name_plural = "All Members" def __str__(self): return str(f"{self.full_name}") class ActiveMember(models.Model): member = models.OneToOneField(Member, on_delete=models.CASCADE, related_name='is_member') start_date = models.DateField(default=django.utils.timezone.now) end_date = models.DateField(default=django.utils.timezone.now) status = models.CharField(max_length=2, choices=(('1','Active'), ('2','Inactive')), default = '1', blank=True, null=True) def __str__(self): return str(f"{self.member}") management command from turtle import update from django.core.management.base import BaseCommand, CommandError from members.models import ActiveMember from datetime import datetime, timedelta class Command(BaseCommand): help = 'Deactivate expired memberships!' def handle(self, *args, **options): ActiveMember.objects.filter(end_date__lt=datetime.now().date()).update(status='2') What's the easiest way to find out which member status is being changed and pull their name and phone number or name and email. -
Django Model Linking
How it should be: I choose a Book A http://127.0.0.1:8000/<slug:book_slug> opens with a selection of pages that are associated with the book that I have chosen; As it turns out: I choose a book A http://127.0.0.1:8000/<slug:book_slug> opens with a choice of absolutely all created pages; My Code: models.py from django.db import models from django.urls import reverse class Book(models.Model): title = models.CharField(max_length=(500)) slug = models.SlugField( max_length=(150), unique=True, db_index=True, verbose_name="URL" ) def __str__(self): return self.title def get_absolute_url(self): return reverse('book', kwargs={'book_slug': self.slug}) class Page(models.Model): title_title = models.ForeignKey('Book', on_delete=models.PROTECT) number_page = models.CharField(max_length=(500)) def __str__(self): return self.number_page urls.py from django.urls import path from .views import First_page, Second_page urlpatterns = [ path('', First_page), path('<slug:book_slug>', Second_page, name='Second_page') ] views.py from django.template.response import TemplateResponse from .models import Book, Page from django.shortcuts import get_object_or_404 def First_page(request): book = Book.objects.all() return TemplateResponse(request, "first.html", {'book': book}) def Second_page(request, book_slug): page = Page.objects.all() get_object_or_404(Book, slug=book_slug), return TemplateResponse(request, "second.html", {'page': page}) first.html {% extends 'index.html' %} {% block content %} {% for b in book %} <ul> <li><a href="{{b.slug}}">{{b.title}}</a></li> </ul> {% endfor %} {% endblock %} second.html {% extends 'index.html' %} {% block content %} {% for p in page %} <ul> <li><p>{{p.number_page}}</p></li> </ul> {% endfor %} {% endblock %} -
removetags returns invalid filter
Im trying to use {{ content|removetags:"style link script"|safe }} to remove specific html tags, but it is returning error django.template.exceptions.TemplateSyntaxError: Invalid filter: 'removetags' can someone help? -
Cannot resolve keyword 'location' into field
Good day, I spent a couple of day to solve that issue and I hope you can help. I installed django and I would like to use leaflet to display the position of my weather station. I found that nice tutorial and I could success the process. However, now I would like to apply that exercise to my project. I have a database with about less of one million of measures and I need to keep the structure of my database/table. I will do my best to describe my problem. My problem start here (viewsets.py) and here . As I understand, the 'location' match to a field of my table, which should contain a value similar to this 'POINT(6.000251769184164 46.19337852885697)',0 because the type of the field is POINT. However, my database does not have a such field. Instead, I have a field station_lat (float(8.6)) and station_lng (float(8.6)), where I save the latitude and longitude. That the reason why, I have the error Cannot resolve keyword 'location' into field. Choices are: fields_id_field, fields_id_field_id, id_station, installed, map, sensors, station_active, station_alt, station_archive, station_created, station_description, station_lat, station_lng, station_longname, station_name, station_order, stations_types_id_stations_type, ttn_app_id, ttn_dev_id, ttn_hardware_serial As I have to use my database as the fields … -
UNIQUE constraint failed: account_user.username
I customized the user model And I want to create a superuser in the terminal and I get an error. I was only able to make it the first time((I still can't login, it gives an error:Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.) Note that I do not enter duplicate username and email. my models.y: from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils.html import format_html from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=155, unique=True) full_name = models.CharField(max_length=200 , null=True, blank=True) phone_number = models.CharField(max_length=11, unique=True, null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) avatar = models.FileField(upload_to='avatar_user', null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin def showImage(self): # show image … -
django - making sections for course
I am building a site with the logic of Course - Section- Lesson. I can shoot the sections of the course, but I cannot shoot the lessons of the sections. Where am I doing wrong? Models.py class CourseCategoryModel(models.Model): name = models.CharField(max_length=200, verbose_name="Category Name") slug = models.SlugField(unique=True) class CourseModel(models.Model): name = models.CharField(max_length=200, verbose_name="Course Name") category = models.ForeignKey(CourseCategoryModel, null=True, blank=True, on_delete=models.PROTECT, verbose_name="Course Category") class CourseLessonSectionModel(models.Model): name = models.CharField(max_length=200, verbose_name="Section Name") order = models.IntegerField(max_length=3, verbose_name="Section Order") course = models.ForeignKey(CourseModel, null=True, blank=True, on_delete=models.PROTECT, verbose_name="Course") class CourseLessons(models.Model): course = models.ForeignKey(CourseModel, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Course") section = models.ForeignKey(CourseLessonSectionModel, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Lesson Section") name = models.CharField(max_length=200, verbose_name="Lesson Name") order = models.IntegerField(max_length=3 , verbose_name="Lesson Order", default=0) View.py def detail(request, slug): course = CourseModel.objects.get(slug=slug) courseSection = CourseLessonSectionModel.objects.all().filter(kurs__slug=slug) courseLessons = CourseLessons.objects.all().filter("what should i write here?") return render(request, "coursedetail.html", context={ "course": course, "courseLessons" : courseLessons, "courseSection" : courseSection })