Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamic FileField upload_to throws RelatedObjectDoesNotExist error
I'm trying to make dynamic upload path to FileField model. So when user uploads a file, Django stores it to this path /folder/(environment.id)/(filename). Here is what I did: def get_upload_path(instance, filename): return f"folder/{instance.environment.id}/{filename}" class FileUploader(models.Model): environment = models.ForeignKey(Environment, on_delete=CASCADE) file = models.FileField( verbose_name="Object Upload", storage=MinioBackend(bucket_name=bucket_name), upload_to=get_upload_path, ) but I have this error FileUploader.environment.RelatedObjectDoesNotExist: FileUploader has no environment. Can someone helps me to resolve this error please -
django file upload - file(PDF) not opening from the path
hello everyone i have simple django app with PDF model (title, file ) everything is working file am able to upload the pdf and its getting uploaded to media folder which i specified for it the problem is when i click the link of the file in django admin the page keeps on loading whithout anything happen i dont get any kind of errors in the terminal am using :Django 3.2.13 models.py from django.db import models class PDF(models.Model): title = models.CharField(max_length=255,null=True,blank=True) file = models.FileField(upload_to='pdf/',blank=True,null=True) urls.py from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' not sure what should happen when clicking the link open/download note:changing the field to "models.ImageField" works fine and able to open the image from the link -
How to distribute Celery workers to different servers and queues with docker
I am trying to do some asynchronous tasks with redis and celery for my django website: I have a small task that only takes 10 seconds and is very simple, but I also have a task that can take several hours and is very resource intensive. I would like to have different queues for each kind of task, and have the easy queue run on my server(same server as the other db, web, redis containers; I am using Docker), but have the other queue run tasks on other external server. Is this possible to do? Should I create an additional redis container in the main server just for these external tasks? Do I just create a celery and a redis container in the external servers? Can a queue be connected to multiple external servers at the same time? Thanks I am able to run the celery tasks on my server( in a different container), but I can't find a way to spread them out like I want: having one queue run on my main server in this container, and the other one use only several external servers. -
How make dataclass for partial update(Patch method)?
Use @dataclass in my project. Now I want to implement @dataclass for PATCH method(partial_update) and initialize only provided arguments. For example: @dataclass class Person: id: int first_name: Optional[str] last_name: Optional[str] birthday: Optional[datetime.date] and use it like: person = Person(id=1, first_name ='Andrew') so now person have only two arguments id and first_name(person.id, person.first_name ) Does someone have understanding how to implement such stuff? P.S. Can't use @dataclass class Person: id: int first_name: Optional[str] = None last_name: Optional[str] = None birthday: Optional[datetime.date] = None because it will provide None to not provided arguments and it will update fields in database with None. I don't want these fields be updated in database, so I don't need them being initialized in dataclass. -
Which backend should I choose for a mobile app?
I am a junior dev and I am trying to create a mobile app with flutter ( ios + android). This app will have the « same » fonctionnality as a social network. However, I don’t know what is the best solution for the backend. I heard about Firebase but I am afraid about being stucked in their server. I also heard about Django but it seems to be for web app. What would you advise me to choose ? ————————————————————- -
Django GraphQL mutation returns null
I'm new to Graphene, Django, and GraphQL and am trying to wrap my head around how it would work when updating tables that use a Foreign Key. I am able successfully create a new author, which does not require populating a foreign key field, but I cannot create a new book, which does require populating a foreign key field. My Question: What is wrong with my implementation that is preventing me from creating a new book? What is Happening When I run the CreateNewBook mutation (shown below), GraphQL returns null as the title and no data is added to dim_all_books. What I Expect I expect that when I run the CreateNewBook mutation that the return results show the title of the book and a new record is appended to the table dim_all_books. What I've Tried When I run the following query, it works fine. mutation CreateNewAuthor{ createAuthor(authorData: { authorName: "William Shakespeare", yearBorn: "1722", yearDied: "1844", country: "Austria", booksWritten: 11 }) { author { authorName } } } However, when I run the following query immediately after that query, I get this result: { "data": { "createBook": { "book": null } } } mutation CreateNewBook { createBook(bookData: { title: "Romeo & … -
Trying to start Django on Apache: Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
the goal was to run my django project, which is created in a virtual environment from "virtualenv", on apache. I followed this tutorial, which worked well untill I wanted to start the apache as a windows service which resulted in: [Tue Mar 14 14:43:28.277072 2023] [mpm_winnt:notice] [pid 19800:tid 412] AH00455: Apache/2.4.56 (Win64) mod_wsgi/4.9.4 Python/3.10 configured -- resuming normal operations [Tue Mar 14 14:43:28.278069 2023] [mpm_winnt:notice] [pid 19800:tid 412] AH00456: Apache Lounge VS17 Server built: Mar 6 2023 10:53:37 [Tue Mar 14 14:43:28.278069 2023] [core:notice] [pid 19800:tid 412] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Tue Mar 14 14:43:28.283041 2023] [mpm_winnt:notice] [pid 19800:tid 412] AH00418: Parent: Created child process 8896 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\miniconda3' sys.base_exec_prefix = 'C:\\miniconda3' sys.platlibdir = 'lib' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\miniconda3' sys.exec_prefix = 'C:\\miniconda3' sys.path = [ 'C:\\miniconda3\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x000050e4 (most recent call first): <no Python frame> … -
Django Timeout when submitting a form with more than 5 fields [closed]
I have a Django website using mysql db running for more than one year, but now when I submit an update form for an instance with attributes more than 6, it gives me time out with no errors. when I decrease the number of attributes to 5 it works fine, no matter what are the 5 attributes it is about their length. I am using the Django UpdateView class. The code doesn't enter the post method it Hults before it. any idea of the cause? Thanks in advance I have updated python version to 3.8 and django version to 4.1.7, but no update happened -
Django: how to change status of cart item, if its quantity more than product's general_quantity?
My models.py: class CartModel(models.Model): CART_STATUS = ( ('n', 'Новая'), ('o', 'Заказана'), ('d', 'Удалена'), ) status = models.CharField( max_length=1, choices=CART_STATUS, blank=True, default='n') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, related_name='cart', verbose_name='Принадлежит') created_at = models.DateTimeField( auto_now_add=True, verbose_name="Дата создания") class Meta: verbose_name = "Корзина" verbose_name_plural = "Корзина" ordering = ('-created_at',) class CartItemModel(models.Model): CARTITEM_STATUS = ( ('a', 'Доступен'), ('n', 'Недоступен'), ('d', 'Удалён'), ) status = models.CharField( max_length=1, choices=CARTITEM_STATUS, blank=True, default='a') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product = models.ForeignKey( ProductModel, on_delete=models.CASCADE, related_name='items', verbose_name="Продукт") quantity = models.IntegerField(verbose_name="Количество") cart = models.ForeignKey( CartModel, on_delete=models.CASCADE, related_name='items', verbose_name="Корзина") class Meta: verbose_name = "Товар корзины" verbose_name_plural = "Товары корзины" class ProductModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=82, verbose_name='Товар') category = models.ForeignKey( ProductCategoryModel, on_delete=models.CASCADE, verbose_name='Категория', related_name='products') description = models.TextField(max_length=256, verbose_name='Описание') price = models.DecimalField( max_digits=6, decimal_places=2, verbose_name='Цена') general_quantity = models.IntegerField(verbose_name='Общее количество') def __str__(self): return self.title class Meta: verbose_name = "Товар" verbose_name_plural = "Товары" My serializers.py class CartItemSerializer(serializers.ModelSerializer): singe_item_price = serializers.SerializerMethodField('get_item_price') def get_item_price(self, obj): return obj.product.price class Meta: model = CartItemModel exclude = ('cart',) class CartSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): items = CartItemSerializer(many=True, required=True) total_sum = serializers.SerializerMethodField('get_field_name') def get_field_name(self, obj): return sum([i.quantity*i.product.price for i in obj.items.all()]) class Meta: model = CartModel # exclude = ('user',) fields = ('id', 'status', 'created_at', 'total_sum', 'items') … -
rtsp stream with django
I'm trying to put a url based on my views.py but it returns the error: Reverse for 'transmition' not found. 'transmition' is not a valid view function or pattern name. project urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from plataforma.views import * from django.views.generic.base import TemplateView urlpatterns = [ path("admin/", admin.site.urls), path('contas/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='index.html'), name='index'), path('plataforma/', TemplateView.as_view(template_name='plataforma.html'), name='plataforma'), path('plataforma/stream', TemplateView.as_view(template_name='stream.html'), name='stream'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app urls.py: from django.urls import path from .views import * urlpatterns = [ path('plataforma', PlataformaView.as_view(), name='plataforma'), path('stream/', StreamView.as_view(), name='stream'), path('transmition/', transmition, name='transmition'), ] app views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.core.mail import EmailMessage from django.views.decorators import gzip from django.views.generic import TemplateView from django.http import StreamingHttpResponse import cv2 import threading @gzip.gzip_page def transmition(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), mimetype="multipart/x-mixed-replace;boundary=frame") except: pass # return render(request, 'stream.html') class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture( "rtsp://jorge:jorge33621005@189.124.26.190:554/cam/realmonitor?channel=1&subtype=1") (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') class … -
Djanog custom models give [return-value] error
I am building some custom model fields for a project, which include a User model and a Team model, both in different directories. I have included the team app in the settings. I included the import in case I am importing incorrectly. from team.models import Team class UserManager(BaseUserManager): def create_superuser( self, name: str, email: str, number: str, password: Optional[str] = None, team: Optional[int]=None, ) -> "User": return self.create_user( name, email, number, password=password, team=team, is_staff=True, is_superuser=True, ) def create_staff( self, name: str, email: str, number: str, password: Optional[str] = None, team: Optional[int]=None, ) -> "User": return self.create_user( name, email, number, password=password, team=team, is_staff=True, is_superuser=False, ) def create_user( self, name: str, email: str, number: str, password: Optional[str] = None, team: Optional[int]=None, is_staff: bool = False, is_superuser: bool = False, ) -> "User": user = self.model( name=name, email=self.normalize_email(email), number=number, password=password, team= team, is_staff=is_staff, is_superuser=is_superuser, ) user.save(using=self._db) token = Token.objects.create(user=user) return user class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=250, unique=True) date = models.DateTimeField("Date", auto_now=True) number = models.CharField(max_length=100, default="") team = models.ForeignKey(Team, on_delete=models.PROTECT, default=1) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name", "number", "password"] def __str__(self) -> str: return f"{self.name} ({self.email}) {self.number}" … -
Throttle admin action django
I have accept_withdraw_request action in my RequestWithdaw admin model class RequestWithdraws(admin.ModelAdmin): list_display = ("get_email", "amount", "address", "is_accept", "is_reviewed") list_filter = ("is_reviewed",) actions = ("accept_withdraw_request", "decline_withdraw_request") @transaction.atomic def accept_withdraw_request(self, request, queryset): for withdraw_request in queryset: if withdraw_request.is_reviewed: self.message_user(request, level=messages.ERROR, message=f"Withdrawal request has already reviewed") return queryset.update(is_reviewed=True) for withdraw_request in queryset: with translation.override(withdraw_request.account.user.language): withdraw_request.account.withdraw(-withdraw_request.amount) amount = withdraw_request.amount - withdraw_request.commission tx_hash = USDT.create_tx_out(withdraw_request.address, amount) self.message_user(request, "Accepted {} withdraws".format(queryset.count())) queryset.update(is_accept=True) How can i throttle it to 1 request per 2 seconds when i push accept_withdraw_request admin action button How can i throttle it to 1 request per 2 seconds when i push accept_withdraw_request admin action button -
For loop with range in django template
How can i make a for loop with range function in django template? i want to search in three lists by using this structure. I tried this and it didn't work: {% for i in range my_list|length %} {{ my_list.i }} {% endfor %} -
Django list display of foreign key attribute that is boolean field using check or cross icons
My problem is similar to this thread: Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?. I want to display a foreign key attribute from the list display. This attribute is a BooleanField. Normally, it would display a check or cross if the admin page is on the model itself containing the field. Such as this: However when I reference this to other admin page. class ProofOfPaymentAdmin(admin.ModelAdmin): list_display = ('id', 'reference_number', 'user', 'is_subscribed',) def is_subscribed(self, obj): return obj.user.is_subscribed The return from the list display is the boolean values True or False. How can I change this to display the icons check or cross similar from the above? -
How to return to main page (with POST data) after viewing detail pages in Django
I am building a Django (4.1) app that managers can use to view production data. An initial GET request /prod-query request displays a blank form with machine, part, and date fields. Submitting the form creates a POST request to /prod-query that displays a list of machines with production data filtered by the above data. Each row of the above data is a link to a detail page for that machine. The detail page for that machine has Next and Prev buttons that show the same detail page for previous or next time periods. I also have a Back button that I want to return to the last /prod-query with the POST data so it displays the last data set. Note: I can't use onclick="history.back() as the page I want may not be the last page viewed. Is there a simple way to do this I am missing? Do I need to put the POST data in the session and check for it when I make a GET to the original URL? The data size isn't an issue. Just thinking there should be a more Pythonic way. For now, I am going to create a form in the detail pages that … -
django-wkhtmltopdf not loading apex charts
I'm working on a project where I need to export some reports about a certain entity, using wkhtmltopdf with an html template that includes some charts from ApexCharts.js. The charts load fine in a rendered html but not in the pdf generated. Here's a sample of what I'm trying to do: in report.html <!DOCTYPE html> <html lang="en"> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> </head> <body> <div id="chart"> </div> </body> <script> var options = { chart: { width: '100%', type: 'line', animations: { enabled: false, }, }, series: [{ name: 'sales', data: [30,40,35,50,49,60,70,91,125] }], xaxis: { categories: [1991,1992,1993,1994,1995,1996,1997, 1998,1999] } } var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); </script> </html> in views.py from django.core.files import File from io import BytesIO from wkhtmltopdf.views import PDFTemplateResponse from django.views.generic import View from django.shortcuts import redirect from django.urls import reverse_lazy class GenerateReportView(View): filename = "myfile.pdf" template_name = "reports/report.html" def get(self, request): response = PDFTemplateResponse(request=self.request, template=self.template_name, filename=self.filename, context={}, show_content_in_browser= False, cmd_options = { 'quiet': None, 'enable-local-file-access': True, 'encoding': 'utf8', 'no-stop-slow-scripts': True, 'page-size': 'A4', 'javascript-delay': 5000, } ) file = File(BytesIO(response.rendered_content), name="myfile.pdf") Report.objects.create( file=file, ) return redirect(reverse_lazy("home:home")) I have tried the following, with no luck: Using imgkit to pre-convert the chart to an image. Disabled the … -
locate all DOM elements inside script contianer
In my Django web page i have a for loop which creates multiple instances of a form. In each form i would like to execute some Javascript code when the page is loaded. My problem is I am unsure how to reference the form that contains the script inside the Javascript code. I am trying to search through each input in each form {% for item in items %} <form class="entry-item-container" action="{% url 'view_POST' view %}" method="post"> {% csrf_token %} <script> var inputs = form.getElementsByTagName("input") var input_values = [] for (let i = 0; i<inputs.length; i++) { if (inputs[i].type != "hidden") { input_values.push(inputs[i].value) } } </script> ... <!-- inputs --> ... {% endfor %} i would like the form in var inputs = form.getElementsByTagName("input") to reference the parent form -
Passing variable from urls.py to html
I set django-built-in messages to pass some info from my views.py file to html file directly. I'm using directly messages.info(request, "User credentials are updated.") to send messages. As you see below, it works fine. Right now, I am planning to pass variables from urls.py to HTML directly. Something like below: path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(template_name="account/dashboard.html"), **{'messages': 'User credentials are updated.'}**, name='password_change_done') When I search for it, I see that I can send a dictionary but it doesn't work for me. I tried to stick the same format(messages dictionary) where HTML expects. **{'messages': 'User credentials are updated.'}** Part of my urls.py file: # Password change # 1 ) Submit password change form path('password_change/', auth_views.PasswordChangeView.as_view(template_name="account/password/password-change-form.html"), name='password_change'), # 2 ) Success message stating that password is changed path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(template_name="account/dashboard.html"), **{'message': 'User credentials are updated.'}**, name='password_change_done'), Part of my dashboard.html file: <!-- Django's built-in message template part --> {% for message in messages %} {% if message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %} <h6 id="message-timer" class="alert alert-success text-center"> <i class="fa fa-sign-out" aria-hidden="true"></i> &nbsp; {{ message }} </h6> {% endif %} {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %} <h6 id="message-timer" class="alert alert-danger text-center"> <i class="fa fa-exclamation" aria-hidden="true"></i> &nbsp; {{ message }} </h6> {% endif %} {% if message.level == DEFAULT_MESSAGE_LEVELS.INFO %} <h6 … -
Django rest freamework: get a path parameter in the serializer
I request to a service with this path: /api/story_step/<chatbot>/<story_name>/ And in the suitable Django serializer I have the following field: interaction_name = serializers.CharField(source='interaction.name', read_only=True) Which is a reference to another table field: interaction = models.ForeignKey('interactions.Interaction', models.CASCADE, 'story_interaction', 'story_interaction') Is there any way to filter that field by the path parameter in order to see only the interactions of that defined chatbot? Thanks. -
How to hash previously saved password in phpmyadmin in Django
I'm building a Django app and working with existing database with it's own data. I built login function and creating user accounts from admin side. My question is how can I hash previously saved passwords in the database instead of re-creating accounts. Note: saved passwords are plain text not hashed. My views.py: creating accounts: @admin_login_required def add_emp(request): if request.method == 'POST': user_name = request.POST['user_name'] user_email = request.POST['user_email'] user_otj = request.POST['user_otj'] user_password = pwo.generate() user_password1 = make_password(user_password) empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj) if empObj: subject = 'Advanced Analytics Portal - Login Info' message = f'Name : {user_name}, \n Email : {user_email}, \n Password : {user_password} \n FROM - AA Portal' email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [user_email]) messages.success(request, "Employee was added successfully!") return HttpResponseRedirect('/create-emp') else: messages.error(request, "Some error was occurred!") return HttpResponseRedirect('/create-emp') return render(request, 'AddEmp.html') login view: def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email).first() if user_details and check_password(user_password, user_details.user_password): request.session['logged_in'] = True request.session['user_email'] = user_details.user_email request.session['u_id'] = user_details.user_email request.session['user_name'] = user_details.user_name request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') -
Django: how to clear session variables on page load, that way that paginator won't clear them
I'm storing filter data in session variables. How to clear them only when user in reloading or navigating to that page, but keep them when user is using pagination? def boxes(request): user = request.user log_in_form = CustomUserLogInForm() filter_form = FilterForm() # THAT MAKES SESSION VARIABLES USABLE ONLY ONCE, THAT IS GREAT UNLESS USER IS USING PAGINATION if filter := request.session.get("box_filter"): boxes = Box.objects.all().filter(id__in=filter) form_city = request.session.get("form_city") form_radius = request.session.get("form_radius") del request.session["box_filter"] del request.session["form_city"] del request.session["form_radius"] else: boxes = Box.objects.all() form_city = "" form_radius = "" paginator = Paginator(boxes, 5) page = request.GET.get("page") boxes = paginator.get_page(page) if boxes.paginator.num_pages < 5: page_numbers = range(1, boxes.paginator.num_pages + 1) else: if boxes.number < 3: min = 1 else: min = boxes.number - 2 if boxes.number > boxes.paginator.num_pages - 2: max = boxes.paginator.num_pages + 1 else: max = boxes.number + 3 page_numbers = list(range(min, max)) page_numbers.append("...") page_numbers.append(boxes.paginator.num_pages) log_in(request) if request.method == "POST": form = FilterForm(request.POST) if form.is_valid(): cities = pd.read_csv(settings.BASE_DIR / "static/cities_db.csv", sep=";") city = form.cleaned_data["city"] radius = form.cleaned_data["radius"] request.session["form_city"] = city request.session["form_radius"] = radius city_row = cities.loc[cities["Name"] == city.title()] city_lat, city_lon = str(city_row["Coordinates"].iloc[0]).split(", ") tmp_box_filter = [] for box in Box.objects.all(): if geopy.distance.geodesic((float(city_lat), float(city_lon)), (float(box.lat), float(box.lon))).m <= float(radius): tmp_box_filter.append(box.id) request.session["box_filter"] = tmp_box_filter return redirect("boxes") … -
Form marked for deletion but empty FormSet.deleted_forms
I've got a piece of code similar to the following: from django.forms import inlineformset_factory class EmailForm(forms.ModelForm): class Meta: model = MyModel EmailFormSet = inlineformset_factory( MyRelatedModel, MyModel, form=EmailForm, can_delete=True, extra=0 ) And I've got a custom class-based view which works perfectly fine for creating/saving new MyModel instances and for editing existing instances. When I mark a form / an instance for deletion, I can see my view receives the following POST method: <QueryDict: { 'csrfmiddlewaretoken': ['XXX'], 'email-TOTAL_FORMS': ['1'], 'email-INITIAL_FORMS': ['1'], 'email-MIN_NUM_FORMS': ['0'], 'email-MAX_NUM_FORMS': ['1000'], 'email-0-id': ['94ef2d4c-b2fc-4082-a460-e4344ddb20d4'], 'email-0-value': ['12345'], 'email-0-DELETE': ['on'], }> I believe this is, again, the expected behavior, in particular the formset.data do contain {'email-0-DELETE': ['on']} and the form is valid. However, the corresponding instance is not deleted. Indeed, when I display formset.deleted_forms, it turns out to be an empty list. Why? I've tried to deep dive into Django's inner mechanisms and I've noticed the method deleted_forms relies on another called _should_delete_form which simply returns form.cleaned_data.get(DELETION_FIELD_NAME, False). But in my case, form.cleaned_data only contains {'value': '12345'}, no "DELETE" key... So how is _should_delete_form supposed to return something else than False? Am I supposed to explicitly add a DELETE field to EmailForm, isn't the formset supposed to manage that extra field? -
is postman setting different for mac and windows? facing issue for postman in mac but same is working fine in windows
is postman setting different for mac and windows? facing issue for postman in mac but same is working fine in windows is postman setting different for mac and windows? facing issue for postman in mac but same is working fine in windows -
Optimizing Django db queries for Viewset
I recently was tasked to optimize db queries and performance of some of our django rest apis written in drf and was able to successfully use prefetch_related() to implement them. But there is one usecase I have been unable to resolve and looking for support on the same. Here goes the structure: Models.py class Section(models.Model): section_tags = models.ManyToManyField(AssetTag) section_name = models.CharField(max_length=200) section_createdate = models.DateTimeField(auto_now=True) class Collection(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name="collection_set") system_tags = models.ManyToManyField(AssetTag, blank=False, related_name='system_tags_poster_collections') card = models.ManyToManyField(Card) class Card(models.Model): tag = models.ManyToManyField(CardTag) # should we deprecate? system_tags = models.ManyToManyField(AssetTag, blank=False, related_name='system_tags_poster_cards') card_name = models.CharField(max_length=200) views.py class SectionViewset(viewsets.ModelViewSet): serializer_class = serializers.SectionSerializer http_method_names = ['get'] def get_queryset(self): queryset = Section.objects.filter(section_status=True, section_expiredate__gte=datetime.now()) return queryset serializer.py class SectionSerializer(serializers.ModelSerializer): collection_set = CollectionSerializer(many=True, read_only=True) class FilteredCollectionSerializer(serializers.ListSerializer): def to_representation(self, data): data = data.filter(collection_status=True, collection_expiredate__gte=datetime.now()) return super(FilteredCollectionSerializer, self).to_representation(data) class CollectionSerializer(serializers.ModelSerializer): card = CardSerializer(many=True, read_only=True) system_tags = AssetTagBadgeSerializer(many=True, read_only=True) class Meta: list_serializer_class = FilteredCollectionSerializer model = Collection fields = ('id', 'card', 'system_tags') I am unable to apply prefetch_related() to get any optimization of the queries on the SectionViewSet since it is sort of a reverse relationship in the Collection Model. Is there any way to optimize calls to db since I see many calls for card__tag and … -
Set height of div based on previous div
I have a for loop that creates product cards using Bootstrap. I want to add an additional card after where the user can click through to view all products in that category. I want that additional card to always been the same size and it's previous card. I have tried several JavaScript solutions from Google but can't get it to work. My code is as follows: {% extends "base.html" %} {% load static %} {% block content %} <!-- Disposable Vape Section --> <section> <div class="overlay"></div> <div class="container-fluid"> <div class="row"> <div class="col text-center mt-5"> <h2 class="logo-font">Shop Disposables - Over 100 flavours available</h2> <hr class="w-50 mb-5"> </div> </div> <div class="row"> <div class="product-container col-10 offset-1"> <div class="row mt-1"> {% for product in products %} {% if product.category.name == 'disposable_vape' %} <div class="col-sm-6 col-md-6 col-lg-4 col-xl-3"> <div class="card h-100 border-0"> {% if product.image %} <a href="{% url 'product_detail' product.id %}"> <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}"> </a> {% else %} <a href="{% url 'product_detail' product.id %}"> <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> </a> {% endif %} <div class="card-body pb-0"> <p class="mb-0">{{ product.name }}</p> </div> <div class="card-footer bg-white pt-0 border-0 text-left"> <div class="row"> <div class="col"> <p class="lead mb-0 …