Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return an html file as a response python django
This is my views file: from django.shortcuts import render from django.http import HttpResponse def hellothere(request): return render(request, "hello.html") # use forward slashes Everything is right, the name of the file is right, but for some reason django keeps saying that "the template could not be found". What reasons could there be that django couldn't find the template? This views.py file is in an app called "playground" and the hello.html file is in a folder in playground called "templates". Also, I've already tried adding the filepath to the DIRS attribute in the TEMPLATES array and I've tried using the exact and relative path of hello.html instead of just "hello.html", yet the problem still persists. -
Generate PDF's Pages with a background image
I'm generating a pdf with Django. This is the code def generar_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mi_archivo.pdf"' buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=letter) contenido = [ {"spaceBefore": 0, "spaceAfter": 15, "texto": "text 1", "tipo": 1, "negrita": False}, {"spaceBefore": 0, "spaceAfter": 0, "texto": "text 2", "tipo": 2, "negrita": False}, {"spaceBefore": 15, "spaceAfter": 15, "texto": "text 3", "tipo": 3, "negrita": False}, {"spaceBefore": 0, "spaceAfter": 0, "texto": "text 4", "tipo": 2, "negrita": False}, {"spaceBefore": 15, "spaceAfter": 0, "texto": "text 5", "tipo": 3, "negrita": False}, ... ] flowables = [] for item in contenido: parrafo = Paragraph(item['texto'], ParagraphStyle( name=name, fontName='Helvetica', fontSize=18, alignment=TA_LEFT, spaceBefore=item['spaceBefore'], spaceAfter=item['spaceAfter'] )) flowables.append(parrafo) doc.build(flowables) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response In this pdf, I need each page to have a background image. I tried using PageTemplate this way: frame = Frame(inch, inch, doc.width - 2 * inch, doc.height - 2 * inch) template = PageTemplate(id='background', frames=[frame], onPage=add_background) doc.addPageTemplates([template]) But it only apply in the first page, and no to the others.In addition, it reduces the size where the information is displayed but i don't know why. -
When i publish my Django CMS page with a ManyToManyField it's just be displayed in edit page
When i publish my Django CMS page with a ManyToManyField it's just be displayed in edit page. This is my model code: class ProductCarrossel(CMSPlugin): title = models.CharField( verbose_name='Título do Carrossel', max_length=150, null=True, blank=True, ) subtitle = HTMLField( verbose_name='Subtítulo do Carrossel', max_length=1000, help_text='Insira um subtítulo para o Carrossel', null=True, blank=True, default='', ) categories = models.ManyToManyField( Category, related_name="products_to_carrossel_by_category", blank=True, verbose_name='Selecione as Categorias desejadas', ) subcategories = models.ManyToManyField( Subcategory, related_name="products_to_carrossel_by_subcategory", blank=True, verbose_name='Selecione as Subategorias desejadas', ) text_color = models.CharField( max_length=30, choices=ColorClassesToTexts.choices, default=ColorClassesToTexts.AZUL, verbose_name='Somente os textos da capa', help_text='Selecione a cor dos textos', ) def __str__(self): return "{}{}".format(self.title, self.subtitle) class Meta: verbose_name = 'Carrossel de Produtos' verbose_name_plural = 'Carrossíes de Produtos' This is my CSM plugin code: @plugin_pool.register_plugin class ProductCarroselPlugin5(CMSPluginBase): module = 'Produto' name = '04 - Produtos - Carrossel de Produtos' model = ProductCarrossel render_template = "productapp/product_carrossel.html" allow_children = False def render(self, context, instance, placeholder): if instance.show_only == 'category': carrossel_products = Product.objects.filter( category__in=instance.categories.all(), productimage__isnull=False, # Apenas produtos que tenham imagem productprice__price__gt=0, # Apenas produtos com preço > 0 disp='disponivel' ).order_by('?')[:12] elif instance.show_only == 'subcategory': carrossel_products = Product.objects.filter( subcategory__id__in=instance.subcategories.all(), productimage__isnull=False, # Apenas produtos que tenham imagem productprice__price__gt=0, # Apenas produtos com preço > 0 disp='disponivel' ).order_by('?')[:12] for product in carrossel_products: #Pegando preço dos produtos … -
"Error Failed to load PDF document" in Django"
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. I relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I get "Error Failed to load PDF document" in my browser. Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage import docx import openai from pdf2docx import parse from docx2pdf import convert import time #remove # Create your views here. @csrf_protect def translateFile(request) : file = '' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path)) response = HttpResponse(file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response else: form = UploadFileForm() return render(request, 'translator_upload/upload.html', {'form': form}) def reConverter(inputDocxPath): return convert(inputDocxPath) def translateDocx(aDocx, stringOfDocPath): docx_file = stringOfDocPath myDoc = docx.Document(docx_file) #translation logic myDoc.save(stringOfDocPath) return reConverter(stringOfDocPath) #stringOfDocPath is used as convert() requires file path, not file object(myDoc) def converter(inputPdfPath): # convert pdf to docx pdf_file = inputPdfPath docx_file = inputPdfPath … -
Can we modify a django project from the front end?
I am making an open source suite of web apps using Django. Users can run it on their local servers, heroku, etc. I wish to enable the users to: Update the suite (i.e., the django project) to the latest version, and choose which apps in the project is to be installed. Importantly, I want the users to be able to do this from the front-end. How can I make this happen? -
Results are not limited on the page
I created a simple page in Django showing variety of pictures. <div class="container"> <div class="panel active" style="background-image: url('{% static 'home/test_business.jpg' %}')"> <h3>Business Session</h3> </div> <div class="panel" style="background-image: url('{% static 'home/test_molo.jpeg' %}')"> <h3>Relax</h3> </div> <div class="panel" style="background-image: url('{% static 'home/test_home_office.jpeg' %}')"> <h3>Home Office</h3> </div> <div class="panel" style="background-image: url('{% static 'home/stake.jpeg' %}')"> <h3>Foodporn</h3> </div> <div class="panel" style="background-image: url('{% static 'home/big_ben.jpg' %}')"> <h3>Traveling</h3> </div> </div> 4th and 5th element should be hidden when viewport is shrieked to 480 px so I provided this CSS code: .container { display: flex; width: 90vw; } .panel { background-size: auto 100%; background-position: center; background-repeat: no-repeat; height: 80vh; /* Rounded corners */ border-radius: 50px; color: white; flex: 0.5; margin: 10px; position: relative; transition: flex 0.7s ease-in; } .panel h3 { font-size: 24px; position: absolute; bottom: 20px; left: 20px; margin: 0; opacity: 0; } .panel.active { flex: 5; } .panel.active h3 { opacity: 1; } @media (max-width: 480px) { .container { width: 100vw; } .panel:nth-of-type(4), .panel:nth-of-type(5) { display: none; } } But when I change viewport to 480 px or 300... 4th and 5th element still appear. Does anyone know what is wrong with my code? -
static image wont load
my image wont load for my django project... inside my .html i have: {% load static %} <img src="{% static 'img/img1.jpg' %}" alt="My image"/> inside my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') DEBUG = True inside urls i added: ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I have to mention that in the html i already use static to import a js that works: <script src="{% static 'js/main.js' %}"></script> This works, while trying to display the image it wont work. Also the path in message it displays seems to be correct "GET /static/img/img1.jpg HTTP/1.1" 404 1896 Anyone have any clue why is it not loading in? Thanks -
How to pre-fill a form with Django?
I have a Django app with instances of restaurants. I want my users to be able to update restaurants. However, when a user gets to the update_restaurant.html form, i want the form to be pre-populated so that if the user only wants to edit one field, he doesn't need to re-fill all the other fields. I'm using crispy forms. restaurant_update.html: {% extends "base.html" %} {% load static %} {% block page_content %} {% load crispy_forms_tags %} <div class="container"> <h1> Update {{ restaurant.name|title }} </h1> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Update Restaurant" class="btn btn-primary"/> </form> </div> {% endblock %} forms.py: from django import forms from .models import Restaurant, Comment class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = ['name', 'description', 'address', 'image'] models.py: class Restaurant(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=1000) address = models.CharField(max_length=100, blank=True) image = CloudinaryField('image', null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.name views.py: def restaurant_update(request, pk): restaurant = get_object_or_404(Restaurant, pk=pk) if not restaurant.user_can_delete(request.user): return redirect('restaurant_detail', pk=pk) if request.method == 'POST': form = RestaurantForm(request.POST, request.FILES, instance=restaurant) if form.is_valid(): form.save() return redirect('restaurant_detail', pk=pk) else: form = RestaurantForm(instance=restaurant) context = { 'restaurant': restaurant, 'form': form } return render(request, 'restaurant_update.html', context) I … -
Tamplate does not work on html and it does not show any content
Hello My Tamplate in html does not work. It does not show an error but the homepage is white, there are not any content: The code: typ<!DOCTYPE html> <html> <body> {%block body%} {% endblock%} </body> </html>e here and my page where the content is : {% extends "hi/yes.html" %} {% block body %} <form> <input type="text" name="OK"> <input type="submit" name="O"> </form> <h1 id="ok">No</h1> {% endblock %} {% include "hi/yes.html" %} type here the Problem is that it does not work. If i were to do this in one html file it works but if I try to link them, it does not work. My path: A Html page with context (input with submit field) -
Django InconsistentMigrationHistory on first migration. Can't make migrations after initial migrations
I'm trying to use a custom user model with my django app. In settings.py: AUTH_USER_MODEL = 'sfauth.User' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', # These 3 are custom apps in a folder ROOT/api/apps/X (root = where manage.py is) 'api.apps.sfauth', # Contains the custom user model 'api.apps.admin', # Custom admin site 'api.apps.myapp', # Meat of the project (though managed=False for database for this) ] apps/admin/admin.py class SFAdminSite(AdminSite): """ Custom override for Django Admin page """ site_header = ADMIN_HEADER apps/admin/apps.py: class SFAdminConfig(apps.AdminConfig): default_site = 'api.apps.admin.admin.SFAdminSite' I can run the first makemigrations just fine. Migrations for 'myapp': api\api\apps\myapp\migrations\0001_initial.py - Create model User - Create model APIRequestLog But if I run it again, I get django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency sfauth.0001_initial on database 'default'. And trying to run the initial migration errors with django.db.utils.ProgrammingError: (1146, "Table 'django.sfauth_user' doesn't exist") I've tried commenting out my custom user model, making the migrations and migrating, then adding it back, which didn't work. I am ok with recreating the database and losing all data to fix this. -
How can I disable Django's csrf protection only in certain cases so that the sessionid and csrftoken won't display in the browser console?
I have developed a django app with some APIs now the requirement is that I should not allow the app to display the session_id and csrftoken being displayed in the browser. I have read the docs and other article on how to disable csrf on a view this I did that but still it appears in the browser see screenshot below. Thank you for your helps in advance. -
Chained dropdown not working properly in django
I basically created a chained dropdown with JS and Django but the thing is that it's not working properly, when i select a company in the dropdown it displays all the users but when i select it tells me "select an element of the list" when i click for the secod time it tells me "this field is required" and when i click for the third time it finaly prints me the user and the company but the thing is that i don't understan why i'm getting this behavior this is the view that I'm using class PruebaForm(forms.Form): company = company = forms.ModelChoiceField( queryset=CompanyInfo.objects.all(), ) user = forms.ModelChoiceField( queryset=UserLicense.objects.all(), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['user'].queryset = UserLicense.objects.none() if 'company' in self.data: try: company_id = self.data.get('company') self.fields["user"].queryset = UserLicense.objects.filter(company_id=company_id) except (ValueError, TypeError): pass def locationview(request): #print(args) if request.method == "POST": form = PruebaForm(request.POST) if form.is_valid(): print('########',form.cleaned_data["company"]) print('########',form.cleaned_data["user"]) else: (form.errors) else: form = PruebaForm() return render(request, 'template_de_prueba.html', {"form":form}) def load_users(request): company_id = request.GET.get('company_id') users = UserLicense.objects.filter(company_id=company_id) return render(request, 'users_dropdown_list_options.html', {'users': users}) this is my template where I'm calling the form {% extends "main_page_layout.dj.html" %} {% block content %} <form method="post" id="pruebaform" data-users-url="{% url 'load_users' %}">{% csrf_token %} {{ form.as_p }} … -
Getting "GET /user HTTP/1.1" 401 28 in django development server
When I login in my reactjs i get jwt token but at backend didn't recieve the token is empty it execute this part of code and after printing token token = request.COOKIES.get('jwt') None is printed why I am not getting the cooking in backend. since i got cookies in my browser after i login cookies:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NywiZXhwIjoxNjkzMjQ3NDA3LCJpYXQiOjE2OTMyNDM4MDd9.SPecH4BsNh76EjTHMoSDzWfaT8dt8KhnfNYKx8qQ0OU Django code print(token) if not token: print("dint get token") raise AuthenticationFailed('Unauthenticated') `class UserView(APIView): # permission_classes = [AllowAny] def get(self, request): token = request.COOKIES.get('jwt') print(token) if not token: print("dint get token") raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data)` reactjs code `import jwtDecode from 'jwt-decode'; import { useState,useEffect } from 'react'; const HomePage = () => { const [name, setName] = useState(''); useEffect(() => { ( async () => { const response = await fetch('http://127.0.0.1:8000/user', { headers: { 'Content-Type': 'application/json' }, credentials: 'include', }); if (response.ok) { const content = await response.json(); setName(content.name); console.log(name); const cookies = document.cookie; const token = cookies.split(';')[0].split('=')[1]; const decodedToken = jwtDecode(token); console.log(decodedToken); } else { console.log('Error fetching user data'); } } )(); }, [fetch]); return ( <div> <h1>hi {name}</h1> </div> ); }; export default HomePage;` ` django backend didn't … -
DoesNotExist at / No exception message supplied in Django
I'm encountering a DoesNotExist exception when using the provider_login_url template tag from the allauth library in my Django project. The issue occurs on the signup.html template in the section where I'm using this tag. Despite trying various solutions, I'm unable to resolve this error. Error Details: When I access the homepage of my Django application (http://127.0.0.1:8000/), I encounter a DoesNotExist exception with no specific exception message. The traceback points to the usage of the provider_login_url template tag on line 166 of the signup.html template. <body> <div class="background"> <div class="shape"></div> <div class="shape"></div> </div> <form method="POST"> {% csrf_token %} <h3>Signup Here</h3> <label for="username">Username</label> <input type="text" placeholder="Username" name="username" id="username"> <label for="email">Email</label> <input type="email" placeholder="Email or Phone" name="email" id="email"> <label for="password1">Password</label> <input type="password" placeholder="Password" id="password1" name="passwd"> <label for="password2">Confrom Password</label> <input type="password" placeholder="Confrom Password" id="password2" name="cpasswd"> <button type="submit">Signup</button> <a href="{% url 'login' %}" >i have already account</a> </form> 165 <h2>Google Account</h2> 166 <a href="{% provider_login_url 'google' %}?next=/">Login With Google</a> </body> Configuration Details: Django Version: 4.2.4 Python Version: 3.11.4 Installed Applications: django.contrib.auth django.contrib.sites allauth allauth.account allauth.socialaccount allauth.socialaccount.providers.google Steps Taken: Checked for extra whitespace around the provider_login_url template tag. Ensured proper configuration of the Google social application in Django admin. Verified the correctness of the Google API … -
Looking for a monorepo system to handle it all
I am currently working on X repositories. We would like to refine everything at work to use them within a monorepo. But here comes the point. The repositories include JavaScript (NodeJS, NextJs, ReactJs) [including TypeScript], a Django backend written in Python, and serverless functions. The JS parts are not the big problem. Here I use npm (we would change to pnpm) as package manager and VITE as bundler. My biggest problem is the Python part. We use pip currently and use a "requirement.txt" for the dependencies. I have already seen Nx and tried it. But the python plugin uses poetry . I can get it to work. But my boss doesn't want to switch to poetry unless it's absolutely necessary. Is there a monorepo that I can use without switching to poetry? Additionally, we want to upgrade to python 3.11. Otherwise there is a monorepo system which meets the requirements? Hours and hours of research -
why wont the template i am calling show up when i set my form to "crispy"
i have a django project with a login page i have called register.html i have created a directory in my project called users and keeping with django another directory named users and a sub-directory template->users->register: my_project/ ├── my_project/ │ ├── ... │ ├── users/ │ ├── templates/ │ │ ├── users/ │ │ │ ├── register.html │ └── ... the code for the page is as follow: {% load crispy_forms_tags %} <!DOCTYPE html> <html> <head> <meta name="description" content="Welcome to our text messaging campaigning website"> <title>R&D Texting</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>hi</h1> </header> <div class="content-section"> <form method="POST"> {% comment %} Do not remove the csrf token! {% endcomment %} {% csrf_token %} <fieldset class = "form-group"> <legend class ="border-bottom mb-4">Join today</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already have an account?<a class ="ml-2" href="#">Sign in</a>" </small> </div> </div> </body> </html> when i run this code(with the proper urls and paths etc) i get a 404 page saying it cant find the template when i remove the "|crispy" everything runs fine. my rendering request form views etc seem to be find however the crispy template cant be found(i have made sure … -
uploading an image api in django return null
my models class Slider(models.Model): image = models.ImageField(upload_to="images/") description = models.TextField() my views class UploadImage(viewsets.ModelViewSet): queryset = Slider.objects.all() serializer_class = SliderSerializer parser_classes = (MultiPartParser, FormParser) def perform_create(self, request, *args, **kwargs): try: file = request.data["image"] title = request.data['description'] except KeyError: raise ParseError('Request has no resource file attached') Slider.objects.create(image=file, description=title) serializers class SliderSerializer(serializers.ModelSerializer): class Meta: model = Slider fields = '__all__' urls urlpatterns = [ path('api/upload', views.UploadImage.as_view({'post': 'create'}), name='home') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) json Hello I Wrote an API for uploading image in Django but unfortunately it didn't work and when I upload an image it return null and I don't know why. I appreciate if you help me. Thank you. -
How to add an editable field in the django admin that is not directly linked to a model field?
How to add a custom editable field in the django admin and then transform it before storing it in a field in the model? Given this Model: import json from django.db import models from django.core.serializers.json import DjangoJSONEncoder class Foo(models.Model): _encrypted_data = models.TextField(null=True, blank=True) @property def data(self): encrypted = self._encrypted_data if not encrypted: return {} return json.loads(decrypt(encrypted)) @data.setter def data(self, value): if not value: self._encrypted_data = {} return self._encrypted_data = encrypt( json.dumps(value, cls=DjangoJSONEncoder) ) The field Model._encrypted_data contains encrypted data. The property Model.data makes it easy to work with the decrypted data in the code: encrypt/decrypt automatically. I am looking for an editable admin field that represents the Model.data property. I started to explore a custom Admin Form but I am not sure how to pass the decrypted data to the field and then save it on the model. class FooAdminForm(forms.ModelForm): class Meta: model = Foo fields = '__all__' data = forms.JSONField(label='Data', required=False) class FooAdmin(admin.ModelAdmin): form = FooAdminForm -
FileField in Django does not send file to its form request
I have a Django form where I upload an image through an input type file. class Form(forms.Form): photo = forms.FileField( label="Photo", widget=forms.FileInput( attrs={ 'class': 'form-control', } ) ) I wrote the next view: def upload(request): context = {} if 'photo' in request.POST: form = Form(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES["photo"]) else: print(form.errors) else: form = Form() context['form'] = form return render(request, 'app/upload.html', context) def handle_uploaded_file(file): with open('app/upload/'+file.name, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) When I send the form the request does not recieve any file, even if I loaded a file before. I am able to show by javascript jpeg files loaded when the field has changed. So the field is loading files but is not sending theme in the request. Form does not check the validation form.is_valid(): it says it is required even when I have uploaded a file .jpeg Error shown in print(form.errors): <ul class="errorlist"><li>photo<ul class="errorlist"><li>This field is required.</li></ul></li></ul> I leave my template form here: <form action="" method="post" id="search_face_form" style="width: 100%;"> {% csrf_token %} <div class="row"> <div class="col-sm-4"> <div class="input-group-sm mb-4"> <label for="floatingInput">Archivo de búsqueda</label> {{ search_form.face }} {{ search_form.face.errors }} </div> </div> <div class="col-sm-6"> <img id="search_face_img" src="{% static 'cameras_admin/img/not_found.jpg' %}" style="display: none; max-height: 25vh;"> </div> <div … -
Confirming the Updated User Email address in Django with a Boolean
Am creating profile Update. It works fine and l can change the Username and the Email. But l would like to confirm the New submitted email by sending an otp or a verification link , so that a user can verify that email. I have been looking for the solution of doing it but l just found one post on Stackoverflow, whereby someone is suggesting that you can deactivate the user and send a confirmation email and then activate him or her again But am asking; ls it possible to create a model with a Boolean field and connect that model to a User model, so that l can set that Boolean field to send a verification code to User who changed his or her email Address? email_comfirm.py #email comfirm model class EmailComfirm(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) is_comfirmed=models.BooleanField(default=True) active_otp=models.CharField(max_lenght=8) If possible; How can l phrase that model and it's function? I would like to call that Boolean to check if the email is changed, and if changed, turns off or set false and process the verification link after confirming the email it sets true. is_comfirmed() = False Secondly; How am l going to confirm that email? To me l would like to … -
My test fails due to sending an invalid file
Initially I will show you my action in my view: def add_photo_to_object(self, request, object_id, pk=None): uploaded_file = request.data.get('image') print(uploaded_file.size) request.data['user_owner'] = request.user.id print(request.data) serializer = self.action_serializers['add_photo_to_object'](data=request.data) serializer.is_valid(raise_exception=True) serializer.save() ... The results of these prints are - 0 and <QueryDict: {'name': ['small'], 'image': [<InMemoryUploadedFile: mock_image.jpg (image/jpg)>], 'user_owner': [1]}> My test looks like this: def test_add_photo_to_object(authorized_client, objects): checkpoint = objects[0] questionnaire = checkpoint.element.first() url = reverse('checkpoint-add-photo-to-object', kwargs={'pk': checkpoint.id, 'object_id': object.id}) uploaded = SimpleUploadedFile('mock_image.jpg', b'mock_content' * 1000, content_type='image/jpg') photo_data = {"name": "small", "image":uploaded} response = authorized_client.post(url, data=photo_data, format='multipart') response_data = response.json() assert response.status_code == status.HTTP_201_CREATED, response_data Well I always end up getting the error that AssertionError: {'image': ['Sent file is empty.']}. Please advise me how to avoid this error and Mock image such send. I can't use Pillow or store the test image on the server -
--headless vs --headless=chrome vs --headless=new in Selenium
I'm learning Selenium with Django and Google Chrome. *I use Selenium 4.11.2. Then, I tested with --headless, --headless=chrome and --headless=new as shown below, then all work properly: from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless=chrome") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless=new") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title My questions: What is the difference between --headless, --headless=chrome and --headless=new? Which should I use, --headless, --headless=chrome or --headless=new? -
How to insert placeholder in Django Admin text input
I've tried three methods, first as described in how-to-add-placeholder-text-to-a-django-admin-field and in the docs from django import forms class AppointmentAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): kwargs['widgets'] = { 'name': forms.TextInput(attrs={'placeholder': 'Type here'}) } return super().get_form(request, obj, **kwargs) Then the method described in django-add-placeholder-text-to-form-field, slightly altered to get around Python errors. class AppointmentAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields['customer'].widget.attrs["placeholder"] = "Type here" return form Finally, using formfield_overrides: class AppointmentAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: { "widget":forms.TextInput(attrs={'placeholder':'Type here'})}, } None of these are working. I must be overlooking something simple? The relevant portion of models.py: class Appointment(models.Model): customer = models.ForeignKey(Customer, blank=False, null=True, default=None, on_delete=models.CASCADE, related_name='appointments') -
how to write test in django to check code fallback behavior to the database from redis corectly?
I have a python-django code. the code take inscode as input and check the redis and return blong data. in case redis is down or no data in it code fallback to database and read data from there. then i write integration test for this code in pytest check behave of the code in multiple cases on of the cases is that i want to mock redis and raise an error to disable it and see code can fallback to database and return data and in end return data should assert equal with data i got from redis before. main code: class GetOrderBook(APIView): def get(self, request, format=None): # get parameters inscode = None if 'i' in request.GET: inscode = request.GET['i'] if inscode != None: try: #raise ('disabling redis!') r_handle = redis.Redis( redis connection) data = r_handle.get(inscode) if data != None: return Response(json.loads(data)) else: print('GetOrderBook: data not found in cache') except BaseException as err: print(err) orderbook = OrderBook.objects.filter( symbol__inscode=inscode).order_by('rownum') if len(orderbook) > 0: data = OrderBookSer(orderbook, many=True).data data_formatted = # here making bnew format for row in data: # new format return Response(data_formatted) else: return Response({'Bad Request': 'invalid input'}) return Response({'Bad Request': 'incomplete input data'},) and this is test for part … -
SSO authentication not working on cross-domain requests
I am trying to enable SSO on my website. The backend is on Django hosted on a different domain and frontend is on React on a different domain. The backend is making Djoser package to handle social authentication. The sessionId which I receive in the form set-cookie header is not getting saved in browser cookies even though Access-Control-Allow-Credentials is true due to which SSO is failing. The same is working if my backend and frontend are on the same domain. Is there any solution to this? I am expecting SSO authentication on cross domain architecture but it is failing because session Id is not getting saved in browser cookies even though Access-Control-Allow-Credentials were enabled.