Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
changes made in django frontend is not working
I am trying to use a sefaria project : https://github.com/Sefaria/Sefaria-Project i have ran the project locally and when I tried to change the logo and some text in Header.jsx under static/js folder, desired result is not showing on browser. I am guessing its because of django caching that they put in place. If you guys have any idea, how to figure it, plz let me know. const headerContent = ( <> <div className="headerNavSection"> { Sefaria._siteSettings.TORAH_SPECIFIC ? <a className="home" href="/" >{logo}</a> : null } <a href="/texts" className="textLink"><InterfaceText context="Header">Textss</InterfaceText></a> <a href="/topics" className="textLink"><InterfaceText>Topicss</InterfaceText></a> <a href="/community" className="textLink"><InterfaceText>Communityss</InterfaceText></a> <DonateLink classes={"textLink donate"} source={"Header"}><InterfaceText>Donate</InterfaceText></DonateLink> </div> -
Django - setting up Server-sent Events with Channels: Unhandled Exception: SseConsumer() missing 2 required positional arguments: 'receive' and 'send'
I have an existing Django Channels setup that is working with websockets and I have to add another endpoint to support SSE. I'm following an example from here https://channels.readthedocs.io/en/stable/topics/consumers.html to set up a consumer using AsyncHttpConsumer and I've been getting an error: TypeError: ServerSentEventsConsumer() missing 2 required positional arguments: 'receive' and 'send' My setup is as follows: playground/consumers.py from datetime import datetime from channels.generic.http import AsyncHttpConsumer class ServerSentEventsConsumer(AsyncHttpConsumer): async def handle(self, body): await self.send_headers(headers=[ (b"Cache-Control", b"no-cache"), (b"Content-Type", b"text/event-stream"), (b"Transfer-Encoding", b"chunked"), ]) while True: payload = "data: %s\n\n" % datetime.now().isoformat() await self.send_body(payload.encode("utf-8"), more_body=True) await asyncio.sleep(1) playground/asgi.py import os import django from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'playground.settings.production') django.setup() application = get_asgi_application() playground/routing.py from playground.asgi import application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from .consumers import ( BaseConsumer, ServerSentEventsConsumer, ) from django.urls import path, re_path application = ProtocolTypeRouter( { "http": application, "websocket": AllowedHostsOriginValidator( JwtAuthMiddlewareStack( URLRouter( [ re_path(r"^wss$", BaseConsumer), re_path("sse", ServerSentEventsConsumer.as_asgi()) # <- Desperate attempt. I don't wanna use websockets. ] ) ) ), } ) playground/urls.py urlpatterns = [ path("sse/", ServerSentEventsConsumer.as_asgi(), name="sse") ] I am using the following software versions: asgiref = "3.7.2" Django = "4.0.10" channels-redis = "4.1.0" channels = "4.0.0" I've seen some related issues where people resolved … -
Extending Django model
I have two apps in my project, app1 and app2. In app1 I have two models called Task and Job. I want to add new feature to these two models, I want to add category to them. But its more complicated then just a new field and app2 is mainly responsible for estimation of the category, so I created new model in the app2 as below: class Category(models.Model): CAT1 = 1 CAT2 = 2 OTHER = 6 UNKNOWN = 7 CATEGORY_CHOICES = ( (CAT1, "Cat1"), (CAT2, "Cat2"), (OTHER, "Other"), (UNKNOWN, "Unknown"), ) auto_category = models.PositiveSmallIntegerField(choices=CATEGORY_CHOICES, default=UNKNOWN) user_category = models.PositiveSmallIntegerField(choices=CATEGORY_CHOICES, default=UNKNOWN) modify_timestamp = models.DateTimeField(blank=True, null=True) modified_by = models.ForeignKey("app1.User", on_delete=models.PROTECT, related_name='category_creator', blank=True, null=True) Also I want every Task and Job object to have a default category as soon as it is created so I don't have to deal with None values on the frontend, "Unknown" value should be a default value so I created below function in app2/utils.py: def create_default_category(): new_category = Category.objects.create() return new_category.pk And then I added OneToOneField relation to my Task and Job models in the app1 as well as default value: class Task(models.Model): # Some already existing fields category = models.OneToOneField('app2.Category', on_delete=models.CASCADE, related_name='task_category', default=create_default_category) class Job(models.Model): # Some … -
Blocked 'frame-ancestors'
I have set CSP_FRAME_ANCESTORS = ("*", ) in my Django application. But still, I am seeing Blocked 'frame-ancestors' in logs. Am I missing something here? -
How to resolve graphene DjangoFilterConnectionField?
I have below queries in my graphene API list, class Query(UserQuery, graphene.ObjectType): all_users = DjangoFilterConnectionField( UserType, filterset_class=UserFilter) all_leagues = DjangoFilterConnectionField( LeagueType, filterset_class=LeagueFilter) For these connections fields I need to apply @login_required style permission. I found that I need to resolve these api endpoints in order to apply those. @login_required def resolve_all_users(self, info): #code But I don't know what to return from the above method? There is a model called Users and ideally all records from that model needs to be returned. But when I apply filter on first, last, before, after, I get below error, "message": "Query.resolve_all_users() got an unexpected keyword argument 'first'" Please advise. -
Invalidate Django cached_property in signal handler without introducing unnecessary queries
Let's say I have the following Django models: class Team(models.Model): users = models.ManyToManyField(User, through="TeamUser") @cached_property def total_points(self): return self.teamuser_set.aggregate(models.Sum("points"))["points__sum"] or 0 class TeamUser(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) points = models.IntegerField() I want to create a signal handler that will invalidate the team.total_points cache when TeamUser object is created/updated/deleted. I started with the following signal handler. Note the Django docs recommended the del instance.prop call. @receiver(post_save, sender=models.TeamUser) @receiver(post_delete, sender=models.TeamUser) def invalidate_cache(**kwargs): try: del kwargs["instance"].team.total_points except AttributeError: pass And some tests. Note I'm using pytest-django. def test_create_team_users(django_assert_num_queries): user = factories.UserFactory() team = factories.TeamFactory() assert team.total_points == 0 with django_assert_num_queries(1): TeamUser.objects.create(team=team, user=user, points=2) assert team.total_points == 2 with django_assert_num_queries(1): TeamUser.objects.create(team=team, user=user, points=3) assert team.total_points == 5 def test_delete_all_team_users(django_assert_num_queries): user = factories.UserFactory() team = factories.TeamFactory() for _ in range(10): TeamUser.objects.create(team=team, user=user, points=2) with django_assert_num_queries(2): TeamUser.objects.all().delete() assert team.total_points == 0 The test_create_team_users test passed but the test_delete_all_team_users test failed because the query count is 12 instead of 2. Yikes! Looks like an N+1 query. To prevent this, I updated my signal handler to only invalidate the team.total_points cache if the user object is cached on the TeamUser object. I found the is_cached method in this SO answer. @receiver(post_save, sender=models.TeamUser) @receiver(post_delete, sender=models.TeamUser) … -
executing async task or background task in a Django service running on GCP Cloud run
I'm building a Django application and planning to deploy it on Cloud Run. I have used celery before, but it seems too complicated to set it up with Cloud Run. After some exploration, I found Cloud Task and Cloud Scheduler. My understanding is I can use Cloud Scheduler to init HTTP requests to my cloud run service periodically and use Cloud Task as a queue to send HTTP requests on demand. So my question is what's the best practice to deploy my service? For the easiness of development, I see I can only have one Django repo docker and deploy that to a single cloud run service. Then all the regular requests and all async/background requests will go to the same service(the task execute endpoints will also be public). Another way is to deploy a second cloud run service using the same docker, but hide that in vpc network. Is there a good reason to do the second one instead? (If cloud run scales itself, isn't that cost the same?) I looked at https://cloud.google.com/run/docs/authenticating/service-to-service, There is service to service authentication, but wonder did anyone implemented the Django level permission auth on task endpoints? can i use my service jwt instead … -
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