Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get default_storage path in django for use with google storage
how i can get the path of default_storage? i need to declare this path to use with google storage and openpyxl, the problem is that i can write and read files with default_storage.open, but i only need the path for use with openpyxl, but when i use default_storage.path i got the error: this backend doesnt support absolute paths. something like this i what i need: directory = default_storage.path() plantilla_excel = openpyxl.load_workbook(f"{directory}/ficha.xlsx") -
How to create dynamic model and form in Django
In my Django application I have a model named Service that contains multiple value. And I want a system that for each value different kinds of form to appear. I know I need models to generate forms and store data. But since the admin from custom admin panel can add or remove data in the Service model dynamically, I want a system that he can select the form for each data he enters in Service model. I need a guide on how can I achieve my goal. -
Popup-model is not opening in for loop (HTML)
I am trying to open a Pop up Model in for loop for every instance but the pop up model is opening for first instance But is not opening for other instances. I am using Django in template loop. template.html {% for comment in comments %} <button id="ModelButton">Open Model</button> <div id="Model" class="flagModel"> <div class="modal-content"> <div class="modal-mod"> <div class="container-fluid"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit"> </form> </div> </div> </div> </div> <script> var formModel= document.getElementById("Model"); var formButton = document.getElementById("ModelButton"); formButton .onclick = function () { formModel.style.display = "block"; } window.onclick = function (event) { if (event.target == formModel) { formModel.style.display = "none"; } } </script> {% endfor %} When I Place the JavaScript outside the for loop then it doesn't even work for one. I have tried many times but it is still not working. Any help would be much Appreciated. Thank You -
TypeError: dict object is not callable (inside Thread function)
I am getting an error in a program which is using threading to perform functions simultaneously, this process is a job which is run once per hour, The data that comes in is from a view in sql. The function that is called in target arg returns a dictionary and says "dict object is not callable". Inside the function, is returned a dictionary. My doubt is what should return in this function, if I don't return anything will it affect any other thread? # inside the jobs in django I call this function def ticket_booking(): query = " SELECT * FROM vw_ticket_list;" ttd = [] try: result = query_to_dicts(query) tickets = json.loads(to_json(result)) if tickets: # Calling the vaccination push message (php). for ticket in tickets: # Getting Generic details used by all categories full_name = tickets['full_name'] gender = tickets['gender'] email =tickets[email] if tickets['language_id'] == 1: # book english movie tickets # Calling the function inside the Thread for a Syncronuz Call (Wait and Watch) myThread = threading.Thread(target=book_english(email, full_name)) myThread.start() myThread.join() if tickets['language_id'] == 2: # book italian movie tickets myThread = threading.Thread(target=book_italian( email, full_name, gender)) myThread.start() # Starting the Thread myThread.join() #Will return here if sth is returned As you … -
Django REST Framework: Does ModelSerializer have an option to change the fields dynamically by GET or POST?
Does ModelSerializer have an option to change the fields dynamically by GET or POST? While GET requires complex fields such as nested serializers, these are not required for POST. I think the solution is to use separate serializers for GET and POST. But in that case, I'd have to create quite a few useless serializers. Is there any good solution? -
Django open excel.xlsx with openpyxl from google cloud storage
i need to open a .xlsx file from my bucket on google storage, the problem is i get :FileNotFoundError at /api/ficha-excel [Errno 2] No such file or directory: 'ficha.xlsx' this are the settings from my bucket. UPLOAD_ROOT = 'reportes/' MEDIA_ROOT = 'reportes' This are the route bucket/reportes/ficha.xlsx This are the code of mi get function: directorio = FileSystemStorage("/reportes").base_location os.makedirs(directorio, exist_ok=True) # read print("Directorios: ", directorio) plantilla_excel = openpyxl.load_workbook(f"{directorio}/ficha.xlsx") print(plantilla_excel.sheetnames) currentSheet = plantilla_excel['Hoja1'] print(currentSheet['A5'].value) what is the problem with the path? i cant figure out. -
Django ORM : Using pivot/intermediate tables
I am trying to render the view article by filtering through the model Spots and Images. I have managed to render the spots associated with each article, but cannot seem to render the images for each spot. I have an intermediate table ArticleSpots to link the 2 tables Spots and Articles. I have another intermediate table ImagesSpots to link the tables Spots and Images. All spots associated with the article is rendered, but how can I render the images for each spot? views.py def article(request, slug): article = get_object_or_404(Articles, slug=slug) spots = Spots.objects.filter(articlespots__article=article).distinct() images = Images.objects.filter(imagespots__spots=spots) context = {'spots': spots, 'article': article, 'images':images} return render(request, 'articletemplate.html', context) models.py class Articles(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) summary = models.TextField(blank=True, null=True) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') class Meta: managed = True db_table = 'articles' verbose_name_plural = 'Articles' def __str__(self): return str(self.id) + ": " + str(self.title) class Spots(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) author = models.ForeignKey(Authors, models.DO_NOTHING) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') summary = models.TextField(blank=True, null=True) content1 = models.TextField(blank=True, null=True) content2 = … -
How can I solve strftime TypeError when making a POST request in Django?
I am creating an API that contains a DateTimeField using Django but I am getting the following error "TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object" I have tried checking different sources but I haven't found a solution. The error is arising from the start_date line. from datetime import datetime def question_view(request): if request.method == 'GET': return HttpResponse("Вопрос не создан") elif request.method == 'POST': poll_question = request.POST['poll_question'] title = request.POST['title'] start_date = datetime.strftime(request.POST['start_date'],'%Y-%m-%d') Question.objects.create(poll_question=poll_question,title=title, start_date=start_date) return HttpResponse("Вопрос создан") else: return "Попробуйте снова" -
Is Nested aggregate queries possible with Django queryset
I want to calculate the monthly based profit with the following models using django queryset methods. The tricky point is that I have a freightselloverride field in the order table. It overrides the sum of freightsell in the orderItem table. That's why I have to calculate order based profit first and then calculate the monthly based profit. Because if there is any order level freightselloverride data I should take this into consideration. Below I gave a try using annotate method but could not resolve how to reach this SQL. Does Django allow this kind of nested aggregate queries? select sales_month ,sum(sumSellPrice-sumNetPrice-sumFreighNet+coalesce(FreightSellOverride,sumFreightSell)) as profit from ( select CAST(DATE_FORMAT(b.CreateDate, '%Y-%m-01 00:00:00') AS DATETIME) AS `sales_month`, a.order_id,b.FreightSellOverride ,sum(SellPrice) as sumSellPrice,sum(NetPrice) as sumNetPrice ,sum(FreightNet) as sumFreighNet,sum(FreightSell) as sumFreightSell from OrderItem a inner join Order b on a.order_id=b.id group by 1,2,3 ) c group by sales_month from django.db import models from django.db.models import F, Count, Sum from django.db.models.functions import TruncMonth class Order(models.Model): CreateDate = models.DateTimeField(verbose_name="Create Date") FreightSellOverride = models.FloatField() class OrderItem(models.Model): SellPrice = models.DecimalField(max_digits=10,decimal_places=2) FreightSell = models.DecimalField(max_digits=10,decimal_places=2) NetPrice = models.DecimalField(max_digits=10,decimal_places=2) FreightNet = models.DecimalField(max_digits=10,decimal_places=2) order = models.ForeignKey(Order,on_delete=models.DO_NOTHING,related_name="Item") result = (OrderItem.objects .annotate(sales_month=TruncMonth('order__CreateDate')) .values('sales_month','order','order__FreightSellOverride') .annotate(profit=Sum(F('SellPrice')-F('NetPrice')-F('FreightNet')),freight=Sum('FreightSell')) ) -
django live reload doesnt work with 2nd docker-compose file
I want to create 2 environments. Test and the standard dev environment. I need to run the django test server within test environment and the regular server, manage.py runserver on the other. The main dev environemnt will use the docker-compse.yml and the test environment will use test.yml. When I run docker-compose up, live-reload works normally. When i run docker-compose -f test.yml up, the test server runs but docker does not do live reloads. I add the same services to both files to shorten the CLI syntax. docker-compose.yml version: "3.9" services: web: build: dockerfile: ./compose/django/Dockerfile context: . container_name: main_app_django env_file: - ./.local/.env command: compose/django/start.sh volumes: - .:/code ports: - "8000:8000" redis: container_name: main_app_redis image: "redis:alpine" command: redis-server ports: - "6379:6379" celeryworker: build: dockerfile: ./compose/celery/Dockerfile context: . container_name: main_app_celery command: celery -A app worker -l INFO env_file: - ./.local/.env volumes: - .:/code depends_on: - redis test.yml version: "3.9" services: web: build: dockerfile: ./compose/django/Dockerfile context: . container_name: test_main_app_django env_file: - ./.local/.env command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py testserver cypress/fixtures/user.json cypress/fixtures/tracks.json --addrport 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" redis: container_name: test_main_app_redis image: "redis:alpine" command: redis-server ports: - "6379:6379" celeryworker: build: dockerfile: ./compose/celery/Dockerfile context: . container_name: … -
Patch with only one field with generics.RetrieveUpdateDestroyAPIView
I ma having the following models, and I wanted to achieve the best practice of patching data with RetrieveUpdateDestroyAPIView. Below is the models class Post(TimeStampedModel, models.Model): """Post model.""" title = models.CharField(_('Title'), max_length=100, blank=False, null=False) # TODO: Add image upload. image = models.ImageField(_('Image'), upload_to='blog_images', null=True, max_length=900) body = models.TextField(_('Body'), blank=False) description = models.CharField(_('Description'), max_length=400, blank=True, null=True) slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100) owner = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) class Meta: ordering = ['created'] def __str__(self): """ Returns a string representation of the blog post. """ return f'{self.title} {self.owner}' def save(self, *args, **kwargs): """Generate slug field.""" if not self.id: date = datetime.datetime.now() uid = uuid.uuid4() slug_str = '{} {} {}'.format(self.title, date, uid) self.slug = slugify(slug_str) super(Post, self).save(*args, **kwargs) class Tag(models.Model): """Tags model.""" name = models.CharField(max_length=100, blank=False, default='') owner = models.ForeignKey(User, related_name='tags_owner', on_delete=models.CASCADE) posts = models.ManyToManyField(Post, related_name='tags', blank=True) class Meta: verbose_name_plural = 'tags' def __str__(self): """ Returns a string representation of the tags post. """ return f'{self.name}' So in my views this is the Class which might help in patching : class PostDetail(generics.RetrieveUpdateDestroyAPIView): """Blog post details""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = [permissions.IsAuthenticatedOrReadOnly] lookup_field = 'slug' def patch(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, partial=True, context=request) if serializer.is_valid(): serializer.save() return … -
What happens when I log to stdout and stderr
I am switching my logging config in my django app away from a specific file and instead logging directly to the console (stdout & stderr) to allow the underlying system to handle, via 12 factor app. However, I am worried about pushing this to production because I cannot find an article about how my underlying system will handle the logs. I am running on Ubuntu 20.04. Is there any configuration I need to do on the server to actually capture this output? Is there any articles / resources that explain how this whole process works? Frankly right now I am rather mystified. Any help is greatly appreciated. -
Cannot assign "1": "Event.created_by" must be a "User" instance
Im stil getting errors like: Cannot assign "1": "Event.created_by" must be a "User" instance. or Cannot assign "admin": "Event.created_by" must be a "User" instance. my model: class Event(models.Model): name = models.CharField('the name of the event', max_length=255) created_at = models.DateTimeField(default=timezone.now, validators=[LessThanNowValidator()]) additional_data = models.CharField(max_length=300, blank=True, default='') created_by = models.ForeignKey(User, on_delete=models.CASCADE) class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_token = models.CharField(max_length=100, blank=True, null=True, unique=True) def __str__(self): return f"{self.user.username}" my view: class EventApiView(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Event.objects.all() serializer_class = EventSerializer @action(methods=['POST'], detail=False) def post(self, request): raw = json.dumps(request.data) data = json.loads(raw) name = data.get('name') additional_data = data.get('additional_data') created_by = data.get('created_by') event_data = { 'name': name, 'additional_data': additional_data, 'created_by': created_by #also tried "request.user.username" } event = Event.objects.create(**event_data) serializer = EventSerializer(data=event_data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
pylint message: "django not configured"
I'm building a python webapp with django. When I run prospector -X on the project, I get the following error from one of the .py files Line: 1 pylint: django-not-configured / Django was not configured. For more information run pylint --load-plugins=pylint_django --help-msg=django-not-configured I've tried following: github and stackoverflow but they didn't work. prospector 1.5.1 pylint 2.11.1 astroid 2.8.3 Python 3.7.0 What should I do? -
How to get a button outside of a form to line up with button inside of form?
I feel like this is relatively simple styling, but i cant for the life of me figure out how to do it. My code: <div class="container py-5"> <div class="pull-left" style="margin-right:5px"> <form method="post"> {% csrf_token %} <p> <h3> Do you want to delete <em>"{{ entry.title }}"</em> posted on {{ entry.date_created|date:'Y-m-d' }}? </h3> </p> <button class="btn btn-danger" type="submit" value="Confirm">Confirm</button> </form> </div> <a href="{% url 'entry-detail' entry.id %}"> <button class="btn btn-secondary">Cancel</button> </a> </div> I want both the Confirm and Cancel buttons to be aligned next to eachother, but if I put the Cancel besides the Confirm button or in a div inside of the form it too performs the delete action. In Django using Bootstrap. -
Need to create required foreign key pointing to User, Django model
I need to create required field with foreign key pointing to User. Is this correct? created_by = models.ForeignKey(User, on_delete=models.CASCADE, default='') -
Django Bootstrap modal is giving an error
I am using jQuery script excecuted on an on("click") event to do following: ajax call to Django url / view that populates a 'modal' template. modal template's HTML is then appended to an empty modal div. ajax success event then does show() modal div. Everything appears to work successfully eg I get the modal to show, with populated modal template content, but I am also getting the following error: Uncaught TypeError: Illegal invocation selector-engine.js:22 at Object.findOne (selector-engine.js:22) at De._showElement (modal.js:221) at modal.js:143 at b (index.js:242) at backdrop.js:53 at b (index.js:242) at v (index.js:248) at ke._emulateAnimation (backdrop.js:125) at ke.show (backdrop.js:52) at De._showBackdrop (modal.js:328) Any ideas what is happening here? Using Bootstrap 5, jquery-3.6 Empty div: <div id="modal-div"></div> Script: var modalDiv = $("#modal-div"); $(".open-modal").on("click", function() { $.ajax({ url: $(this).attr("data-url"), success: function(data) { modalDiv.html(data); $("#photo-modal").modal('show'); }, }); }); Modal template HTML: <div id="photo-modal" class="modal-container"> <p>{{ photo.id }}</p> </div> -
How can I set custom template for change password in Django
I have template like this <form method="POST"> {% csrf_token %} {{ form }} <button>Change password</button> </form> I have a class in views.py like this class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangingForm template_name = 'external/change-password.html' success_url = reverse_lazy('password_success') I have a form like this class PasswordChangingForm(PasswordChangeForm): old_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'type' : 'password'})) new_password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'type' : 'password'})) new_password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'type' : 'password'})) class Meta: model = External fields = ['old_password', 'new_password1', 'new_password2'] I set the template name but by default it takes the django admin site for changing the password not my custom one. Can anyone help me please? -
While im trying to migration . the error showing
return getattr(self._connections[self._alias], item) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\connection.py", line 62, in getitem conn = self.create_connection(alias) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py", line 204, in create_connection backend = load_backend(db['ENGINE']) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py", line 111, in load_backend return import_module('%s.base' % backend_name) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 29, in raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. PS C:\Users\mehdy\projects\mehdy> -
app running but whenever uploading file i get "Truncated or oversized response headers received from daemon process" in django
whenever i activate django logging in deployed app using apache with mod_wsgi i get Truncated or oversized response headers received from daemon process same thing happens whenever i activate logging in settings.py. this is example of the logging code LOGGING = { 'version': 1, 'loggers': { 'django': { 'handlers': ['file', 'file2', 'file3'], 'level': 'DEBUG' } }, 'handlers': { 'file': { 'level': 'CRITICAL', 'class': 'logging.FileHandler', 'filename': '../logs/debug5.log', 'formatter': 'simpleRe', }, 'file2': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '../logs/debug6.log', 'formatter': 'simpleRe', }, 'file3': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '../logs/debug7.log', 'formatter': 'simpleRe', } }, 'formatters': { 'simpleRe': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', } } } -
Getting id of instance in form and save in it
I am building a Blog App and I am working on a feature in which A user can report comment so I created another model for storing reports so i am saving which comment is reported But I placed report form in detail view so report form will be below the comment in post detail page, In which I am not getting the comment id when reporting. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=1000) class Comment(models.Model): commented_by = models.ForeignKey(User, on_delete=models.CASCADE) body = models.CharField(max_length=1000) class ReportComment(models.Model): reported_by = models.ForeignKey(User, on_delete=models.CASCADE) reported_comment = models.ForeignKey(Comment, on_delete=models.CASCADE) text = models.CharField(max_length=1000) views.py def blog_detail_page(request, blog_id): post = get_object_or_404(Blog, pk=blog_id) if request.method == 'POST': reportform = CommentReportForm(data=request.POST) if FlagCommentForm.is_valid(): form = reportform.save(commit=False) # Saving in this line flagForm.reported_comment = reportform.id form.reported_by = request.user form.save() return redirect('home') else: reportform = CommentReportForm() context = {'reportform':reportform, 'post':post} return render(request, 'blog_detail_page.html', context) blog_detail_page.html {{post.title}} {% for comment in post.comment_set.all %} {{comment.body}} <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ reportform }} </table> <button type="submit">Save</button> </form> </div> {% endfor %} What have I tried :- I have also tried by using loop like :- comments = post.comment_set.all() for com in comments: if request.method == 'POST': ...... … -
media files getting downloaded with .html extension Django
I have a problem in Django, all the media files uploaded on the site are getting downloaded as .html despite having extensions like .mp3, .wav, .zip and .mp4. I have tried changing the content type but nothing is working. Here is my views.py: def post(self, request, pk, type, *args, **kwargs): if type == 'item': item = Item.objects.get(id=pk) item_media = ItemMedia.objects.get(item=item) #order data check if item.price != 0: if request.user.is_authenticated: orderDataCheck = OrderData.objects.filter(item=item, user=request.user) orderDataCheck_count = orderDataCheck.count() #Checking if an item is part of the purchased album try: purchase_acheck = OrderData.objects.filter(album__id=item.album.id, user=request.user, item_type='album').count() except: purchase_acheck = 0 if orderDataCheck_count > 0 or request.user.id == item.business_owner.id or purchase_acheck > 0: #Return an mp3 image_buffer = open(item_media.file.path, "rb").read() response = HttpResponse(image_buffer) response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(item_media.file.path) return response #return redirect(item.upload_file.url) else : return HttpResponse('<h4>Error, You do not have access to this product!</h4>') else: return redirect('accounts:login_page') -
How to process time consuming task in DJango?
Can anyone let me know how to process asynchronous HTTP requests in general (or in DJango specifically)? I actually have a web app which needs to generate a report in backend and output to a excel file. Its a time consuming process, and takes upto 5 minutes to be completed. I am actually new to asynchronous requests and am pretty much confused with so many jargons like message queues, message brokers, RabbitMQ, Celery.... -
Connection aborted error using Django and database code
I have a problem with Django and database postresql. I am trying to fetch some data with the following code: resultQuery=Usuario.objects.filter(correo=strmail,contrasena=strpwd) So far all is good, also I get the record count, but after a little while the server seems to disconnect and I get this error: ConnectionAbortedError: [WinError 10053] Se ha anulado una conexión establecida por el software en su equipo host When I don't use database code it seems to be fine, it only happens when I start using some database code. Thanks -
Django REST FileUpload Parser does not work with images
I am very new to Django. I am trying to develeop a web service using REST Framework. The client will send me image or pdf and I will do some image processing on this files. When i send a multipart/formdata request from Postman with attachment, pdf files are saved correctly, but images are not. views.py class FileUploadView(APIView): parser_classes = (FileUploadParser,) def post(self, request, format="file"): file_obj = request.FILES['file'] #file_name = default_storage.save(file_obj.name, file_obj) filename = 'filename' with open(filename, 'wb+') as temp_file: for chunk in file_obj.chunks(): temp_file.write(chunk) return Response(file_obj.name, status.HTTP_201_CREATED) Can you help me? What am i doing wrong?