Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django Test AssertionError: ValueError not raised
My test is not detecting a value error in my test model file when email is not provided its raising a value error and in my test file i did not provide an email but its not detecting a value error https://github.com/kekidev/CustomUserDjango/blob/main/users/models.py ` https://github.com/kekidev/CustomUserDjango/blob/main/users/tests.py this is my test file at the very bottom i commented details about my problem from django.test import TestCase from django.contrib.auth import get_user_model class UserAccountTests(TestCase): def test_new_superuser(self): db = get_user_model() super_user = db.objects.create_superuser( 'testuser@super.com', 'username', 'password') self.assertEqual(super_user.email, 'testuser@super.com') self.assertEqual(super_user.username, 'username') self.assertTrue(super_user.is_superuser) self.assertTrue(super_user.is_staff) self.assertTrue(super_user.is_active) self.assertEqual(str(super_user), "username") with self.assertRaises(ValueError): db.objects.create_superuser( email='testuser@super.com', username='username1', password='password', is_superuser=False) with self.assertRaises(ValueError): db.objects.create_superuser( email='testuser@super.com', username='username1', password='password', is_staff=False) def test_new_user(self): db = get_user_model() user = db.objects.create_user( 'testuser@user.com', 'username', 'password') self.assertEqual(user.email, 'testuser@user.com') self.assertEqual(user.username, 'username') self.assertFalse(user.is_superuser) self.assertFalse(user.is_staff) self.assertFalse(user.is_active) with self.assertRaises(ValueError): # This part is the problem when i dont pass an email in my model file it should raise a ValueError and it DOES raise ValueError but TestCase dose not detect it db.objects.create_user( email='', username='a', password='password')` and this is my model file Look at line 9 from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): def create_user(self, email, username, password=None, **other_fields): if not email: … -
Django Not redirecting http -> https
I want to redirect almy http request to https i have installed django-sslserver and set SECURE_SSL_REDIRECT = True in settings.py file WHen i run : python manage.py runsslserver localhost:8000 It worka fine But when i try to access my application by entering http://localhost:8000 it is not redirecting to https://localhost:8000 please help..Thanks in advance -
How to use optgroups with Django admin's FilteredSelectMultiple?
I've been using optgroups on my Django Admin page with a SelectWidget, but when I moved to FilteredSelectWidget, they no longer work. What I've noticed is that before the JS for FilteredSelectWidget loads the underlying SelectWidget has the optgroups, but once the JS loads they disappear. For example, if I have a form mixin like so: class SelectMixin(forms.ModelForm): select_field = forms.ModelMultipleChoiceField( queryset=ModelA.objects.all(), required=False, widget=FilteredSelectMultiple("Select Field", is_stacked=False) ) def __init__(self, *args, **kwargs): super(SelectMixin, self).__init__(*args, **kwargs) self.fields['select_field'].choices = (('Group 1' ((1, 'item 1'), (2, 'item 2'))), ('Group 2' ((3, 'item 3'), (4, 'item 4')))) This works when the widget is set to SelectWidget, but when it's set as above it no longer works. Despite the fact that it still generates the correct groupings via the optgroup method. It would appear that the JS of FilteredSelectWidget overwrites them. Has anyone found a way around this? I need a select widget that I can easily deselect with, and the filtering is a nice bonus. -
django - change static to dynamic view retruning only one id in the restframework list
I have written the static code for the django application where user select the time format (DD-MM-YYYY or MM-DD-YYY)date & time that returning the time in such format but im using conditional statement for each time format I want it to be dynamic when there is a additional format is added (YYYY-MM-DD) I don't want to create another conditional statement. I don't want to create any more additional model field in the db.Is there any way to make it dynamic I have tried but couldn't figure out. And also in api I'm converting the time according to selected timezone I could not able to get the date and time for all the user it returning only one user with time.when I use normal django restframework method its returning all the user without time.In detail View im able to get the time for individual user separately API: models.py: from django.db import models import pytz from django.db import models import datetime from django.shortcuts import reverse from django.utils import timezone from datetime import datetime from django.conf import settings from django.utils.text import slugify TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) CHOICES =(('DD-MM-YYYY','DD-MM-YYYY'),('MM-DD-YYYY','MM-DD-YYYY'),('DD-MM-YYYY HH-MM','DD-MM-YYYY HH-MM'), ('MM-DD-YYYY HH-MM','MM-DD-YYYY HH-MM')) class Userbase(models.Model): username = models.CharField('username', max_length=155) slug = models.SlugField(editable=False) email … -
Class 'MyModel' has no 'objects' member
I'm using prospector to run pylint-django, but for some reason it is not interpreting my model classes as part of the Django framework. Running it as follows: DJANGO_SETTINGS_MODULE=myproj.myproj.settings prospector It seems that prospector picks up that the project itself is Django however, as we can see from the final output: Check Information ================= Started: 2021-10-01 05:58:18.025548 Finished: 2021-10-01 05:58:27.211931 Time Taken: 9.19 seconds Formatter: grouped Profiles: default, no_doc_warnings, no_test_warnings, strictness_medium, strictness_high, strictness_veryhigh, no_member_warnings Strictness: None Libraries Used: django Tools Run: dodgy, mccabe, pep8, profile-validator, pyflakes, pylint Messages Found: 53 Throughout my entire project I'm getting errors like: pylint: no-member / Class 'MyModel' has no 'objects' member (col 28) I've tried creating a new django project with the same skeletal structure, but have not yet been able to reproduce, suggesting there is something about my real-world project causing the issue. Any suggestions on what sort of thing might be causing it, and how to debug to try and narrow down the issue? -
Empty tag failed with like button
I am beginner in Django. I am building a simple question and answer site and I am implementing like answer feature so i made a model of Like Answer but it was not working in just if else in template so i added empty tag But button is not liking the answer. 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=modelsCASCADE) 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">Liked</button> {% else %} <button name='submit' type='submit' value="Like">Not Liked</button> {% endif %} {% empty %} <button name='submit' type='submit' value="Like">Not Liked</button> {% endfor %} </form> {% endfor %} When i save a like from another user from admin then it is liking from request.user but when no-one like … -
Django foreign key relationship with multiple models
I have many different models with different types of fields. I want to use foreign key for multiple models. Like: class Model1(models.Model): title = models.TextField() body = models.TextField() class Model2(models.Model): tag = models.CharField(max_length=200) uploadedDate = models.DateTimeField(auto_now_add=True) class MainModel(models.Model): content = models.ForeignKey([Model1, Model2], on_delete=models.CASCADE) # this will give error How can I do this? -
How to get Image name while updating in react js?
Here I'M trying to create updating feature. I'm getting all the values while editing but i'm not able to get the name of image which was uploaded while creating the post. How can I get the name of image instead of "No File Choosen"? I'm getting data from the backend in this format. setEditInitialState({ id: data.id, meta_title: data.meta_title, blog_name: data.blog_name, blog_category: { value: blogCategories.data?.data.find( (category) => category.id === data.blog_category )?.id || "", label: blogCategories.data?.data.find( (category) => category.id === data.blog_category )?.title || "", }, slug: data.slug, image: data.image, ##Here is the form <div className="form-group"> <label htmlFor="">Image</label> <Input type="file" // className="form-control" // value={values.image} name="image" onChange={(event: any) => setFieldValue("image", event.target?.files[0]) } /> {/* <p>{initialValues.image}</p> */} <FormikValidationError name="image" errors={errors} touched={touched} /> </div> -
How i change status code of jwt token exception while token is invalid or expired.?
I want to know , how i do update status code of jwt authorization while token is invalid vor expiried. -
How to display the results based on what the user search django
I have a web page that shows the details from the database, I have a search bar that will only search based on reception number and part number but whenever I enter the details, it will not display the row of the details in the form of a table. Example shown below: As seen from the URL it manage to show the search=the reception number, but the table still show the whole data that is from the database, instead of just showing the whole row of the data that the user search based on the reception number. How to make it display the data of what the user search based on reception number and part number in a form of a table? views.py @login_required(login_url='login') def gallery(request): search_post = request.GET.get('reception') search_partno = request.GET.get('partno') if search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) & Q(partno__icontains=search_partno)) else: allusername = Photo.objects.all().order_by("-Datetime") context = {'allusername': allusername} return render(request, 'photos/gallery.html', context) gallery.html {% extends "logisticbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <script> // Function to download table data into … -
Failed to load PDF File in Cypress
I am testing a react APP that can render PDF fine but as soon as I open it in Cypress, I get this error "Failed to load PDF File". This is an inconvenience because I am trying to test some part of the app that deals with the PDF. Any suggestions? -
Detecting import error when manage.py runserver on Django
I'm working on a project in Python 3.7.4 and Django 3.1.3 In the process of build and deployment, I want to send a notification by detecting an ImportError when running by manage.py runserver. For example, slack message or email. In manage.py, from django.core.management import ... execute_from_command_line(sys.argv) I twisted the import syntax of the views.py file and tried to try-except to the execute_from_command_line(), but I couldn't catch exception. The error is only appearing on the runserver console. Perhaps I think we should modify the utility.execute() within this execute_from_command_line() logic, which is a package modification, so I want to avoid this method. In utility.execute(), def execute(self): """ Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if no arguments were given. # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False) parser.add_argument('--settings') parser.add_argument('--pythonpath') parser.add_argument('args', nargs='*') # catch-all try: options, args = parser.parse_known_args(self.argv[2:]) handle_default_options(options) except CommandError: pass # Ignore any option errors at this point. …