Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cloudflare Server Error 500 - success_fraction - mobile connection to server API error
After enabling Cloudflare, everything seems to work fine. I notice when I am on WIFI (my mobile app), I can use my server API without problems. However, when I on mobile data (4G), my mobile app (i'ved also tested directly with API), it will return 500 error. Here is the following error: <h1>Server Error (500)</h1> Response headers alt-svc: h3=":443"; ma=86400,h3-29=":443"; ma=86400 cf-cache-status: DYNAMIC cf-ray: 74968a18ee948986-SIN content-language: en content-type: text/html date: Mon,12 Sep 2022 06:20:49 GMT nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800} report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=XqpSLNdG070p90inA%2Fyz8fGLCaFJd8Ok0Q1LIX1DnZ8f1TB91QxK7C0akJOAxzWikVPGZ1%2BgGZplkOp7fo7Cx8rQDftwF6e%2FE9ZeoRHVrh6d%2BN9XidYUuwBFeAVsp5dmxQt1HrjXGxqY"}],"group":"cf-nel","max_age":604800} server: cloudflare vary: Origin,Accept-Language,Cookie x-frame-options: SAMEORIGIN How can I solve this ? (FYI, I'ved not enabled any WAF firewall rules at all) -
how can i import a class Product from model.py in Shop app to the cart.py in the Cart pp
File "C:\Users\KARIM\Desktop\DjangoShop\online\Cart\cart.py", line 4, in from ..Shop.models import Product ImportError: attempted relative import beyond top-level package -
How to merge guest cart item and user cart Django?
I am trying to merge guest cart (session cart) items and existing user cart. if cart items repeating increase quantity else, create a new cart item. In my case user already have a cart. in it three products [<CartItem: The Book Thief>, <CartItem: Sapiens: a Brief History of Human Kind>, <CartItem: The Forty Rules of Love>] then the user logged out and add some products [<CartItem: The Alchemist>, <CartItem: Sapiens: a Brief History of Human Kind>] , then when he login again, the repeating product should add quantity, not as a repeating product. and the new product should show as new product in the cart. but my code results always repeating product in the cart? def user_login(request): if request.user.is_authenticated : return redirect('home') else: if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user= authenticate(email =email, password = password) if user is not None: try: cart = Cart.objects.get(cart_id = _cart_id(request)) is_cart_item_exists = CartItem.objects.filter(cart=cart).exists() if is_cart_item_exists: cart_items = CartItem.objects.filter(cart=cart) new_cart_items = [] for cart_item in cart_items: item = cart_item new_cart_items.append(item) print(new_cart_items) cart_items = CartItem.objects.filter(user=user) existing_cart_items = [] id =[] for cart_item in cart_items: item = cart_item existing_cart_items.append(item) id.append(cart_item.id) print(existing_cart_items) print(id) for new_cart_item in new_cart_items: print(new_cart_item) if new_cart_item in existing_cart_items: #i think … -
How do I label fields on a Django form?
I'm trying to figure out how to label my Django form fields- at the moment I'm unable to change them. I have tried amending the field names and adding labels within models.py, but it throws an error, I'm not sure where to add them. models.py: from django.db import models from django.contrib.auth.models import User class Stats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"You currently weigh {self.weight}, {self.user}" views.py: class UpdateHealth(View): def get(self, request, *args, **kwargs): stats = Stats update_form = StatUpdateForm context = { 'stats': stats, "update_form": update_form, 'user': stats.user, 'weight': stats.weight, 'date': stats.date, } return render(request, 'health_hub_update.html', context) def post(self, request, *args, **kwargs): stats = Stats update_form = StatUpdateForm(data=request.POST) context = { 'stats': stats, "update_form": update_form, 'user': stats.user, 'weight': stats.weight, 'date': stats.date, 'run time': stats.run_time, 'run distance': stats.run_distance } if update_form.is_valid(): update_form.save() return render(request, 'health_hub_update.html', context) forms.py: class StatUpdateForm(forms.ModelForm): class Meta: model = Stats fields = ('user', 'weight', 'run_distance', 'run_time') Any help would be appreciated! -
python3.10 RuntimeError populate() isn't reentrant
While upgrading it from python 3.6 (working file) to 3.10.4, I encounter the following error. File "/usr/local/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/local/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant Observations: The code works file outside the docker and throws the error only in the container. -
Django ORM: Perform conditional `order_by`
Say one has this simple model: from django.db import models class Foo(models.Model): n = models.IntegerField() In SQL you can perform an order by with a condition e.g. select * from foo orber by n=7, n=17, n=3, n This will sort the rows by first if n is 7, then if n is 14, then if n is 3, and then finally by n ascending. How does one do the same with the Django ORM? It is not covered in their order_by docs. -
Connection reset by peer celery
When i create a long term tasks(1-2 days) some of them are run successfully, but some raises Connection Reset by peer error(104). For example tasks run at 11:30 failed(but some are successful), but tasks run at 12:00 or before 11:30 are successful. settings.py DATABASES['default']['CONN_MAX_AGE'] = 0 if REDIS_PRIMARY_URL: CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL", REDIS_PRIMARY_URL) else: CELERY_BROKER_URL = _env_get_required("CELERY_BROKER_URL") # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_backend CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_WORKER_MAX_TASKS_PER_CHILD=500 # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-accept_content CELERY_ACCEPT_CONTENT = ["json"] # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-task_serializer CELERY_TASK_SERIALIZER = "json" # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_serializer CELERY_RESULT_SERIALIZER = "json" # http://docs.celeryproject.org/en/latest/userguide/configuration.html#beat-scheduler CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" CELERY_ACKS_LATE = True How I run scheduler and worker on aws using containers ["celery","--app=app.celery_app","beat","--loglevel=INFO"] - start scheduler ["celery","--app=app.celery_app","worker","--loglevel=DEBUG","-n worker.%%h","--without-gossip","--without-mingle","--without-heartbeat","-Ofair","--pool=solo"] - start worker Celery version 5.2 -
Django couldn't find "django-filter" or "django-cors-headers" when I use Pantsbuild
I configured Pantsbuild for our Django projects, and everything worked neatly. Here my BUILD file: python_requirements( name="reqs", ) python_sources( name="lib", dependencies=[ ":reqs", ], ) pex_binary( name="manage", entry_point="manage.py", restartable=True, ) but when I added "django-filter", I faced an error: Traceback (most recent call last): File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/home/xurvan/monorepo/jango/manage.py", line 8, in <module> import django_filters ModuleNotFoundError: No module named 'django_filters' my manage.py file is like this: #!/usr/bin/env python import os import sys import django_filters def main(): os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'monorepo.jango.app.settings', ) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) if __name__ == '__main__': print(django_filters.__version__) main() The interesting point is that print(django_filters.__version__) works. And I can see the version correctly but then the error occurs. I also installed Django Rest Framework, and it works fine. But I have the same problem with "django-cors-headers". I don't understand the difference. # pip freeze django==4.1.1 djangorestframework==3.13.1 django-cors-headers==3.13.0 django-filter==22.1 -
Could not parse the remainder: '%if context %' from '%if context %' [duplicate]
This is my views.py : from django.shortcuts import render from django.http import HttpResponse posts= [ { 'author' : 'sahil tariq', 'title' :'Blog post 1', 'content': 'First blog post', 'date' : '12 sep , 2022' }, { 'author' : 'Hanan ', 'title' :'Blog post 2', 'content': 'Second blog post', 'date' : '13 sep , 2022' } ] def home(request): context = { 'posts': posts } return render(request, 'blog/home.html' , context) def about(request): context = { 'title' : 'About' } return render(request, 'blog/about.html', context) this is my home.html: <!DOCTYPE html> <html> <head> {{% if title %}} <title>Django Blog - {{ title }}</title> {{% else %}} <title>Django Blog</title> {{% endif %}} </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p> By {{ post.author }} on {{ post.date }}</p> <p> {{post.content}}</p> {% endfor %} </body> </html> So what I am trying to do is display the page title if there is one title present in the jinja if statement but it shows me an error when I try to run the if statement in home.html. -
django- login issue with AbstractBaseUser model
I've created the custom User model with AbstractBaseUser model. The creation of user works fine and i have checked on admin page. But the problem is... when I try to log-in existing users from the custom User model, the username seem to validate from the database, but it doesn't seem to be able to bring or validate the password from the database. here are my codes from my project. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, UserManager # Create your models here. class AccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("반드시 이메일 주소가 있어야 합니다.") if not username: raise ValueError("아이디는 반드시 있어야 합니다.") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Member(AbstractBaseUser): MALE = 'M' FEMALE = 'F' GENDER_CHOICE = [ (MALE, '남성'), (FEMALE, '여성'), ] YES = '동의' NO = '미동의' SMS_CHOICE = [ (YES, '동의'), (NO, '미동의'), ] FOREIGNER = '외국인' NATIVE = '내국인' FOREIGN_CHECK = [ (FOREIGNER, '외국인'), (NATIVE, '한국인'), ] no = models.CharField(verbose_name="스카이패스 회원번호", max_length=10, unique=True) username = models.CharField(verbose_name="회원 아이디", max_length=20, unique=True ) … -
how to check if object exist before adding in django api view
I have a favorite list but for course,user can add courses those like to see in future,I want to check course exist in list or not before adding it,if exist tell it exist before if not add it to list class AddtoMyCoursesView(viewsets.GenericViewSet): serializer_class = MyCoursesListSerializer def get_queryset(self, *args, **kwargs): pk = self.request.POST.get('pk') user = self.request.user print(user) courses = MyCoursesList.objects.filter(user=user.pk) print(courses) for course in courses: print(course) try: return MyCoursesList.objects.get_or_create(my_courses=course, id=pk) except: return Response("Item already exists", status.HTTP_400_BAD_REQUEST) model class MyCoursesList(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, blank=True) courses = models.ForeignKey(Courses, on_delete=models.CASCADE, blank=True,related_name='my_courses') added_date = models.DateTimeField(auto_now_add=True) teacher = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING, default=1) class MyCoursesListSerializer(serializers.ModelSerializer): class Meta: model = MyCoursesList fields = ['id', 'user', 'courses', 'added_date', 'teacher'] -
how to do search with pagination using Django
You can easily understand which functionality i'm trying to add this pagination Using option, i want to show limited data like if user select 10 then number of data should display 10 Next, if user enter page number 2 then it go to page number 2 form.html <form class="form-inline" method="GET" action="{% url 'bookings:cancelled_bookings_list' %}"> {% csrf_token %} <select class="form-control w-50" data-selected="Data" name="no_of_data"> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> </select> <br> <div class="input-group"> <input type="text" class="form-control w-25" placeholder="Enter Page No" name="page_no"> <div class="input-group-append"> <button class="btn btn-primary" type="submit" id="button-addon2">Go</button> </div> </div> </form> views.py page = request.GET.get('page', 1) paginator = Paginator(bookings, PAGE_SIZE) try: bookings = paginator.page(page) except PageNotAnInteger: bookings = paginator.page(1) except EmptyPage: bookings = paginator.page(paginator.num_pages) if request.method == "GET": no_of_data = request.GET.get('no_of_data') page_no = request.GET.get("page_no") paginate_by = no_of_data -
Can DRF serializer combine a few fields into a nested JSON?
I have a model of a product for Internet shop. Can I write a serializer that will wrap up a few fields in a nested JSON? For example: class Product(models.Model): product_type = models.CharField( choices=ProductType.choices, max_length=20 ) vendor_code = models.CharField(max_length=20) name = models.CharField( max_length=100, default=vendor_code ) material = models.CharField( choices=Material.choices, max_length=20 ) coating = models.CharField( choices=Coating.choices, default=Coating.NO_COATING, max_length=20 ) gem_type = models.CharField( choices=GemType.choices, default=GemType.NO_GEM, max_length=20 ) gem = models.CharField( choices=Gem.choices, blank=True, null=True, max_length=20 ) I want some fields combined into nested JSON when serializing: { 'product_type': ..., 'vendor_code': ..., 'characteristics': { 'material': ..., 'coating': ..., ... } Is it possible in DRF? -
How to enter data without textarea Django?
I have a form that looks like stackoverflow textarea I am trying to add a product. The description of which will be entered through this form. But I don't know how to insert textarea or inpur here html: <div class="col-12"> <div class="mb-2"> <label class="form-label">Текст новости</label> <div id="blog-editor-wrapper"> <div id="blog-editor-container"> <div class="editor"> </div> </div> </div> </div> </div> vievs: def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.preview=request.POST.get("preview") obj.date=request.POST.get("date") obj.image=request.POST.get("image") obj.save() models: text = models.TextField('Текст статьи') -
How do I connect to my Django local webserver using another device through ip address?
I created a dummy website using Django, python, HTML, CSS, and JavaScript recently. After completing it I tested the website by starting the server. python3 manage.py runserver I was able to open the website in a browser in the local machine using the link 127.0.0.1:8000/ Now, I want to connect to this server using my android device. As my first step I started a hotspot on my android which I've connected my pc by wifi in order to bring the client and server in the same network. Then I figured out the local IP address of my PC and I've switched off the firewall on my PC. After doing that I ran the Django runserver command with this address, python3 manage.py runserver 0.0.0.0:8000 And just like before I am able to use the website without a problem in my local machine/PC. However, when I tried to connect to this with my mobile using the link, 192.168.45.220:8000 Where 192.168.45.220 is the IP address of the PC which I'm running as the current local server. I get a error message as The site can't be reached 127.0.0.1 refused to connect ERR_CONNECTION_REFUSED I don't understand what I am doing wrong. Can someone let … -
How to customize validation messages in Django
I would like to know how to customize the Validation message when using UniqueConstraint to create unique constraints on multiple columns (including foreign keys) of Model in Django. In Django, I am creating a system for parents to apply for school lunches for their children. An account exists for each parent, and one or more children are associated with one parent. When parents log in to the school lunch application screen, select their child and date, and press the school lunch application button to complete the application. The validation of this application form did not go well. We use UniqueConstraints for multiple columns (child, date) in the Lunch model to avoid duplicate lunch requests for the same child on the same date. By default, the error message is confusing, so I tried to change the validation message, but it didn't work. Specifically, I created check_duplicate as a class method in the Lunch model and called it from the clean method of the form (ModelForm). At this time, both the validation message that I created and the default message are displayed on the actual screen. ・Message I created (child has already applied for yyyy/mm/dd school lunch.) ・Default message (Lunch with this … -
is it posible to order_by "NOT ILIKE search%" in django?
i'm trying to sort the trigram search result in postgres not only by the distance but prefix and suffix too. I know the trigram result put more weight on leading matches but sometime suffix matches showing closer distance. is it possible to order by search_on NOT ILIKE keyword% in django? -
Edit Data in Django Unable to show the data
I'm using Django to build a website. Modal bootstrap is what I'm utilizing. All works good for add, and delete data. However, In the Django form, I am unable to appear the data stored in the database for the update. Appreciate your help maybe I did something wrong with my code. I am not sure if my html or modal is correct. Thank you -->> HTML <<-- <!-- Table Header --> <thead> <tr> <th>User ID</th> <th>Username</th> <th>First Name</th> <th>Middle Name</th> <th>Last Name</th> <th>Role</th> <th>Created Date</th> <th>Modified Date</th> <th>Status</th> <th>Settings</th> </tr> </thead> <!-- Table Body --> <tbody> {% for members in member %} <tr> <td>{{members.id}}</td> <td>{{members.username}}</td> <td>{{members.first_name}}</td> <td>{{members.middle_name}}</td> <td>{{members.last_name}}</td> <td>{% if members.role %}{{members.get_role}}{% endif %}</td> <td>{{members.created_date}}</td> <td>{{members.modified_date}}</td> <td> {% if members.status == 1 %} <button type="button" class="btn btn-success rounded-pill">{{members.get_status}}</button> {% elif members.status == 2 %} <button type="button" class="btn btn-danger rounded-pill">{{members.get_status}}</button> {% elif members.status == 3 %} <button type="button" class="btn btn-secondary rounded-pill">{{members.get_status}}</button> {% endif %} </td> <td> <a href="#" data-toggle="modal" data-target="#viewUserModal{{ members.id }}"><i class='bx bxs-folder-open' data-toggle="tooltip" title="View"></i></a> <a href="#" data-toggle="modal" data-target="#editUserModal{{ members.id }}"><i class='bx bxs-edit' data-toggle="tooltip" title="Edit"></i></a> <a href="#" data-toggle="modal" data-target="#deleteModal{{ members.id }}"><i class='bx bx-trash' data-toggle="tooltip" title="Delete" ></i></a> </td> </tr> {% include 'includes/modals.html' %} {% endfor %} </tbody> <!-- End of Table … -
How to use a function in another class and modify it Django
Sup, need to use a function in a different class without losing the model, while still being able to change the function(not important, I can rewrite func into more flexible func). Can't solve this issue at least 10 hours. Google didnt help =( I know code is a little dirty, I will clean that :D Don't worry class head(View): template_name = "dental/mainpage.html" model = signup def get(self,request): if request.method == 'GET': form = UserSign return render(request, "dental/mainpage.html", {"form": form}) def FormSign(self,request): if request.method == 'POST': form = UserSign if form.is_valid(): body = { 'Name': form.cleaned_data['Name'], 'email': form.cleaned_data['email'], 'Number': form.cleaned_data['Number'], } info_user = "\n".join(body.values()) send_mail( 'Sign', info_user, 'eric1122221@mail.ru', ['eric1122221@mail.ru'], fail_silently=False) return render(request, "dental/mainpage.html", {"form": form}) #self.template_name return render(request, "dental/mainpage.html", {"form": form}) class stockpage(ListView): template_name = "dental/stocks.html" model = stock context_object_name = "stocks" -
Uploading image via django from react is showing error of UnicodeDecodeError: 'utf-8'
I am building a Blog App in React and Django and I am trying to upload an image from react in django But It is showing UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 136: invalid start byte views.py class BlogCreateView(APIView): serializer_class = BlogSerializer def post(self, request, *args, **kwargs): print(request.body) data = json.loads(request.body) print(data) return Response({"status": "SUCCESS"}) serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = ("id", "image") App.js function BlogCreate() { const [image, setImage] = useState(null); const saveBlog = () => { let form_data = new FormData(); form_data.append("image", image, image.name) const headers = { "Content-Type": "multipart/form-data", Accept: "application/json", } axios.post("http://127.0.0.1:8000/blog_create/", form_data, {headers:headers}).then((res) => { console.log(res) }) return ( <> <input type="file" onInput={(e) => setImage(e.target.files[0])} /> <button type='button' onClick={saveBlog}>Save</button> </> ) } } } When I use for loop like :- for data in request.data: json_accep = data.replace("'", "\"") get = json.loads(json_accep) print(get) then It is showing json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I have tried many times but it is still not working. -
Append List of String and Q Expression into Q Expression in Django
I am trying to convert a list of strings ( parenthesis, AND, OR ) and Q Expression into Q Expression. I have tried many things but still couldn't find a solution. The input list looks like ['(', <Q: (NOT (AND: name = XYZ))>, ')', 'AND', '(', '(', <Q: (AND: dob = 2020-04-04)>, ')', 'OR', '(', <Q: (AND: no_of_degree = 3)>, ')', ')'] And Desire output is ( ~Q( name = 'XYZ' )) & ( (Q(dob = 2020-04-04)) | (Q(no_of_degree = 3)) ) Any Idea how to do this? -
HTML Docs Not Updating from CSS
I am using a CSS file to update my HTML in a Django app, but despite the fact that my "style.css" sheet is linked to the HTML file, there are no updates occuring. "style.css" is in the same folder as my HTML document ("index.html"), but nothing is changing. I've pasted my code below: <head> <link type="text/css" rel="stylesheet" href="style.css" media="screen"/> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> I know that the CSS and HTML files are linked, because when I hover over the "style.css"href, I can press CTRL + click, and "styles.css" opens in a new window. I've been through four or five tutorials several times each, I have copied everything which they did, but mine is still not working. I've closed and restarted the app, I've re-started the local server, and I'm extremely confused how I can follow a tutorial exactly and still not get this to work. I tried moving "style.css" to its own folder ("styles"), and then changed href to href="styles/style.css" but it is still not working. Nothing I have done works, and no tutorial has been even remotely helpful. Any help or insight is really appreciated, as even on here, finding people with … -
How to reduce space between elements on a row in css bootsrap?
Can someone help me to reduce the extra space between the fields (Site ID and Switch) on my django form below? I am using bootstrap, css and html. I am new to CSS/Bootstrap therefore any guidance will be appreciated. Thanks! Here is code: {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <br> <br> <div class="row form-row spacer rootrow" style="width: 700px; padding: 0; margin: left;" id = "id_parent"> <div class="col"> <!-- <label>{{form.name.label}}</label> --> </div> <div class="col" style="width: 25px;"> <div class="form-group" style="width: 1300px; height: 20px;"> <!--this style= width value changes the width of the form row--> <div class="input-group"> {% for field in form %} <div class="col-auto"> <label for="{{field.id_for_label}}" >{{ field.label }}{% if field.field.required %}*{% endif %}</label> </div> <div class="col-auto"> <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'site' %} {% render_field field class="dropdownlistener" required=true %} {% endifequal %} </div> </div> </div> <div class="col-auto"> <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'switch' %} {% render_field field class="dropdownforswitch" required=true %} {% endifequal %} </div> </div> </div>``` -
How do I change the Django form.errors display text?
I want to remove the circled bit from being displayed. How would I be able to do this? {% if form.errors %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> <p class="m-0">{{ form.errors }}</p> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"> </button> </div> {% endif %} This always displays property where the error is found error message error message ... I want to remove the property where the error is found. How would I do this? -
Django forms, django.core.exceptions.FieldError: Unknown field(s) (password1, password2) specified for User
After several hours of crooked searching, I still did not find a solution, so I am asking for your help. I decided to add a password confirmation to the registration, and in the forms.py - fields I added password1 password2 manage.py - File "C:\Users\User\Desktop\Work\StudyDjango\projects_practicles_\coolsite1\todo_list\views.py", line 3, in <module> from .forms import RegisterForm, TaskForm, LoginForm File "C:\Users\User\Desktop\Work\StudyDjango\projects_practicles_\coolsite1\todo_list\forms.py", line 28, in <module> class RegisterForm(ModelForm): File "C:\pthn\lib\site-packages\django\forms\models.py", line 327, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (password1, password2) specified for User forms.py - class RegisterForm(ModelForm): captchen = CaptchaField() email = forms.EmailField(required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'class':'form-control'}) self.fields['email'].widget.attrs.update({'class':'form-control'}) self.fields['password'].widget.attrs.update({'type':'password','class':'form-control', }) # self.fields['password1'].widget.attrs.update({'class':'form-control'}) # self.fields['password2'].widget.attrs.update({'class':'form-control'}) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') and views.py - def user_registration(request): form = RegisterForm if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user_session = form.save() login(request, user_session) return redirect('all_task') else: return redirect('user_registration') else: return render(request, 'todo_list/register.html', {'form':form})