Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django server returning a 404 out of nowhere
I'm quite new to Django and coding to be honest! I'm facing a problem that appeared out of nowhere when I was finishing a website I can't seem to find anything here that helps with my case. The problem goes with when I try to run the server with python manage.py runserver it gives me this error : System check identified no issues (0 silenced). July 27, 2022 - 17:30:51 Django version 4.0.6, using settings 'sitewilza.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [27/Jul/2022 17:30:53] "GET / HTTP/1.1" 404 2573 Not Found: / [27/Jul/2022 17:30:57] "GET / HTTP/1.1" 404 2573 and the server returns this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in sitewilza.urls, Django tried these URL patterns, in this order: admin/ sobremim [name='sobre'] formacao [name='formacao'] contato [name='contato'] The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. the problem is I did not change anything in both my urls.py, here they are : from django.urls import path, include urlpatterns = … -
Django filter value not in a list
I want to ask how can I filter table object that is not in a list of values. For example this is my list kyc_cat_list = ['Urgent Cases', 'NSB - Alimony Wallet', 'SGP - Site Guard Wallet', 'Suspended Cases - Rejected by BDC'] I want to get all records that are not in the above list records = history_table.objects.filter(KYC_Category not in kyc_cat_list) My Table: class history_table(models.Model): id=models.AutoField(primary_key=True) Dial = models.IntegerField(null=False) Serial = models.IntegerField(null=False, default=0) Bag = models.IntegerField(null=False, default=0) wave_no = models.CharField(max_length=50,null=False, blank=False) type = models.CharField(max_length=100, null=False, blank=False) Today_Date = models.DateField(auto_now_add=True,null=True, blank=True) Today_Date_Time = models.DateTimeField(auto_now_add=True,null=True, blank=True) user = models.CharField(max_length=100) summary = models.CharField(max_length=100,null=False, blank=False) Name = models.CharField(max_length=100,null=True, blank=True) Customer_Address = models.CharField(max_length=100,null=False, blank=False) National_ID = models.IntegerField(null=True, blank=True) Customer_ID = models.IntegerField(null=True, blank=True) Status = models.CharField(max_length=100,null=True, blank=True) Registration_Date = models.DateTimeField(max_length=100,null=True, blank=True) Is_Documented = models.CharField(max_length=100,null=False, blank=False) Needed_Action = models.CharField(max_length=100, null=False, blank=False) Hard_Copy_Type = models.CharField(max_length=100, null=False, blank=False) Request_Status = models.CharField(max_length=100, null=False, blank=False) KYC_Category = models.CharField(max_length=100, null=False, blank=False) -
How to use selenium to access web database in Django?
I am running a Django website using the given dev server command ./manage.py runserver The website contains a submission form with the textfield "title" and a submit button. Once the button is clicked, the input is saved as an object in the Titles table initialized by the following Django model: class Title(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=200, unique=True) I am testing on Python to see if the input is actually saved as an object in the table by using django.test.TestCase and selenium webdriver to write a title and click submit. The problem is that I don't know how to access the objects in the datatable afterwards. Is there a way to access the datatables on the servers using a test method? I am using sqllite for the database. -
Stuck with async python, trying to implement a live chat server
I need abit of help, i cant get chat_message function to work at all, receive works but it doesnt call 'type':'chat ive been trying everything i just cant get it to work, i want receive to call chat_message and then chat_message to append the message to the chat but it doesnt call that function.. consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Message, Room from django.contrib.auth.models import User class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_name, self.room_group_name ) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard( self.room_name, self.room_group_name ) async def receive(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username,room,message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username, 'room': room }) async def chat_message(self, event): message = event['message'] username = event['username'] room = event['room'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, 'room': room })) @sync_to_async def save_message(self, username, room, message): user = User.objects.get(username=username) room = Room.objects.get(slug=room) message = Message.objects.create(user=user, room=room, content=message) room.py {% extends 'core/base.html' %} {% block title %} {{ room.name }} | {% endblock %} {% block content %} <div class="main"> <h1>{{ room.name }}</h1> </div> <div … -
Django: Why does my validation error not show? The title is a unique field that is checked under clean_title, but it just redirects to the profile?
So my form redirects to my profile page, and the form is saved if has a unique title, however this validation error is not raised on testing. Forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "content", "featured_image", "excerpt", "status"] def clean_title(self): title = self.cleaned_data['title'] if Post.objects.filter(title=title).exists(): raise forms.ValidationError("Title already exists") return title Views.py class CreatePost(View): def get(self, request): return render(request, 'create_post.html', { 'post_form': PostForm, }) def post(self, request): form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.slug = slugify(post.title) post.save() return HttpResponseRedirect(reverse('profile', args=[request.user])) The Post Model from models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField( User, related_name='blogpost_like', blank=True) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() please be nice im not a pro dev... yet :) -
Azure FormRecognizer from Python SDK fails with message "Specified model not found or not ready"
Trying to submit document for form recognizer created in form recognizer studio using python api. I have tested the form successfully in form recognizer studio. from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer import FormRecognizerClient endpoint = "https://eastus.api.cognitive.microsoft.com/" credential = AzureKeyCredential("xxxxxxxxxxxxxxxxxxxxxxxx") form_recognizer_client = FormRecognizerClient(endpoint, credential) path = r"3FE5A953-22D4-4197-B262-E195C3A2CE9F.pdf" with open(path, 'rb') as f: blob = f.read() poller = form_recognizer_client.begin_recognize_custom_forms(model_id='mymodel', form=blob) result = poller.result() get exception azure.core.exceptions.HttpResponseError: (1001) Specified model not found or not ready, Model Id: mymodel Code: 1001 Message: Specified model not found or not ready, Model Id: mymodel I have tried recreating the model with every version of the API available - (2021-9-30-preview, 2022-1-30-preview, 2020-6-30-preview) and still no luck. I am using version 3.1.2 on the sdk. I have tried on version 3.1.0 and 3.2.0b5 and still get the error. -
I can't Read Outlook Email with Python on Linux
I need to do an email automation. For this I need to read an email from Outlook and then send it after configuring some data. The problem is that all the tutorials I've seen say to use the Outlook application installed on the computer. As I use Linux I can't do this. To read the email using Gmail, I did the following: import datetime from imap_tools import MailBox, AND user = "myemail@gmail.com" password = "anypassword" #This password is an "App Password" that I need to configure within Gmail. my_email = MailBox("imap.gmail.com").login(user, password) today = datetime.date.today() list_emails = my_email.fetch(AND(from_="", date=today, subject="")) for email in list_emails: print(email.text) How can I adapt the code for Outlook? PS: In Gmail it is possible to set an "App Password". I didn't get this in Outlook. -
How can I use the single field of the queryset?
I would like to pick the value of "titolo", for example, from the query set. This is my code: class PostUserListView(generic.DetailView): model=Autore template_name=('blogv1/post_list.html') def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) articolo=Articolo.objects.filter(autore__id=context['autore'].id) The articolo is <QuerySet [<Articolo: Ingegneria>]> Models.py Articolo has 3 fields: Titolo (charField),Autore(foreign key) and DataPubblicazione (date field) I'd like to take the value "titolo" from the articolo "ingegneria" -
How can I retrieve brands based on specific category in django?
I can retrieve all product based on specific category_name and Brand name, but i can not retrieve brands name based on specific category_name. How can I do this? My Category Model class Category(models.Model): category_name = models.CharField(max_length=20, unique=True) logo = models.ImageField(upload_to='Category') slug = models.SlugField(unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents") def __str__(self): return self.category_name My Brand Model class Brand(models.Model): brand_name = models.CharField(max_length=40, null=True, blank=True, unique=True) def __str__(self): return self.brand_name My Product Model class Product(models.Model): product_name = models.CharField(max_length=50, blank=False, help_text='Add Product Model Name or Product Name.') category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", blank=True, related_name="Products") brand_name = models.ForeignKey(Brand, on_delete=models.CASCADE, default="", blank=True, related_name="Products") specification = models.CharField(max_length=400, blank=True, default="") price = models.FloatField(blank=False, default=0.00, validators=[MinValueValidator(0.0)], help_text='Price Can not be Less than Zero.') quantity = models.PositiveBigIntegerField(default=0) class Meta: unique_together = [['category', 'brand_name', 'product_name', 'specification'] ] def __str__(self): return self.product_name -
I want to use HTML to dynamically change values and call py functions without screen refreshing
I have an app.py and a bunch of classes related to cards, players, and etc. The cards come from a csv in my local repo. In theory the game works just through the terminal, but obviously it's unintuitive and I figured a website is a good home for displaying the game. I'm currently using flask and I've looked at many many many posts relating to this and the answers are summed up to: Flask can only do that if I refresh the page. Use django or ajax. Rewrite everything in JS and use react. Also as a heads up I'm very much a noob, I only started coding recently and have more of an aptitude for python logic and constructing the game itself, but anything web-related I absolutely suck at as it's a bunch of syntax and annoying nuances that I still don't fully understand. However, if that's really my only option then of course I'll try and familiarize myself but as of right now I don't even know where to start. Any advice would be appreciated, especially if I have the whole thing confused and don't even know what I'm talking about. If you need more code or context … -
NOT NULL constraint failed: users_profile.user_id?
When I update the user's profile I keep getting the error NOT NULL constraint failed: users_profile.user_id. I have tried to fix it by setting the argument commit to False form.save(commit =False) then performing form.save(). My question is how can I update my profile and the user field of the Profile model is populated automatically by the currently authenticated user. Here is my code... users/views.py @login_required(login_url=reverse_lazy("users:login")) def profile(request,slug): if request.method == "POST": form = ProfileUpdateForm(request.POST) if form.is_valid(): form.save(commit = False) form.cleaned_data["user"] = request.user form.save() messages.success(request, "Profile updated successfully!") return redirect("users:profile", kwargs="profile") else: profile = Profile.objects.get(user__username = slug) form = ProfileUpdateForm() context = {"profile":profile,"form":form} return render(request, "users/profile.html", context) users/models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.TextField(blank = True) image = models.ImageField(default = "default.jpg", upload_to = "profile_pics") city = models.CharField(max_length=20,blank = True) url = models.URLField(blank = True) def __str__(self): return f"{self.user.username}'s profile" users/signals.py @receiver(post_save, sender = User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender = User) def create_profile(sender,instance,created,**kwargs): instance.profile.save() users/forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile exclude = ["user"] -
Django: Trying to add 'SHORT_TIME_FORMAT' somehow changes time zone to Chicargo
I required some extra date/time formats in addition to ones Django ships with, sI created these new formats: SHORT_TIME_FORMAT FILE_DATETIME_FORMAT ISO8601_DATETIME_FORMAT. So that I could use them in templates like this: {{ value|date:"SHORT_DATE_FORMAT" }} I created the following code in utils/time/formats.py: from collections import ChainMap from django.utils import formats DJANGO_DATETIME_FORMATS = { 'DATETIME_FORMAT': 'd M Y, H:i', 'DATE_FORMAT': 'j M Y', 'TIME_FORMAT': 'H:i:s', 'SHORT_DATETIME_FORMAT': 'Y-m-d H:i:s', 'SHORT_DATE_FORMAT': 'Y-m-d', 'MONTH_DAY_FORMAT': 'd M', 'YEAR_MONTH_FORMAT': 'Y M', } EXTRA_DATETIME_FORMATS = { 'SHORT_TIME_FORMAT': 'H:i', 'FILE_DATETIME_FORMAT': 'Y-m-d H.i.s', 'ISO8601_DATETIME_FORMAT': 'c', # Compatible with Javascript passing } def set_formats(globals_dict): """Returns a set of datetime formats for use across the whole project Contains a union of the default formats along with the additional ones. To add a new format, one has to perform the following two actions: 1. Add the name of the format to formats.FORMAT_SETTINGS 2. Add a variable with the same name as the variable to the settings.py file with the value assigned to the required format. globals_dict is the globals from the settings.py file """ formats.FORMAT_SETTINGS = frozenset(formats.FORMAT_SETTINGS | EXTRA_DATETIME_FORMATS.keys()) all_formats = ChainMap(DJANGO_DATETIME_FORMATS, EXTRA_DATETIME_FORMATS) for setting, value in all_formats.items(): globals_dict[setting] = value However when I add it to my settings.py file as so: # … -
Django api endpoint working in postman but returning undefined in the front end after axios get call
I have the following 2 projects to analyze financial data: https://github.com/codyc4321/dividends_ui https://github.com/codyc4321/stocks_backend I have an endpoint like such from django.shortcuts import render from django.http import HttpResponse from django.core import serializers import datetime, json, yfinance def get_current_price(yahoo_obj): info = yahoo_obj.get_info() price = info['currentPrice'] return price def get_all_dividends(yahoo_obj): panda_dividends_obj = yahoo_obj.dividends dividends_dicts = [] for i, v in panda_dividends_obj.iteritems(): dividends_dicts.append({'date': i.to_pydatetime().date(), 'amount': v}) return dividends_dicts def get_current_dividend_yield(price, dividends): """ this doesnt need any dates because current assumes were checking the rate over this past year""" rate = get_yearly_dividend_rate_from_date(dividends, datetime.date.today()) return round((rate / price) * 100, 2) def current_dividend_yield_view(request, ticker): yahoo_stock_obj = yfinance.Ticker(ticker.upper()) price = get_current_price(yahoo_stock_obj) dividends = get_all_dividends(yahoo_stock_obj) current_yield = get_current_dividend_yield(price, dividends) current_yield_object = {'current_yield': current_yield} data = json.dumps(current_yield_object) return HttpResponse(data, content_type='application/json') and path('current_yield/<str:ticker>/', views.current_dividend_yield_view, name='current_yield'), according to postman and my browser the endpoint works as intended my app.js passes the callback to the SearchBar component import React from 'react'; import SearchBar from './SearchBar'; import axios from 'axios'; class App extends React.Component { state = {data: null} onSearchSubmit = async (term) => { const url = 'http://localhost:8000/dividends/current_yield/' + term console.log(url) const response = await axios.get(url, { params: {query: term}, headers: { // Authorization: 'Client-ID *YOUR KEY HERE*' // "Access-Control-Allow-Origin": "*", } }); … -
Python: Making post.file.url unique for image and video files
Ive been working on a social media website where you can upload images and videos and follow other users. I managed to upload and display uploaded files to the website. I used FileField to load the image and video files, but when I implement it in my Template it shows both spaces, because there both using the same source url {{ source.file.url }} models.py class Post(models.Model): title = models.CharField(max_length=150) file = models.FileField(upload_to='uploads/%Y-%m-%d') feeds.html {% if post.file.url %} <video class="video-context" width="500px" height="500px" controls> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% endif %} {% if post.file.url %} <img class="image-context" src="{{ post.file.url }}" type="image/jpg" type="image/jpeg"> {% endif %} heres a sreenshot empty video player over img I tried the if endswith form: {% if file.endswith .mp4 %} <video class="video-context" width="500px" height="500px" controls> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% endif %} {% if file.endswith .jpg/jpeg %} <img class="image-context" src="{{ post.file.url }}"> {% endif %} But it didn't work. How can I just display the file thats uploaded. How can I make the {{ post.file.url }} unique for image and video, so its easier to difference? How is it possible to difference the upload types, but still using FileField? -
Django: Multiple Photos Uploading not connected to user
i've been trying to upload multiple photos to the gallery of a user and i am being able to do so but they are not being connected to the user who is uploading them. images just gets to the specified path but when i see it in admin panel, photos are there, but no user is connected to them. #views.py def images(request): owner = request.user.profile name = request.POST.get('filename') files = request.FILES.getlist('images') for file in files: i = Images.objects.create(image=file,) i.save() return render(request, 'profiles/images.html') #models.py class Images(models.Model): profile = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) f_name = models.CharField(max_length=250, null=True) image = models.ImageField(upload_to='user/') updated = models.DateField(auto_now=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) #forms.py class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images fields = ('image',) -
How to make a password authentication with QR for a django html form
I have made a password protected page with django and cms wagtail, i need the following cases to happen: If user enters the url normally: page requires him a password through an HTML form, and don't get him access to it until it gives the correct password (Done). If user enters with a QR code: page doesn't require him the password, and get him immediate access to the content page. Models.py: from wagtail.core.models import Page, PageViewRestriction from wagtail.images.edit_handlers import ImageChooserPanel from django.utils.translation import gettext_lazy as _ class ProfilePage(Page): template = 'profile/profile_page.html' def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) return context def save(self, *args, **kwargs): your_page = ProfilePage.objects.all().first() PageViewRestriction.objects.create(page=your_page, restriction_type='password') return super().save(*args, **kwargs) password template (wagtail's default one): <!DOCTYPE HTML> <html> <head> <title>Password required</title> </head> <body> <h1>Password required</h1> <p>You need a password to access this page.</p> <form action="{{ action_url }}" method="POST"> {% csrf_token %} {{ form.non_field_errors }} <div> {{ form.password.errors }} {{ form.password.label_tag }} {{ form.password }} </div> {% for field in form.hidden_fields %} {{ field }} {% endfor %} <input type="submit" value="Continue" /> </form> </body> </html> -
Custom ordering in django rest framework?
I have view: class ContactListView(generics.ListAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer filter_backends = (filters.SearchFilter,filters.OrderingFilter) ordering_fields = ['name'] search_fields = ('name',) I set ordering by name but name contains First Name and Last Name , I want to set order by Last Name I created : class SurnameOrdering(OrderingFilter): ordering_fields = ['surname'] def get_ordering(self, request, queryset, view): pass but how set this ordering ?? -
How to restrict regular users from accessing admin page?
I would like to allow only admin users to access admin page and raise 404 error if user is not authenticated or is not a staff member. Is there a way to wrap admin view with another function to check if user is admin? -
Django How to pass username in a predefined template
I created a templates for header/footer and imports, if I want to acess the username in my header template I cant do that because it has no views. How can I pass the username to the header template? header_template.py from django import template register = template.Library() @register.inclusion_tag('home/partials/header.html') def header(element): return {'element': element, } Import in Template {% load header_template %} {% header context %} Usage in the template: {% if user.is_authenticated %} <a class="btn btn-primary display-4" href="{% url 'home:profil' %}">Profil</a> {% else %} <a class="btn btn-primary display-4" href="{% url 'home:login' %}">Login</a> {% endif %} Thanks for your help. -
Docker-Compose Django can't connect to DB or Celery
I have everything on one network (it talks to another app in another docker-compose file). But I keep getting this error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (192.168.208.3) and accepting TCP/IP connections on port 5000? When I change my SQL_PORT=5432 (default port that's running in the postgres container) the error above disappears and my app is up, but then it has problems when trying to connect to celery or in shell it says db is not connected. I have to use 5000 cause there is another postgres db on the other app in the second docker-compose setup. I think I'm lost on the internals of networks. I was pretty sure I am suppose to use the exposed port of 5000 for my database. version: "3.9" services: app: build: . command: python manage.py runserver 0.0.0.0:8000 container_name: app environment: - DEBUG=True - PYTHONUNBUFFERED=1 - CELERY_BROKER=redis://broker:6379/0 - CELERY_BACKEND=redis://broker:6379/ - APP_BASIC_AUTH_PASSWORD=adPswd12* - APP_BASIC_AUTH_USER=admin - APP_TOKEN_AUTH=NHEC_UTILITY - VTN_API_URL=vtn_app:8000 - VTN_API_TOKEN=NHECAPP_UTILITY - SQL_PORT=5000 volumes: - .:/code ports: - "9000:8000" networks: - app-web-net depends_on: - db - celery-worker - broker app_test: build: . command: python manage.py test container_name: app_test environment: - DEBUG=True - … -
Django multiple user group design method
I have a project for a staffing service company that has at least four user groups (admin, employers, employees and the owner of the staffing service company). Each of them has the following functions: Admin can do everything. Employer can publish, update, view the job/gag events. (can't delete without admin's permission). Employee can view, confirm/update after finishing the events. Owner is pretty much similar to admin. Perhaps does not have delete permission. BTW, admin and owner could be the same person if it would be simpler. I have read some blogs and some of them mentioned to use AbstractUser subclass, etc. However, I still feel not clear enough. Should I build an app called User which has three or four classes in that model.py in User App? Those four classes would be "Class Admin", "Class Owner", "Class Emoloyee", "Class Employer"? Or how should I implement it? Any advice? Thank you! -
Enum field in MySQL
In MySQL there are several types of data, char, varchar int, boolean as you already know. But it also has the Enum type that in SQL we create the table as follows: CREATE TABLE person( id int..... name varchar(50), and Married Enum(Yes,No) ) My goal is, when I'm creating the models in Django (Python) to be able to create the tables in MySQL I can automatically create this type of field as well. I tried like this: from django.db import models from enum import enum class options(Enum): Yes = "Yes" No = "No" class Customer(models.Model) : name = models.CharField(max_length=200) docto = models.CharField(max_length=14) age = models.IntegerField(default=0) username = models.CharField(max_length=20) password = models.CharField(max_length=20) block = models.CharField( max_length=3, choices=[(tag, tag.value) for tag in options], default= 'No' ) def __str__(self): return self.name Create the field in MySQL creates but creates as VARCHAR(3) and not as enum. Can Django do this? How would it be? I wouldn't like to have to create the tables directly in the database, -
Django Forms Radio Button
I had made a form using django forms and call it to a template but while I select a radio button it won't pick what's the solution ''' html section ''' <div class="form-row p-t-20"> <label class="label label--block">Gender</label> {% for radio in form.Gender %} <div class="p-t-15"> <label class="radio-container"> {{radio}} <input type="radio" name="gender"> <span class="checkmark"></span> </label> </div> ''' forms section ''' Gender = forms.ChoiceField(choices=GenderChoice,widget=forms.RadioSelect(attrs={'class':'form-check form-check-inline'})) -
Django is not creating any fields with users created manually
i've created a eccomerce website. this has a registration page where users creates their user account & then can order anything. if i create a user from admin panel, then everything works perfectly. but if i create a user from front end of my registration page using React js, then that user can't order anything, meaning when i post a data using fetch django doesn't store or create any data for that user. why? what's the issue here? i'm using Rest Api in backend & posting data through fetch to send data. but the fetch fails but not if i use a user which was created from admin panel(./admin). am i doing anything wrong in creating the user data manually at my views??? #my_views from django.shortcuts import redirect from django.contrib.auth.hashers import make_password from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from App.models import * from api.forms import RegisterForm from .serializers import * from django.contrib.auth.models import User class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username # ... return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer @api_view(['GET','POST']) def getRoutes(request): routes = [ '/api/token', '/api/refresh', ] return Response(routes) … -
Errors not showing in Django signup template form
Hi i need help with my code, errors not showing up in my HTML form and i dont know how to debug it or how to understand why the div isnt showing, i tried changing its CSS i tried changing classname i tried everything i just cant get it to show when i put bad inputs. views.py from django.shortcuts import render, redirect from .forms import SignUpForm from django.contrib.auth import login def frontpage(request): return render(request,'core/frontpage.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('frontpage') else: form = SignUpForm() return render(request, 'core/signup.html', {'form': form}) signup.html {% extends 'core/base.html' %} {% block title %} Sign Up | {% endblock %} {% block content %} <div class="main"> <h1>Sign Up</h1> </div> <div class="form-container"> <form method="post" action="." class="sign-up-form"> {% csrf_token %} <p>Fill Form :</p> <div class="form-items"> <label for="username">Username</label> <input type="text" class="label" id="username" name="username" placeholder="Username" > <label for="password">Password</label> <input type="password" class="label" id="password" name="password1" placeholder="Password"> <label for="confirm-password">Confirm Password</label> <input type="password" class="label" id="confirm-password" name="password2" placeholder="Confirm Password"> {% if form.error %} {% for field in form %} {% for error in field.errors %} <div class="error-msg"> <p>{{ error|escape }}</p> </div> {% endfor %} {% endfor %} {% endif %} <div class="form-control-buttons"> <button …