Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django crispy form model formset - to STOP showing DELETE column
I am using Django 3.2 and crispy-forms 1.11.2 I have a model and form defined like this: /path/to/myapp/models.py class Foo(models.Model): pass class FooChild(models.Model): parent = models.ForeignKey(Foo, on_delete=models.CASCADE) title = models.CharField(max_length=16) /path/to/myapp/forms.py class FooChildForm(ModelForm): class Meta: model = FooChild fields = "__all__" class FooChildFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = 'post' self.layout = Layout( 'title', ) self.render_required_fields = True /path/to/myapp/views.py class FooCreateView(CreateView): model = Foo def __init__(self, **kwargs): super().__init__(**kwargs) self.choice_formset = inlineformset_factory(Foo, Child, form=FooChild, extra=9) def get(self, request, *args, **kwargs): form = self.form_class() p = self.model() formset = self.choice_formset(instance=p) helper = ChildFormSetHelper() helper.template = 'bootstrap/table_inline_formset.html' helper.form_tag = False return render(request, 'myapp/create.html', {'form' : form, 'formset': formset, 'helper': helper}) /path/to/myapp/templates/myapp/create.html {% block content %} <div class="container-lg"> <form id="frm-foo-create" method="post"> {% csrf_token %} <div class="row" style="margin: 30px 0px;"> <div class="col-lg-12"> <h2>Create a New Foo</h2> <br /> {% crispy form %} {{ form|as_crispy_errors }} {% crispy formset helper %} {{ formset.management_form }} </div> <!-- col-lg-12--> </div> <!-- row --> <div class="row" style="margin: 30px 0px;"> <div class="col-lg-2"> <input style="width:100%; padding-left: 20px;" type="submit" name="submit" value="Submit" class="btn btn-primary" id="btn-foo-create"> </div> </div> </form> </div> <!-- container --> {% endblock content %} When this page is created, it shows a DELETE column next to the Title column … -
Django serialize returns string instead list [closed]
I Have two models, one of them with a Foreign key, it's the same as you can see in this guide: https://docs.djangoproject.com/en/3.2/topics/serialization/ now I have this code to look for books published in a given year: books = Book.objects.filter(year=year) search_results = serializers.serialize( 'json', books, use_natural_foreign_keys=True, use_natural_primary_key=True, ) I expected to have a list, but I have a string: '[{"name": "test", "author"...' What am I doing wrong? -
unknown django core erorr?
I have created an authentication system using drf and now I want the system to display all the urls when accessing 127.0.0.1:8000/. After rearranging urls, I am getting this error here. [01/Oct/2021 13:02:55] "GET / HTTP/1.1" 500 62761 Internal Server Error: / Traceback (most recent call last): File "C:\Users\******\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [01/Oct/2021 13:04:02] "GET / HTTP/1.1" 500 62761 I dont know where is error poining at. core/urls.py from django.urls import include, path from users.views import ApiView urlpatterns = [ path("", ApiView, name="api-view"), path("users/", include("users.urls")), ] users/urls.py from django.urls import path from rest_framework.authtoken.views import obtain_auth_token from . import views urlpatterns = [ path("login/", obtain_auth_token, name="login"), path("logout/", views.Logout.as_view(), name="logout"), path("hello/", views.HelloView.as_view(), name="hello"), path("register/", views.UserCreate.as_view(), name="register"), ] -
how to access to image html tag from django's view?
I've to get access to <img> html tag from django , i'm using webcam to capture multiple images and them into database , but i dont know how use POST.get(img tag) ? here is what im trying .. class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = request.POST.get('images') print(images) format, imgstr = images.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) photo = Document.objects.create( booking = obj, docs = data ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('capture right image ..')) return render(request,'booking/add_img.html',{'obj':obj}) and here is my html and js code const player = document.getElementById('player') const canvas = document.getElementById('canvas') const form = document.getElementById('form') const docs = document.getElementById('document') const captureButton = document.getElementById('capture') const context = canvas.getContext('2d') captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height) e.preventDefault(); let new_image = document.createElement('img') new_image.src = canvas.toDataURL() console.log(new_image) new_image.setAttribute("name","images") form.insertAdjacentElement('beforeend',new_image) }); navigator.mediaDevices.getUserMedia({video: true}) .then((stream) => { player.srcObject = stream;}) <style> form *{max-width:20vw;} img{display:inline-block;} canvas{display:none;} </style> <form id="form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %} <video id="player" controls autoplay></video> <button type="button" id="capture">Capture</button> <button>save</button> <canvas id="canvas" width=320 height=240></canvas> </form> is there please a way to achieve it ? i can save one image in this way : const … -
'heroku' is not recognized as an internal or external command
Actually I am trying to host my site live on Heroku and I downloaded Heroku cli also but when i am trying to run any Heroku command it didn't work. I have set environment variable also. help me to find the solution. I used Techstack as: python, Django, sqlite3 and Heroku for hosting. I am following this video and I am sharing link with you: https://www.youtube.com/watch?v=kBwhtEIXGII&list=PL-51WBLyFTg2vW-_6XBoUpE7vpmoR3ztO&index=23 -
Website getting non responsive in next js
I'm developing an ecommerce website in next.js and django. The problem I'm facing is that sometimes the website is getting non responsive meaning it freezes the whole website and eventually I have to close the tab and start over. I have checked my code and went through several tutorials but didn't got any solution. The problem is not related to any single page or block of code. If anyone have faced any similar situation then please help me. Thanks in advance. -
Data not rendering from django database to html
Data from database to html is not rendering. The static data is rendering but unfortunately the database data is not rendering no error is comming and page is alo rendering but data is not rendering from databse to the page Html doc {% load static %} {% block title %} All Tractors {% endblock %} {% block content%} <section id="all_events"> <h1>All Tractors</h1> <h1>{{posts.implimentaion}} hi</h1> <br> <ul> {% for posts in post %} {% include "tractor/includes/singlePost.html" %} {% endfor %} </ul> </section> {% endblock %} Vews.py from django import forms from django.contrib.auth.models import User from django.shortcuts import render, redirect from .models import Post, Farmer # Create your views here. from django.http import HttpResponseRedirect # Create your views here. def starting_page(request): return render(request,"tractor/index.html") def posts(request): qs = Post.objects.all() context = {"posts":qs} return render(request,"tractor/all-post.html",context)``` -
Serializer with Foreign Keys, how to handle frontend view and backend queries?
I'm new to Django Rest Framework and I'm trying to understand how to handle the serializer both for frontend view and backend queries. I'll try to explain it better. I have these serializers: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', ) class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('name', ) class PostSerializer(serializers.ModelSerializer): author = AuthorSerializer(many=False, read_only=True) category = CategorySerializer(many=False, read_only=True) class Meta: model = Post fields = ('category', 'id', 'title', 'image', 'slug', 'author', 'excerpt', 'content', 'status', 'published') When I retrieve a post it looks like this: { "category": { "name": "django" }, "id": 2, "title": "Learn Django - Class-Based Permission Checks", "image": "http://localhost:8000/media/posts/laptop_SWf7fkV.jpg", "slug": "learn-django-class-based-permission-checks", "author": { "username": "admin" }, "excerpt": "Sed ut quam quis tellus pulvinar maximus. Nulla sodales, felis sed interdum lobortis, mi turpis dictum libero, at imperdiet justo eros a sem. Etiam et laoreet eros, quis gravida neque. Pellentesque vitae sollicitudin erat. Donec faucibus quis diam vitae pellentesque. Proin interdum justo vitae magna pretium egestas. Morbi tortor tortor, vestibulum a sagittis non, vestibulum at dolor. Etiam vulputate bibendum elit, id fermentum dui laoreet a. In ac porttitor lectus, eget tempor massa. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac … -
How to a call a REST API from a button
I'm a noob with html and django rest. In my router.py I declare my 'route' for "rest/v2" url: router.register(r"export/file/<int:id>/csv", views.IncomingFileExportViewSet, basename="ext-incomingfile-export") What I want to do is to call methods that are in the viewSet when a user press the button in the interface. Is it possible to that from html code or there is a better way? html (the button is export-csv): <div class="dropdown"> <button class="btn btn-outline-primary btn-export" aria-expanded="false" data-toggle="dropdown" aria-haspopup="true" > {% translate "Download" %} </button> <div role="menu" class="dropdown-menu"> <button id="export-csv" class="dropdown-item" type="button">{% translate "csv" %}</button> </div> </div> In another post on SO I read that it is possible using ajax, but I don't understand what should i write. -
Add annotation to all Django ORM queries that go through a model
The Django AbstractUser has fields for first_name and last_name, and get_full_name method. If I wanted to filter Users based on a search of their full name, I can add a custom model manager for the User, that has a method something like this: def filter(self, *args, **kwargs): queryset = super().get_queryset() if any(key for key in kwargs if key.startswith('full_name')): queryset = queryset.annotate( full_name=Concat(models.F('first_name'), models.Value(' '), models.F('last_name')) ) return queryset.filter(*args, **kwargs) Meaning I can do things like: User.objects.filter(full_name='Foo Bar') User.objects.filter(full_name__icontains='foo b') ... etc But of course this will only work when directly filtering Users above. If you have Post objects that are FK'd to a User, then you get this: Post.objects.filter(user__full_name='Foo Bar') ... FieldError: Related Field got invalid lookup: full_name So the question is, is there a way (without modifying all models to have custom managers), to allow Django to always recognise a given term (in this case 'full_name') on all joins to a given model's table, and annotate the necessary value so it can be filtered on? Note: I'm aware I could of course add full_name as a field on the user, and try to ensure that it's always up to date, but I'm specifically trying not to add this denormalised … -
ModelMultipleChoiceField field returning no value
How do i retrieve starred_by users by typing name in Django-admin, currently i am getting none class DocumentForm(forms.ModelForm): model = Document starred_by = forms.ModelMultipleChoiceField(queryset=User.objects.all()) class Meta: widgets = { 'created_by': AutocompleteSelect( Document._meta.get_field('created_by').remote_field, admin.site, attrs={'data-dropdown-auto-width': 'true'} ), 'organisation': AutocompleteSelect( Document._meta.get_field('created_by').remote_field, admin.site, attrs={'data-dropdown-auto-width': 'true'} ), 'starred_by':AutocompleteSelectMultiple( Document._meta.get_field('starred_by').remote_field, admin.site, attrs={'data-dropdown-auto-width': 'true'} ) } -
Django CSP Allow iframe from domain without having to set CSP for everything else
I need to allow another domain to embed my website in an iframe. I can use Django CSP to achieve this by setting the following, assuming that example.com is the domain that will be hosting the iframe of my website. CSP_FRAME_ANCESTORS = ("'self'", 'example.com') I would like Django to operate as it does out of the box, which is without CSP (correct me if I'm wrong). In this case, how could I achieve this with my CSP configuration? I currently have this, but it doesn't catch everything, and I'm not sure if it's less secure as Django out of the box, or the same. CSP_DEFAULT_SRC = ("'self'", '*') CSP_FRAME_ANCESTORS = ("'self'", 'example.com') Is this the same as how django operates by default, or have I made my application less secure by configuring it this way? -
ManyToMany django field not working, not taking any input in POST request?
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many to many relationship between them. But when I define it in my module/models.py file, it is not taking any input as 'rooms'. here are my files - module/model.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms) rooms/model.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) is_deleted = models.BooleanField(default=False) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(read_only=True, many=True) class Meta: model = Module fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): module_serializer = ModuleSerializer(data=request.data) if module_serializer.is_valid(): module_serializer.save() return Response(module_serializer.data['module_id'], status = status.HTTP_201_CREATED) return Response(module_serializer.errors, status = status.HTTP_400_BAD_REQUEST) POST request body for creating a module in POSTMAN - { "rooms": [ { "room_id": 2, "title": "4", "desc": "22", "level": "2", } ], "title": "4", "desc": "22", } With this request, module is being created, but no room is getting added in it. Can someone tell me why my rooms ar not getting added while creating modules? -
How can I read a file from ajax call in Django?
I'm working in Django. I need to upload a txt file and print its content in a table. I've tried many things but none of them work. Someone recommended that I just print the table in an ajax call, but it's not working. Here's what I'm trying: I'm showing a form to upload the file: class UploadFileForm(forms.Form): file = forms.FileField(label = "File:") I'm returning the form in a view: def upload(request): form = UploadFileForm() return render(request, 'upload.html', {'form': form}) I'm printing the form in the template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} </form> Then I have a button to confirm the upload: <button id="upload">Upload file</button> And here's where I try to print the table in a fetch, which is not working: var upload = document.getElementById("upload"); upload.addEventListener("click", function(){ const url = "{% url 'table' %}"; fetch(url, {method:'POST'}).then(response => response.json()).then(function(data){ var table = document.getElementById('table'); tableRow1.innerHTML = data.tableHTML; }) }) The url 'table' goes to this function: def table(request): data = file_to_HTML(request.FILES['file']) json_response = {"tableHTML":data} return JsonResponse(json_response) The problem here is that the table isn't printed at all and I get the following error: Internal Server Error: /table/ Traceback (most recent call last): File "C:\Users\Daniel\miniconda3\envs\env1\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ list_ … -
Https call from app in WSL2 to app in Windows 10
I'm working on two web applications (hereafter called App1 and App2) and both running on my Windows 10 PC. I am trying to make an https call from the backend of App2 and the backend of App1. App1 is an application written in ASP.NET and runs directly on Windows 10. This application can be reached via browser at https://localhost:44311/ App2 is written in Django and runs in Ubuntu-20.04 through WSL2 on the same Windows computer. This application can be reached via browser at the address http://localhost:8000/ Initial Test In App1 I expose a test function called GetMyResponse: [HttpGet] [AllowAnonymous] [Route("GetMyResponse")] public IActionResult GetMyResponse() { return Ok("Hello World!"); } I tried to connect to https://localhost:44311/GetMyResponse/ via web browser and everything seems to work correctly. Attempt 1 I'm trying to make an https call from the backend of App2 to the backend of App1 like this: import requests class App1APIView(APIView): def get(self, request, *args, **kwargs): response = requests.get("https://localhost:44311/GetMyResponse/", verify=False) return Response(response.content) This gives me the following error (I tried to disable the windows Firewall but nothing has changed): Traceback (most recent call last): File "/mnt/d/Projects/app2/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/mnt/d/Projects/app2/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) … -
How to add a button to an object page in the admin panel in django?
I have the model Product in my models.py: #models.py class Product(models.Model): code = models.CharField(max_length=8, unique=True, verbose_name='Код товара') category = models.ForeignKey(Category, verbose_name='Категория', on_delete=models.PROTECT) manufacturer = models.ForeignKey(Manufacturer, verbose_name='Производитель', on_delete=models.PROTECT, related_name='products') quantity = models.PositiveIntegerField(verbose_name='Количество') price = models.PositiveIntegerField(verbose_name='Цена') created_date = models.DateField(auto_now_add=True, verbose_name='Дата добавления') updated_date = models.DateField(auto_now=True, verbose_name='Дата изменения') And I want to add a button to the object creating page and to the object editing page in the admin panel, which would add 10 units to the quantity field. Please tell me how can I do this? -
How to fix could not find a version that satisfies the requirement django-multi-captcha-admin==1.0.0
I'm trying to set up a django project on my local. I've created a virtualenv. when I try install the requirements with: pip install -r requirements.txt I'm getting an error: ERROR: Command errored out with exit status 1: command: 'D:\Work\Web Development - Old\PullStream\django\evcs-fe\venv\Scripts\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\lachi\\AppData\\Local\\Temp\\pip-install-847c5ux0\\django-multi-captcha-admin_1ab73ac1a6d14606bffcc9cca96b88bf\\setup.py'"'"'; __file__='"'"'C:\\Users\\lachi\\AppData\\Local\\Temp\\pip-install-847c5ux0\\django-multi-captcha-admin_1ab73ac1a6d14606bffcc9cca96b88bf\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\lachi\AppData\Local\Temp\pip-pip-egg-info-ocge_4v4' cwd: C:\Users\lachi\AppData\Local\Temp\pip-install-847c5ux0\django-multi-captcha-admin_1ab73ac1a6d14606bffcc9cca96b88bf\ Complete output (2 lines): error in django-multi-captcha-admin setup command: use_2to3 is invalid. warning: pypandoc module not found, could not convert Markdown to RST ---------------------------------------- ERROR: Could not find a version that satisfies the requirement django-multi-captcha-admin==1.0.0 (from versions: 1.0.0) ERROR: No matching distribution found for django-multi-captcha-admin==1.0.0 How can I fix this? any suggestions? -
HINT: Add or change a related_name argument to the definition for 'operatives.Operative.user_permissions' or 'auth.User.user_permiss ions'
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'operatives.Operative.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'operatives.Operative.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'operatives.Op erative.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'operatives.Operative.user_permiss ions'. operatives.Operative.groups: (fields.E304) Reverse accessor for 'operatives.Operative.groups' clashes with reverse accessor for 'auth.User.g roups'. HINT: Add or change a related_name argument to the definition for 'operatives.Operative.groups' or 'auth.User.groups'. operatives.Operative.user_permissions: (fields.E304) Reverse accessor for 'operatives.Operative.user_permissions' clashes with reverse acces sor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'operatives.Operative.user_permissions' or 'auth.User.user_permiss ions'. -
Showing two like buttons
I am building a simple question and answer site in which i am implementing a simple like button, so I made another model for like the answer. But it is showing two like button when i like the post. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=900) class Answer(models.Model): question_of = models.ForeignKey(Question, on_delete=models.CASCADE) answer_by = models.ForeignKey(User, on_delete=models.CASCADE) body = models.CharField(max_length=900) class AnswerLike(models.Model): answer_of = models.ForeignKey(Answer, on_delete=models.CASCADE) liked_by = models.ForeignKey(User, on_delete=models.CASCADE) views.py def question_detail(request, question_id): post = get_object_or_404(Question, pk=question_id) answers = post.answer_set.all() context = {'post':post, 'answers':answers} return render(request, 'question_detail.html', context) def answer_like(request, answer_id): answer = get_object_or_404(Answer, pk=answer_id) if request.GET.get('submit') == 'like': save_like = AnswerLike.objects.create(answer_of=answer, liked_by=request.user) return JsonResponse({'liked':'liked'}) question_detail.html {{post}} {% for ans in answers %} {{ans.body}} {% for likes in ans.answerlike_set.all %} <form method="GET" class="AnswerLike" action="{% url 'answer_like' ans.id %}"> {% if request.user == likes.liked_by %} <button name='submit' type='submit' value="UnLike"><i class="fas fa-thumbs-up"></i>Liked</button> {% else %} <button name='submit' type='submit' value="Like"><i class="far fa-thumbs-up"></i> Not Liked</button> {% endif %} {% empty %} <button name='submit' type='submit' value="Like"><i class="far fa-thumbs-up"></i> Not Liked</button> {% endfor %} </form> {% endfor %} I know that i am using if statement like If user liked the post then show liked post liked icon and in else statement If … -
How to convert unicode list items into strings in Django template
Let us consider my template.html as {% for item in items_list %} ..... <td>Supporting seasons: {{ item.support_seasons }}</td> ..... {% endfor %} Where in my support_seasons we can store multiple seasons in my database it is stored as [u'Spring', u'Summer'] and also printing as [u'Spring', u'Summer'] but i want to print it as Supporting seasons: as Spring,Summer -
Dynamic Dropdown values (models.CharField with choices) depending on other Dropdown selection value in Django Admin Panel
I'm new in Django and trying to find solution for my problem with dynamic CharField choices. I've seen many similar threads, but mostly they are about frontend and Forms but I'm looking for solution in admin panel. class Client(models.Model): name = models.CharField(max_length=150) def __str__(self): return str(self.name) class Team(models.Model): name = models.CharField(max_length=150) description = models.TextField() members = models.ManyToManyField(User, through='Membership') clients = models.ManyToManyField(Client) def __str__(self): return self.name class Membership(models.Model): member = models.ForeignKey(User, on_delete=CASCADE) team = models.ForeignKey(Team, on_delete=CASCADE) role = models.CharField(max_length=15, choices=roles, default='member') clients = models.CharField() <--- there is problem def __str__(self): return str(self.member) The Organization has many teams. Each Team has clients, sometimes clients are part of few teams. User can be part of few teams with different roles. For example: User in Team1 has a role of admin and access to all clients of Team1, but also User has a role of normal member in Team2 and has access to only few clients of Team2. The relation between User and Team is defined in Membership where superuser of whole app can give permissions/access to Team and specified clients of this Team. So, I wanted to make dynamic clients field in Membership model. Creating Membership, if I choose team1 I want to … -
How to render multiple pages with one view function // Python
I currently have an app that renders .HTML pdf documents based of whether a bool value is selected or not. The problem is that the app cannot render both pages if more than 1 of the Bool values are selected , my current code looks like this : import tempfile def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) complexName = pkForm.Complex if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' html_string=render_to_string('main/reports/trialBalanceYear.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalanceMonthly' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' html_string=render_to_string('main/reports/trialBalanceMonthly.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) Is there any way that I can make the app render more than 1 page ?(I don't think redirect would work for this either) -
How to Store Image file temporary in Django
I am working on django rest framework API, receive a image. I want to delete images after processing. I am not using any database. -
Create multiple objects in one form django
I working with this models: class Projects(models.Model): id = models.AutoField name = models.CharField(max_length=50, verbose_name='Название проекта') customer_id = models.ForeignKey(Customers, verbose_name='Код заказчика', on_delete=models.CASCADE) description = models.TextField(verbose_name='Описание', null=True) date = models.DateField(auto_now_add=True, verbose_name='Дата заказа') deadline = models.DateField(verbose_name='Дата дедлайна') status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='Проектирование', verbose_name='Статус выполнения') curator = models.ForeignKey(Employees, verbose_name='Код куратора', on_delete=models.PROTECT, default=1) budget = models.DecimalField(max_digits=9, decimal_places=2, verbose_name='Бюджет', null=True) contract = models.FileField(null=True, verbose_name='Договор') def __str__(self): return self.name class Services(models.Model): id = models.AutoField project_id = models.ForeignKey(Projects, verbose_name='Код проекта', on_delete=models.CASCADE) name = models.CharField(max_length=50, verbose_name='Наименование услуги') qty = models.PositiveIntegerField(default=1, verbose_name='Количество') summ = models.DecimalField(max_digits=9, decimal_places=2, verbose_name='Сумма') def __str__(self): return "Услуги {} {}".format(self.name, self.qty) And i have forms for them: class ProjectForm(forms.ModelForm): deadline = forms.DateInput() class Meta: model = Projects fields = ('name', 'customer_id', 'description', 'deadline', 'status', 'curator') widgets = { 'name': forms.TextInput(attrs={'class': 'modal_title_form'}), 'customer_id': forms.Select(attrs={'class': 'modal_customer_form'}), 'status': forms.Select(attrs={'class': 'modal_status_form'}), 'description': forms.Textarea(attrs={'class': 'modal_desc_form'}), 'curator': forms.Select(attrs={'class': 'modal_curator_form'}), 'deadline': forms.DateInput(format='%d-%m-%Y', attrs={'class': 'modal_deadline_form'}) } class ServicesForm(forms.ModelForm): class Meta: model = Services fields = ('name', 'qty', 'summ') widgets = { 'name': forms.TextInput(attrs={'class': 'modal_service'}), 'summ': forms.NumberInput(attrs={'class': 'service_price_form'}), 'qty': forms.NumberInput(attrs={'class': 'counter'}), } I open one form for create one Project and this work: in HTML <form action="" method="POST"> {% csrf_token %} <div id="myModal" class="modal"> <div class="modal-content"> <span class="close">&times;</span> <div class="block modal_title_block"> <p class="label">Название</p> {{ form.name }} … -
from models import Category ModuleNotFoundError: No module named 'models' using Django
settings.py from django.apps import AppConfig class CategoryConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api.category' admin.py code from django.contrib import admin from models import Category admin.site.register(Category) apps.py from django.apps import AppConfig class CategoryConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api.category' Error on the terminalenter image description here