Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at / .Reverse for ‘login’ not found. ‘login’ is not a valid view function or pattern name
I'm currently building a website using Django and have some issues, can someone please help me with this. Here is my urls.py file: from django.urls import path, include from . import views import sys app_name = "myapp" urlpatterns = [ path('', views.index, name='index'), path('register', views.register, name='register'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('wordsearch', views.wordsearch, name='wordsearch'), path('generate', views.generate, name="generate") ] and my views.py: from django.shortcuts import render, redirect # redirect: chuyen huong user toi page khac from django.contrib.auth.models import User, auth from django.contrib import messages from django.http import HttpResponse from .models import Feature from myproject.main import * from django.contrib.auth.forms import UserCreationForm, AuthenticationForm # Create your views here. # gửi request tới thư mục templates để tìm file index.html def index(request): # dictionary return render(request, 'login.html') # log in and sign up function def register(request): # check if the page is rendered with a post method if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() # log the user in return redirect('login') else: form = UserCreationForm() return render(request, 'register.html', {'form': form}) def login(request): if request.method == "POST": form = AuthenticationForm(data = request.POST) if form.is_valid(): return redirect('wordsearch') else: form = AuthenticationForm() return render(request, 'login.html', {'form': form}) # log out def logout(request): auth.logout(request) … -
Desperate for help: Django sessions failing intermittently
I’m in desperate need of some Django help. I wrote an app last year for a community event I run, called Nashville Tabletop Day. The app allows people to scan QR codes to interact with games they can play during the day. Locally it runs great. However when I push it to Fly.io it runs, but reliably drops sessions. By that I mean I can log in, browse to a page or two, and then the session just vanishes. It even happens if I stay on the same page and just reload a few times. It doesn’t happen immediately, or I’d think perhaps the database was the issue. But after 15-30 seconds, or a few page loads—poof. The event is this coming Saturday and this app has to be ready go. I’m tempted to think it could be a config issue, but this app ran last year, almost flawlessly and I’ve only made a few small updates this year. Django 4.1.7 Python 3.8.18 Database is SQLite INSTALLED_APPS = [ 'ntd.apps.NtdConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'ntd.middleware.request_logger.RequestLoggerMiddleware', ] Some debugging I’ve done: I added a simple logging … -
created a templete folder that includes a nav bar.html but it is not showing up on the browser. i keep getting templete does not exist
nav bar is not showing and giving this error TemplateDoesNotExist at /navbar/ in the browser. i have created a folder and put in the nav bar as shown in the screenshot provided. if anyone can tell me the error. Is it because of the layout of my folders? wanted the nav bar to show up -
Djano form no populating with user instance
I'm very new to Django, and I am working on my very first project. I am trying get a model form to populate with the user instance. I have been struggling to find out when when I load the form it doesn't populate with the user instance. The form also doesn't update my model. Here is the model: class Income(models.Model): class Type(models.TextChoices): SALARY = 'Sal', 'Salary' VARIABLE = 'Var', 'Variable' class PayFrequency(models.TextChoices): MONTHLY = 'MON', 'Monthly' BIWEEKLY = 'BW', 'Bi-weekly' SEMIMONTHLY = 'SM', 'Semimonthly' WEEKLY = 'W', 'Weekly' ANNUAL = 'AN', 'Annually' user = models.OneToOneField( User, on_delete=models.PROTECT, primary_key=True, ) pay_amount = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) type = models.CharField(max_length=3, choices=Type.choices) frequency = models.CharField(max_length=3, choices=PayFrequency.choices) #Need day of the month, to calculate weekly, bi-weekly and monthly pay days pay_date_one = models.IntegerField( validators=[MaxValueValidator(31), MinValueValidator(1)] ) #Need second date to calculate semi monthly(2x a month, so need both dates) pay_date_two = models.IntegerField( validators=[MaxValueValidator(28), MinValueValidator(1)], null=True, blank=True ) def __str__(self): return f"{self.user} Income" Here is view: @login_required() def income(request): if request.method == "POST": form = IncomeForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: form = IncomeForm(instance=request.user) return render(request, 'home/income.html', { "form": form }) Here is the template: {% extends "layout.html" %} {% block title %} Income {% … -
django permission using UserPassesTestMixin
I tried to use the user.has_perm() method, but it always returns False. def test_func(self): # Define your custom access control logic here user = self.request.user return user.is_authenticated and user.has_perm('CreateGroup.add_group') -
How do I override the delete() method in Django's DeleteView to send a success message?
I'm using Django 5.0.3. I have a job listings app, with a DeleteListingView. I want to override the delete() method, so that I can use messages.success() to send a message to the success url's template once a listing is deleted. However, the delete() method isn't being overridden. A listing gets deleted, and I'm redirected to the correct url, but the message isn't sent. I've even tried to add a print() statement inside delete() to see if it appears in cmd, but it doesn't. from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from django.urls import reverse_lazy from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from .models import Listings class ListingsListView(ListView): model = Listings template_name = 'listings/listings_list.html' context_object_name = 'listings' class DeleteListingView(LoginRequiredMixin, DeleteView): model = Listings template_name = 'listings/listing_delete.html' context_object_name = 'listing' success_url = reverse_lazy('listings') def delete(self, request, *args, **kwargs): listing = self.get_object() listing_title = listing.job_title messages.success(self.request, f"Listing titled '{listing_title}' was deleted successfully.") print(f"delete() has been overridden successfully.") # To appear in cmd return super().delete(request, *args, **kwargs) and in listings_list.html template: {% for message in messages %} <p> {{ message }}</p> {% endfor %} Nothing I've tried is working, and I can't seem to find a solution anywhere. What … -
Django Paginating and order_by at the same time
class QueryLists(LoginRequiredMixin, ListView): paginate_by=4 def get_queryset(self): queryset=super().get_queryset() queryset=queryset.filter(user=self.request.user) search_filter=self.request.GET.get("search-area") if search_filter: queryset=queryset.filter(name__icontains=search_filter) order_filter=self.request.GET.get("order-by") if order_filter: queryset=queryset.order_by(order_filter) return queryset def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) get_copy=self.request.GET.copy() if 'page' in get_copy: print("hello") get_copy.pop('page') context['get_copy']=urlencode(get_copy) return context I write this code and the url doesn't pop the page when I go to other page for second or third time like this /?page=1&page=2 I want the page appears only once. How can I solve this? -
Can't retrieve cookies with document.cookie (returns empty string)
I am currently trying to build a Django backend with a React frontend. But I have a problem with my cookies (specifically the csrftoken). I think the problem is that I can't get the cookie with document.cookie in the console or in javascript with Cookies.get() although the cookies are shown in chrome: enter image description here This is the response when trying to retrieve the cookies: enter image description here What is the problem? Now the httponly tag is already not set like in the image and the samesite attribute is also set to none, so that cant be the problem. -
Unable to connect two Django models
I'm building a forum website and I have the following models: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile', null=True, blank=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) football_club = models.CharField(max_length=100) location = models.CharField(max_length=100, blank=True) class CustomUser(AbstractBaseUser, PermissionsMixin): userprofile = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='user_profile', null=True, blank=True) username = models.CharField(max_length=150, unique=True) email = models.EmailField(unique=True, null=False) created_at = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) post_count = models.PositiveIntegerField(default=0) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.username The CustomUser fields are entered during the sign-up, while the Profile fields are supposed to be optionally edited on the /profile page of the website. The forms for both models are represented as {{ form.as_p }} inside the corresponding html files. Both forms are setup inside the forms.py file: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser, Profile class SignUpForm(UserCreationForm): class Meta: model = CustomUser fields = ['username', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['avatar', 'football_club', 'location'] And I have the following function/class inside my views.py file: class SignUpView(CreateView): form_class = SignUpForm template_name = 'accounts/signup.html' success_url = reverse_lazy('login')) @login_required def profile(request): profile = request.user.userprofile print("Profile: ", profile) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=profile) if … -
Django - Pagination doesn't work for the last page
In my website I want to showcase the wines with pagination, 9 pages per page (let's assume we have 22 wines). The wines are stored in the admin interface, each wine with fields like name, type, description and ImageField for uploading their respective images. However, when I click on the third(last) page, the following page is showing: ValueError at /page-name/ The 'image' attribute has no file associated with it. Request Method: GET Request URL: http://localhost/page-name/?page=3 Django Version: 5.0.4 Exception Type: ValueError Exception Value: The 'image' attribute has no file associated with it. Exception Location: [path].venv\Lib\site-packages\django\db\models\fields\files.py, line 41, in _require_file Raised during: [app-name].views.wines_page_red And in the console, I get this warning: TypeError: 'ImageFieldFile' object is not subscriptable ..and bunch of exceptions. I'm new to Django and I don't understand what can cause an issue, as all the images for the respective items are uploaded. Read somewhere that the method I used for pagination can be unstable, so I tried to order the wines by their name, and now the 2nd page gave the same errord. Here is the view, url part and the template: View: def wines_page_red(request): red_wines_list = Wine.objects.filter(type='Red') paginator = Paginator(red_wines_list, 9) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return … -
Django formview problem, cant add form to detail view
i have a problem with setup detail view and form view classes in django,when i try to hit send button in my exam form django throw this error: AttributeError: 'TestDetails' object has no attribute 'object' class TestDetails(DetailView, FormView): model = Test form_class = QuestionForm context_object_name = 'test' pk_url_kwarg = 'test_id' template_name = 'app/views/test_details.html' def get_context_data(self, **kwargs): test_id = self.kwargs.get('test_id') context = super().get_context_data(**kwargs) context['title'] = f'Тест - {test_id}' context['questions'] = Question.objects.filter(test_id=test_id) return context def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) def form_invalid(self, form): print(form.cleaned_data) return super().form_invalid(form) Actually, i dont know to solve this problem -
How to compose Django template snippets with Alpine.js to create reusable server-rendered components?
In short, what I’m struggling to achieve is creating a reusable Alpine component with its children defined in a Django template snippet. Example with code that doesn’t work as intended — Carousel I have this template structure: cities_page.html (template) / city.html (snippet) / carousel.html (snippet + Alpine) / carousel_item.html (snippet). cities_page renders many cities and each carousel renders many carousel_items. All rendering happens server-side. cities_page.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Cities Page</title> <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.13.7/dist/cdn.min.js"></script> </head> <body> {% for city in cities %} {% include "myapp/snippets/city.html" with city=city %} {% endfor %} </body> </html> city.html <div> <h2>{{ city.name }}</h2> {% include "myapp/snippets/carousel.html" with images=city.images %} </div> carousel.html <div x-data="carousel"> <template x-for="item in items" :key="item"> <div x-html="item.itemHtml"></div> </template> </div> <script> document.addEventListener('alpine:init', () => { Alpine.data(`carousel`, () => ({ items: [ {% for image in images %} { itemHtml: `{% include "myapp/snippets/carousel_item.html" with image=image %}`, }, {% endfor %} ] })); }); </script> carousel_item.html <p> Item: {{ image }} </p> views.py def cities_page(request): context = { "cities": [ { "name": "London", "images": ["london1.jpg", "london2.jpg", "london3.jpg"] }, { "name": "Paris", "images": ["paris1.jpg", "paris2.jpg", "paris3.jpg"] }, ] } return render(request, "myapp/cities_page.html", context=context) The reason why I want Alpine manage my carousel items … -
AWS EC2 Server not serving some pages and static files propperly
I just Deployed a website on AWS EC2 from github clone. When i visit to Influencer Marketing & Career pages the server serving the static files from S3 Bucket correctly. But when i am visiting my home page & Who are We pages its not serving the static files also i am not getting these pages contents (raw data). I assume that its not serving static files its ok but where is the content of both pages gone. What i am missing here. I am new to AWS and Website deployment So if i did any mistake please let me now i will correct it. If you require any additional information i will add it. Configure Nginx to Proxy Pass to Gunicorn [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/try-django-digital-marketing/try-django-digital-marketing ExecStart=/home/ubuntu/try-django-digital-marketing/try-django-digital-marketing/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ BE.wsgi:application server { listen 80; server_name 3.17.142.65; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Bucket Policy, Cross-origin resource sharing (CORS) & User Policy { "Version": "2008-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::try-marketing/*" } ] … -
Django-formwizard with dynamically generated Formset not submitting
I'm trying to get django-formwizard to work with dynamically generated formset of the users' input in the first form. The forms render and initial data shows up fine, but when I try to submit the 2nd form, I get it back without errors and I do not proceed to the done() method. My forms: class MenuInputForm(forms.Form): content = forms.CharField() class DayMenuForm(forms.Form): menu = forms.CharField() DayMenuFormSet = formset_factory(form=DayMenuForm, min_num=1, extra=0) My views: class MenuAddWizard(LoginRequiredMixin, SessionWizardView): # Either provide form_list as part of .as_view() in urls, or here. # Note: DayMenuFormSet is overwritten in get_form() form_list = [MenuInputForm, DayMenuFormSet] template_name = "menu_add.html" def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) # Determine the step if not given if step is None: step = self.steps.current if step == '1': step_0_cleaned_data = self.get_cleaned_data_for_step('0') # Using step 0 data, I generate the list to be used for initial; removing logic for brevity and using two example items as test DayMenuFormSet = formset_factory(form=DayMenuForm, extra=0) formset = DayMenuFormSet(initial=[{'menu': 'Some example menu'}, {'menu': 'This is some other example text'}]) form = formset return form def done(self, form_list, **kwargs): # This code is never reached pass Template: <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% … -
GraphQLResolveInfo' object has no attribute 'field_asts'"
So I am using graphene-django==3.1.2, which didn't let me importfrom graphql import ResolveInfo . Therefore, I used from graphql import GraphQLResolveInfo as ResolveInfo However the error I see now is - GraphQLResolveInfo' object has no attribute 'field_asts' Am I using the right equivalent of ResolveInfo? -
Object of type 'TypeError' is not JSON serializable added code receives same error message
I am using django and pymongo to code a flashcard app I am using csv files on mongodb compass. I have seen this error posted before however, when I tried to fix it I get the same error from the server here is my code below. when i google this error code to fix it also does not fix the error. views.py import json from django.views.generic import ListView from django.shortcuts import render from .models import Card, myapp_collection from django.http import HttpResponse class CardListView(ListView): model = Card queryset = Card.objects.all().order_by('box', '-date_created') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Prepare flashcards data from MongoDB for template flashcards_data = [...] # Replace [...] with the processed flashcards data flashcards_json = json.dumps(flashcards_data) context['flashcards_json'] = flashcards_json return context models.py # cards/models.py from django.db import models from .db_con import db myapp_collection = db["myapp"] NUM_BOXES = 5 BOXES = range(1, NUM_BOXES + 1) class Card(models.Model): question = models.CharField(max_length=100) answer = models.CharField(max_length=100) box = models.IntegerField( choices=zip(BOXES, BOXES), default=BOXES[0], ) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question card_list.html <!-- cards/templates/myapp/base.html --> {% extends "cards/base.html" %} <!DOCTYPE html> <html lang="en"> <head> <title>Flashcards</title> </head> <body> <header> <h1>Flashcards App</h1> </header> <main> {% block content %} <h2>Welcome to your Flashcards app!</h2> {% endblock … -
Not able to serve the static and media files of django in AWS instance
While deploying a django project to AWS instance , not able to load or serve the static and media files ! , how to configure it with nginx ? and the settings.py How i can successfully serve the static and mediafiles ? Along with django -
Django cors headers doesn't work with django channels
I have a project in django and when I added django channels my cors stopped working correctly # settings.py ... ... ... DEBUG = True ALLOWED_HOSTS = ['localhost'] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CSRF_TRUSTED_ORIGINS =[ "http://localhost:3000", ] CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = [ 'corsheaders', ... 'channels', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] ... ... ... ... WSGI_APPLICATION = 'config.wsgi.application' ASGI_APPLICATION = 'config.asgi.application' # routing from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from django.core.asgi import get_asgi_application websocket_urlpatterns = [ ] application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': URLRouter( websocket_urlpatterns ), }) Error in browser is: Access to XMLHttpRequest at 'http://localhost:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. And when I remove ASGI_APPLICATION from settings file and channels from APPS list then cors works. Whyy? This is my versions: channels==3.0.4 Django==4.0.0 django-cors-headers==4.0.0 I tried to add my own middleware to the top of the list def open_access_middleware(get_response): def middleware(request): response = get_response(request) print('Test') response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Headers"] = "*" return response return middleware but it still not working. -
Issue sending messages to a channel group in Django
Im sat up a system with a user, member and team models. What i am trying to achieve with sockets, it for one of the team members to notify everyone on the team about an achievement. Clientside: Svelte 4.2.7 API: Django 4.2.11 Channels 4.1.0 Just to test out the socket logic, in the frontend, when i connect, i send a test message to the server: function createWebSocket() { const { subscribe, set } = writable(undefined); return { subscribe, connect() { const gameSocket: WebSocket = new WebSocket('ws://' + "localhost:8000" + '/ws/game/'); gameSocket.onmessage = (e) => { const data = JSON.parse(e.data); const message = data['message']; console.log("socket message", message); }; gameSocket.onclose = (e) => { console.log("socket closed unexpectedly"); console.log(e); }; gameSocket.onopen = () => { console.log("socket connected"); this.sendMessage("Test hello!") } set(gameSocket); }, sendMessage: (message: any) => { subscribe((gameSocket) => { if (gameSocket !== null) { gameSocket.send(JSON.stringify({ 'message': message })); } })(); } }; } export const gameSocket = createWebSocket(); In django i connected to redis: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", 'CONFIG': { "hosts": [('127.0.0.1', 6379)] } } } my asgi.py: import os import game.routing from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'game.settings') application = … -
I want to send updated color picker information back to django view each time colour picked before form is submitted
Using HTMX with Alpine.js. trying to get dynamic update from 'color' each time a colour is clicked on the colour picker before form is submitted, I want to send the updated value back to the view function. Undersatnd using htmx.process() is the recognised way to look for changes to content that is added to the DOM outside of the normal htmx request cycle but still want htmx attributes to work. However, this still does not work in the code below. <form method="post" hx-post="{% url 'generate_yarn_colorway' %}" hx-target="#result"> {% csrf_token %} <div x-data="{ colors: [], color: '#ff0000', showHoverMessage: false, selectedItems: [], newItem: '' }"x-init="$watch('color', new_value => { htmx.process(htmx.find('#mycomponent')) })"> <label class="form-label" for="colorPicker">Colour: </label><span x-text="color" id="update_colour"></span> <input class="form-control form-control-color col-md-2" type="color" list="presetcolors" id="colorPicker" name="colorPicker" x-model="color" @mouseover="showHoverMessage = true" @mouseleave="showHoverMessage = false" data-bs-toggle="tooltip" data-bs-placement="top"><span x-show="showHoverMessage" class="text-gray-500">Choose colour. Include main colour first.</span> <br> <datalist id="presetcolors" x-data="{ colorOptions: ['#ff0000', '#FFA500', '#Ffff00', '#00ff00', '#0000ff', '#8F00FF', '#800080', '#FF00FF', '#00FFFF', '#4B0082','#40E0D0', '#Ffc0cb', '#964B00', '#FFFFFF', '#000000', '#808080'] }"> <template x-for="color in colorOptions" :key="color"> <option x-text="color" x-bind:value="color"></option> </template> </datalist> <input id="mycomponent" type="text" name="color" x-model="color" hx-post="{% url 'update_color_description' %}" hx-trigger="changed"> <!-- Button to add color --> <button class="btn btn-primary custom-btn btn-sm" type="button" @click="colors.push(color)">Add Colour</button> <br> {{ form|crispy }} </div> <div > … -
Is there any chance to render a form in django as a plain text?
im rendering a form in django using a forms.py file, the thing is i did my design with only pure html/css and i got in this way: <form action=""> <label for="username"> Username</label> <input type="text" name="username" id="" class="input" > <label for="password"> Password</label> <input type="password" name="password id="" class="input"> </form> and i got my styles to work in that way but then, when im passing it through Django in his function from views.py and in the html file rendering it as {{ user_form }} i got this <form method="post"> <div> <label for="id_username">Username:</label> <div class="helptext" id="id_username_helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</div> <input type="text" name="username" maxlength="150" class="input" required aria-describedby="id_username_helptext" id="id_username"> </div> <div> <label for="id_email">Email address:</label> <input type="email" name="email" maxlength="254" class="input" id="id_email"> </div> <div> <label for="id_first_name">Full Name:</label> <input type="text" name="first_name" maxlength="150" class="input" id="id_first_name"> </div> <div> <label for="id_password">Password:</label> <input type="password" name="password" class="input" required id="id_password"> </div> <div> <label for="id_password2">Repeat Password:</label> <input type="password" name="password2" class="input" required id="id_password2"> </div> <input type="hidden" name="csrfmiddlewaretoken" value="yIK2Cm5pnsIuQzwGZkl0CK5iX2tdfgQP2L8W17D5vEbbImrzVTyH1nW52pyj70E1"> <p><input type="submit" value="Create my account"> </p> </form> which is broking my defined css styles. so how can render this form as i want in the way i define in above? (maybe y'all could think "bro just adapt it" but im weak in css … -
Im not sure I understand why Django wont let me do asynchronous database transactions
I am trying to create a function that will get_or_create a user record for my discord bot in my django User model as soon as someone runs the !home command - but I am encountering an issue that (as far as I understand) is a normal part of django's existing model wherein it disallows asynchronous database transactions. I've tried using the built in sync_to_async method but it raises similiar issues. Is there something I can change in my settings file or something that I havent been able to find online that would be able achieve this functionality here? Here is my home command that is invoked by the command: @bot.command(name="home", description="Displays the character sheet of your character in Oblivion After you have already created your guy") async def home_async(ctx): user_instance, created = await sync_to_async(User.objects.get_or_create( discord_id=discord_user_id, defaults={'username': ctx.author.name} )) if created: character = Character.objects.create(name=f"New Character for {ctx.author.name}") user_instance.character = character user_instance.save() view = HomePageView(user=user_instance) await ctx.send(f"Welcome {ctx.author.display_name}! Manage your character and inventory here.", view=view) Currently this is the issue that I am encountering this error: Traceback (most recent call last): File "/mnt/m/ZocPy/OblivionAlchemy/OblivionAlchemy/venv/oblivion/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke await ctx.command.invoke(ctx) File "/mnt/m/ZocPy/OblivionAlchemy/OblivionAlchemy/venv/oblivion/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File … -
How to master React-Django in depth provide me the resources
can someone tell me how and from where i should lean about Django-react integration and how they both work simultaneously in depth i have basic knowledge of them both. i wanna learn Django and react integration in depth but cant get it all -
Quill rich text editor style is not wroking for my django blog
i have wrote a blog using quill editor. and everything was fine.. but after extracting the whole blog in the string form.. i wanted to display the whole blog in their respected pages.. {{% blog.content | safe %}} whole style of quill is not working for my blog... all the style went blank(not-working) and all the content comes at left side.. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/remixicon/4.2.0/remixicon.css" integrity="sha512-OQDNdI5rpnZ0BRhhJc+btbbtnxaj+LdQFeh0V9/igiEPDiWE2fG+ZsXl0JEH+bjXKPJ3zcXqNyP4/F/NegVdZg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <!-- Include stylesheet --> <link href="https://cdn.jsdelivr.net/npm/quill@2.0.0-rc.5/dist/quill.snow.css" rel="stylesheet" /> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> <script src="https://cdn.jsdelivr.net/npm/quill@2.0.0-rc.5/dist/quill.js"></script> quill style and js are working fine for rich text editor but it is not working for the blog page. -
Why when i try to get an array of data that i send from axios, the list split into multiple values (views.py)
I try to send a list of data from frontend via axios and recieve it in views.py with django . the style of a data that i send : [{ nameDetail: "1", valueDetail: "3" }, { nameDetail: "2", valueDetail: "4" }] and this is when i console.log when i pass the value of details into axios: Array(2) 0 : {nameDetail: 'Size', valueDetail: '2oz'} 1 : {nameDetail: 'Color', valueDetail: 'White'} length : 2 [[Prototype]] : Array(0) Request with axios: const { data } = await axios.post( http://localhost:8000/api/products/product/add/, { name: name, brand: brand, category: category, description: description, badge: badge, price: price, discount: discount, countInStock: countInStock, images: images, details: details, <===== this is the data that i have a problem with }, { headers: { "Content-Type": "multipart/form-data", Authorization: Bearer ${userLogin.token}, }, } ) but when i fetch it in views.py with print(request.data) the data transform: <QueryDict: {'name': ['Electronic'], 'brand': ['ez'], 'category': ['Juices'], 'description': ['azea'], 'badge': ['promos'], 'price': ['22'], 'discount': ['2'], 'countInStock': ['2'], 'details[0][nameDetail]': ['Size'], 'details[0][valueDetail]': ['2oz'], 'details[1][nameDetail]': ['Color'], 'details[1][valueDetail]': ['White'], 'images[]': [<InMemoryUploadedFile: S33ef534d442d4a1d82ce7f52821f391aX (1).webp (image/webp)>]}> why this is happened and how i can pass a list of data to the backend and loop through it. thank you. why this is happened and how …