Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting 'Something went wrong' on form submission in Django signup view
I am experiencing an issue in my Django project's signup view. When I submit the form, the console prints 'Something went wrong,' and the user is not created. I have a custom User model, and the signup view appears to be correctly handling form data. However, despite thorough checks of my code, I'm unable to identify the root cause of the problem. --views.py from django.shortcuts import render, redirect from .models import User def signup(request): if request.method == 'POST': name = request.POST.get('name', '') email = request.POST.get('email', '') password1 = request.POST.get('password1', '') password2 = request.POST.get('password2', '') if name and email and password1 and password2: user = User.objects.create_user(name, email, password1) print('User created:', user) return redirect('/login/') else: print('Something went wrong') else: print('Just show the form!') return render(request, 'account/signup.html') I have also made the following settings: AUTH_USER_MODEL = 'account.User' --models.py import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.db import models class CustomUserManager(UserManager): def _create_user_(self, name, email, password, **extra_fields): if not email: raise ValueError('You did not provide an valid e-amil address') email = self.normalize_email(email) user = self.model(email=email, name=name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, name=None, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user_(name, email, password, **extra_fields) def create_superuser(self, name=None, email=None, password=None, **extra_fields): … -
Guidelines to be good with programming [closed]
Please I really need help, I have been in the field of building websites for more than 3 years now as self thought but it seems as if I'm not learning, please guide me through on how best to be self thought I have tried building projects from Youtube but I always fail. how where and how can I build websites with python and Framework Django -
DRF override default router path
When i register viewset in SimpleRouter i get paths like [get] objects/ [post] objects/ [get] objects/{id} etc. Is there a way to replace default post route with its detailed version? like [post] objects/{id} I've tried to replace it with action in viewset @action(detail=True, methods=['post'], url_path="my-path"): def my_action: ... but all i've got is [post] /objects/{id}/my-path and default post path is still there -
how to delete cache on my VPS Ubuntu Server. Whatever I write on any page is never shown
This is driving me insane. No matter what I do on the pages nothing is shown. Even if I write "hello" on my index.html page it will not show it. The server only shows what I pulled from github a week ago. Nothing, no change. I added the sentry logging tool, it takes zero notice, I copied pasted the logging snippet used and it completely ignores it. I write an extra word on the menu bar at the top, nothing is shown. -
drf-yasg: how to skip some operations during generate_swagger
I use Django with drf-yasg. I have a REST endpoint similar to the following: @swagger_auto_schema( method="POST", request_body=... ) @api_view(["POST"]) def do_something(request: Request) -> HttpResponse: ... When I run the server, I see the do_something operation in /swagger panel, which is fine. Now, when I run ./manage.py generate_swagger I would like do_something operation to NOT show in the resulting OpenAPI yaml. I would like to be able to somehow annotate the operation to be conditionally included, like with some custom @include_conditionally decorator: @include_conditionally @swagger_auto_schema(...) @api_view(["POST"]) def do_something(request: Request) -> HttpResponse: ... I know that setting auto_schema=None prevents the endpoint from being included in Swagger, but it excludes the endpoint from both Swagger web panel and the yaml schema, which I do not want. I tried to use my own generator in ./manage.py generate_swagger -g MyGenerator class MyGenerator(OpenAPISchemaGenerator): def should_include_endpoint(self, path, method, view, public): ... while should_include_endpoint seems to be the right way to go, I failed to detect if the operation was annotated with include_conditionally. Background: I want to exclude some of the endpoints from being exposed with Google ESP while being available locally. How can I exclude some endpoints conditionally from being included in Swagger schema yaml file? -
Re-translate Django
Django comes translated in my language however it's not complete and I don't like some of the translated phrases (personal preference). So I set the locale folder up and run python manage.py makemessages -l fa_IR and I get the file django.po but when I open it, I find that the phrases that are already translated and included with Django are not there. So looks like I have to edit (for example) \venv\Lib\site-packages\django\contrib\auth\locale\fa\LC_MESSAGES\django.po but if I ever update Django package of this project, all my edits will be lost, right? Is there any other solution? -
sorting DataTables from Django
I'm currently working on a Django project where I need to display and sort weather station data in a DataTable. I'm facing an issue when it comes to sorting columns that contain calculated values, such as averages and sums. this code result in clickhouse error due to a problem with the inner join not working as properly I am out of ideas to sort the values (avg_value, max_value,min_value, sum_value, and count_value) please help @cache_page(120) @api_view(['GET']) def station_list(request): serializer = StationListSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) # Extracting DataTables parameters draw = int(request.GET.get('draw', 1)) start = int(request.GET.get('start', 0)) length = int(request.GET.get('length', 10)) order_column_index = int(request.GET.get('order[0][column]', 0)) order_direction = request.GET.get('order[0][dir]', 'asc') search_value = request.GET.get('search[value]', '') selected_region = request.GET.get('region') selected_governorate = request.GET.get('governorate') # QuerySet for AwsGov station_queryset = AwsGov.objects.all() if selected_region: station_queryset = station_queryset.filter(ADMIN=selected_region) if selected_governorate: station_queryset = station_queryset.filter(REGION_ID=selected_governorate) # Define columns for sorting and filtering direct_fields = ['station_id', 'Name', 'ADMIN_NA_1', 'REGION_N_1'] all_fields = direct_fields + ['avg_value', 'max_value', 'min_value', 'sum_value', 'count_value'] # Adjust for language if request.LANGUAGE_CODE == 'ar': direct_fields = ['station_id', 'Name', 'ADMIN_Name', 'REGION_NAM'] if order_column_index < len(all_fields): order_column = all_fields[order_column_index] else: order_column = all_fields[0] # else: # order_column = columns[0] # Default to the first column if out of range if order_column in direct_fields: if … -
Django models, filter based on the division of two fields
I am having trouble understanding the annotate of django models. I am trying to build a datatable where one of its value is the division of two fields that might contain zeros and filter the rest based on the user input so what I tried so far is: model from django.db import models from django.utils import timezone class Item(models.Model): item_name = models.CharField(max_length=200) item_price = models.FloatField(default=0.0) unit_per_item = models.FloatField(default=1) description = models.TextField(default='') is_active = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) date_added = models.DateTimeField(default=timezone.now) views from django.db.models import Q, F, Case, When, FloatField from .models import Item if request.POST['search[value]']: model_obj = Item.objects.annotate( unit_price = Case( When(Q(item_price__exact=0) | Q(unit_per_item__exact=0), then=0), default=F("item_price") / F("unit_per_item"), output_field=FloatField() ) ).filter( Q(item_name__icontains=request.POST['search[value]'])| Q(item_price__icontains=request.POST['search[value]'])| Q(unit_per_item__icontains=request.POST['search[value]'])| Q(description__icontains=request.POST['search[value]'])| Q(unit_price__icontains=request.POST['search[value]']) )[start:length] But I am getting an error that says RegisterLookupMixin.get_lookup() missing 1 required positional argument: 'lookup_name' What I am essentially trying to achieve here in SQL is this SELECT *, item_price/unit_per_item AS unit_price FROM inventory_item WHERE item_name LIKE '%some_value%' OR item_price LIKE '%some_value%' OR unit_per_item LIKE '%some_value%' OR description LIKE '%some_value%' OR CONVERT( CASE WHEN item_price=0 OR unit_per_item=0 THEN item_price ELSE item_price/unit_per_item END, CHAR) LIKE '%some_value%'; I am honestly a little lost at this point, if there is a documentation that can expound further … -
Which package to use when dealing with storing and displaying document files like pdf word excel etc in Django and Oracle
I have a requirement where I need to store documents( pdf, word, excel in Oracle database) and display a list of these files on a page serially. When clicked on its name it should open in next tabs in browser. I also need to be able to search and count few keywords in these documents while it been store in the Database. I am just not sure which package I must use in Django for this requirement and which datatype to be used in Oracle. Can anybody please help me for getting started in right direction. -
Implementing pagination in Angular Material with Django rest frameork
I am trying to implement pagination in my Angular Material that will work with the data coming from my Django server but I haven't gotten it right. Here is my customer.component.ts export class CustomerComponent { customers: Customer[] = [] dataSource: any; displayedcolumns: string[] = ['name', 'phone', 'debt_amount', 'remaining_credit', 'created_at', 'action'] @ViewChild(MatPaginator) paginator!: MatPaginator; @ViewChild(MatSort) sort!: MatSort; constructor(private http: HttpClient, private customerService: CustomerService,) {} ngOnInit(): void { this.fetchCustomers() } fetchCustomers() { this.customerService.getCustomers().subscribe({ next: (data: ApiResponse<Customer[]>) => { this.customers = data.results; this.dataSource = new MatTableDataSource<Customer>(this.customers) this.dataSource.paginator = this.paginator this.dataSource.sort = this.sort console.log(this.customers); }, error: (error: any) => { console.error('Error fetching customers', error); }, complete: () => { console.log('Finished fetching customers'); } }); } Filterchange(data:Event) { const value = (data.target as HTMLInputElement).value; this.dataSource.filter = value; } } Below is my customer.component.html <mat-card-header> <mat-form-field> <input matInput (keyup)="Filterchange($event)" placeholder="Search by Name" /> </mat-form-field> </mat-card-header> <mat-card-content> <table matSort mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container matColumnDef="name"> <th mat-sort-header mat-header-cell *matHeaderCellDef="">Name</th> <td mat-cell *matCellDef="let element">{{element.first_name}}</td> </ng-container> <ng-container matColumnDef="phone"> <th mat-header-cell *matHeaderCellDef="">Phone</th> <td mat-cell *matCellDef="let element">{{element.phone}}</td> </ng-container> <ng-container matColumnDef="debt_amount"> <th mat-header-cell *matHeaderCellDef="">Debt Amount</th> <td mat-cell *matCellDef="let element">{{element.debt_amount}}</td> </ng-container> <ng-container matColumnDef="remaining_credit"> <th mat-header-cell *matHeaderCellDef="">Remaining Credit</th> <td mat-cell *matCellDef="let element">{{element.remaining_credit}}</td> </ng-container> <ng-container matColumnDef="created_at"> <th mat-sort-header mat-header-cell *matHeaderCellDef="">Created At</th> <td mat-cell *matCellDef="let element">{{element.created_at | … -
(CRUD) Inventory System with Sub-inventories in DJANGO
This CRUD is basically a Main Inventory(a), which is going to be used by the inventory manager to feed workers inventories(b,c,d..)... When I try to transfer an item from A to B, the item gets transferred successfully, however, if item already exists, it still creates a new one, duplicating the Item several times. For Example: If a subinventory has "2 Screws", I add "3 Screws". Now the Subinventory has "2 Screws, and "3 Screws", instead of having now "5 Screws". The Models: Main Inventory class Articulo(models.Model): id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=50) descripcion = models.CharField(max_length=100, null=True) costo = models.IntegerField(null=True) cantidad = models.IntegerField(null=True) medida = models.CharField(max_length=20) fecha_ingreso = models.DateTimeField(auto_now_add=True, null=True) fecha_salida = models.DateTimeField(auto_now_add=True, null=True) ubicacion = models.CharField(max_length=50, default='Almacen') SubItem and Subinventory class articuloInventario(models.Model): articulo = models.CharField(max_length=50, null=True) cantidad = models.IntegerField(null=True) medida = models.CharField(max_length=20, null=True) fecha_ingreso = models.DateTimeField(auto_now_add=True, null=True) ubicacion = models.IntegerField(null=True) class brigadaInventario(models.Model): id = models.AutoField(primary_key=True) articulos = models.ManyToManyField(articuloInventario) Views: def transferir_articulo(item_id, quantity): item_a = get_object_or_404(Articulo, id=item_id, cantidad__gte=quantity) item_b = get_object_or_404(articuloInventario, id=item_id, cantidad__gte=quantity) inventario = articuloInventario.objects.all() for b in inventario: if item_a.nombre == b.articulo: item_a.cantidad -= quantity item_a.save() b.cantidad += quantity b.save() return JsonResponse({'mensaje': f'{quantity} items transferred from inventory A to inventory B.'}) item_a.cantidad -= quantity item_a.save() item_b.cantidad += quantity item_b.save() … -
I try to install geonode using ubuntu 20.04 and i failed in "docker-compose logs -f django"
i have an error while loging into geonode in ubuntu 20.04 specifically in the command : docker-compose logs -f django it stops at this line : MONITORING_DATA_TTL=365 and then exits with code 1 i tried to fix this several times but with no succes -
Unable to Commit Changes in Django Project When Including External Repository with Sass Partials
I am working on a Django project where I need to incorporate an external repository containing Sass partials for styling. To achieve this, I performed a git clone of the Sass partials repository into my Django project's repository. However, I've encountered an issue where any commits I make do not include the folder from the cloned Sass partials repository. It seems like the changes within the cloned repository are not being tracked or committed within the main Django project. Here are the steps I took: Cloned the Sass partials repository into my Django project: git clone <repository_url> Checked that the Sass partials folder is present within my Django project. Made changes to the Sass files and attempted to commit: git add . git commit -m "Made changes to Sass files" However, the commit does not include the changes made in the Sass partials folder. Additionally, I would like to emphasize that I do not want the changes made to the Sass partials to be committed within the Django project. I intend to maintain the Sass partials repository as a template only. I suspect there might be something related to the submodule behavior, but I want to ensure that the changes … -
Get graphics in Vue.js
I want to create a personal web application using Django for the backend and Vue.js for the frontend, but I need to know if it is possible to use graphics in Vue.js, is that possible? In my application, I want to implement regression functions in Django to visualise the output in graphics in Vue.js and I want also to show the data flow of some features of my data. Tell me if this is possible, thanks. I haven't tried to do anything yet because it is all a working progress. -
Django ValueError: Cannot assign "<SimpleLazyObject: <User: gouri24>>": "HotelConfirm.username" must be a "userLogin" instance
I am encountering a ValueError in my Django project when trying to assign a user instance to the username field of the HotelConfirm model. The error message is: "Cannot assign "<SimpleLazyObject: <User: gouri24>>": "HotelConfirm.username" must be a "userLogin" instance." Here is a snippet of my code: # Your relevant code snippet here login_required def book_hotel(request, hotel_id): hotel = get_object_or_404(Hotel, pk=hotel_id) if request.method == 'POST': # Process the form submission user_instance = request.user # Use the user instance directly room_type = request.POST.get('roomType') arrival = request.POST.get('arrival') departure = request.POST.get('departure') adult = request.POST.get('adult') children = request.POST.get('children') booking = HotelConfirm.objects.create( username=user_instance, hotel=hotel, roomType=room_type, arrival=arrival, departure=departure, adult=adult, children=children ) booking.save() # Save the booking object # Redirect to the home page after successful booking return redirect('home') # Replace 'home' with the actual name or URL of your home page return render(request, 'Booking_hotel.html', {'hotel_id': hotel_id}) I am using Django's default User model, and it seems that there is a mismatch between the expected model for the username field (userLogin) and the actual user instance (<User: gouri24>). How can I resolve this issue and properly assign the user instance to the username field? Make sure to include the relevant parts of your code that are related to … -
Getting this error while working with django : FOREIGN KEY constraint failed
I have created a BaseUser model to create users and i have also created a Profile for every single user when new user gets created. But when i try to update the information's or try to delete the specific user from the admin panel i get this error :- [12/Jan/2024 15:05:29] "GET /admin/accounts/baseuser/16/change/ HTTP/1.1" 200 17895 [12/Jan/2024 15:05:30] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 347 Not Found: /favicon.ico Internal Server Error: /admin/accounts/baseuser/16/change/ Traceback (most recent call last): File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 313, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1889, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1747, … -
AsyncWebSocketConsumer not receiving shell responses in Django Channels with Paramiko
I am working on a Django Channels application that utilizes the AsyncWebSocketConsumer to establish a WebSocket connection for SSH communication using Paramiko. The async_server_to_client method works correctly when called within the connect method but fails to receive shell responses when called within the receive method. I have attempted to use await sync_to_async and loop.run_in_executor to handle the synchronous get_recv method within the asynchronous context, but the issue persists. The WebSocket connection is established successfully, and data can be sent to the server, but the responses from the shell are not being received and forwarded to the WebSocket client. I also tried to print self.session.recv(1024).decode() but it returns the same command which I've sent from receive method. My whole code: from channels.generic.websocket import AsyncWebsocketConsumer from paramiko import SSHClient, AutoAddPolicy, RSAKey from asgiref.sync import sync_to_async, async_to_sync from channels.db import database_sync_to_async import json from .models import RemoteServer import socket import asyncio class WebSSH(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.session = None @database_sync_to_async def get_remote_server_info(self): server = RemoteServer.objects.get(id=self.rs_id) pkey = RSAKey(filename=server.key_file.path) return { "hostname": server.host_address, "port": server.port, "username": server.username, "pkey": pkey, "timeout": 10, } async def async_ssh_connect(self, server_info): client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) await sync_to_async(client.connect)(**server_info) transport = await sync_to_async(client.get_transport)() session = await sync_to_async(transport.open_session)() await … -
Django custom field sorting
I have a problem in my django, I want to sort with my custom fields (get_total_opened, get_total_reply and the get_total_email_sent) in my serializer: class PersonListSerializer(serializers.ModelSerializer): org = OrgSerializer(many=False) # prompts = PromptResponseSerializer(read_only=True, many=True) # emails = EmailSerializer(read_only=True, many=True) custom_fields = PersonCustomFieldValueSerializer(many=True) tags = TagSerializer(many=True, default=[]) total_click_count = serializers.SerializerMethodField() total_opened = serializers.SerializerMethodField() total_reply = serializers.SerializerMethodField() total_email_sent = serializers.SerializerMethodField() scheduled_emails = serializers.SerializerMethodField() class Meta: model = Person fields = [ "id", "first_name", "last_name", "job_title", "company_name", "work_email", "company_website", "sent_emails", "last_contacted", "next_scheduled_email", "custom_fields", "org", "tags", "total_click_count", "total_opened", "total_reply", "total_email_sent", "got_data", "force_enable", "assigned_user", "status", "person_city", "state", "industry", "phone", "linkedin", "scheduled_emails", ] def get_scheduled_emails(self, obj): return EmailSerializer(obj.get_scheduled_emails(), many=True).data def get_user_created_emails(self, _obj): return _obj.emails.filter(created_by=self.context["request"].user) def get_total_click_count(self, obj): total_click_count = sum( click_count or 0 for email in self.get_user_created_emails(obj) for click_count in email.click_tracking.values_list( "click_count", flat=True ) ) return total_click_count def get_total_opened(self, obj): opened_emails = [ email for email in self.get_user_created_emails(obj) if hasattr(email, "trackings") and email.trackings.opened ] return len(opened_emails) def get_total_reply(self, obj): total_reply_count = ( self.get_user_created_emails(obj).aggregate( total_reply_count=Sum("reply_count__count") )["total_reply_count"] or 0 ) return total_reply_count def get_total_email_sent(self, obj): sent_email_count = obj.emails.filter( status=0, created_by=self.context["request"].user ).count() return sent_email_count and now I am having a problem on returning a sort from api, I have this full code on my modelviewset below but it doesn't work. … -
Uploading large file to GCS with django and django-storages -- direct or multi-part uploads?
I'm creating a django application that uploads multimedia to Google Cloud Storage using django-storages. My application is running on Google App Engine. Right now I'm having trouble with models that contain a large number of images -- for example, some of my models contain several 4K images, and at 25MB/ea I'm easily hitting hundreds of MB per save operation. django-storages is working great for smaller operations, but larger operations are causing issues. I'm currently getting an HTTP 413 error on larger save operations -- my app is POSTing about 100 MB, and Google App Engine's limit is 32MB. So my question is: to get around the limit, is it possible to make multiple POST requests using django-storages? Like, if my model has 4x 4K images, can I upload them each in a sequential upload? I've also read that I should upload files "directly" to GCS -- is it possible to do a "direct" upload using django? How would I go about doing that? thanks! -
How to create callback page for oauth with nextjs with a django grapql backend
I'd like to give some context to the setup I have going on. I'm creating a software web application and below is the setup: Backend - Django with a GraphQL API using graphene. Frontend - NextJS (/app directory) with Apollo GraphQL to speak to the backend. My app will allow users to link their accounts to eBay using OAuth. I have attached how I envisage my flow working: The issue I am running into is on the /ebay-callback page. It is making multiple calls to the GraphQL API and then for some reason it fails redirect as the compiler fails (although not sure if the compiler issue is actually related). The code for my callback page is as follows: 'use client' import { gql, useMutation } from '@apollo/client'; import { useRouter, useSearchParams } from 'next/navigation'; import { useEffect } from 'react'; const INITIATE_OAUTH_GET_ACCESS_TOKEN = gql` mutation InitiateOauthGetAccessToken($name: String!, $code: String!) { initiateOauthGetAccessToken(code: $code, name: $name) { success ebayAccount { id } } } `; export default function EbayCallbackPage() { const router = useRouter(); const searchParams = useSearchParams(); const [initiateOauthGetAccessToken] = useMutation(INITIATE_OAUTH_GET_ACCESS_TOKEN); useEffect(() => { const handleOAuth = async () => { console.log(searchParams); const code = searchParams.get('code'); const state = searchParams.get('state'); … -
unable bring footer down in wagtail and in Django html
In Django, if the footer renders correctly on sub-pages but not on the main page, you should examine the main page template and related files. Check for potential issues in the HTML structure, template blocks Verify that the main page correctly extends the base template and includes the footer within the appropriate block. Additionally, inspect any conditional logic or specific settings in the footer.html file that may affect its rendering. Ensure consistency in the template hierarchy and investigate any page-specific configurations that might impact the footer display. By addressing these aspects, you can troubleshoot and resolve the discrepancy in footer rendering. <section class="py-4 mt-lg-5 mt-0" style='background-color: #814EBF; background-image: url("{% static 'images/contact-overlay.png' %}");'> <div class="container"> <div class="row align-items-center"> <div class="col-lg-8 text-lg-left text-center"> <h2 class="h2 cc-contact-footer-h2"> Global CTA Title </h2> <p class="cc-contact-footer-p mb-0"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam laboriosam consequatur saepe. </p> </div> <div class="col-lg-4 text-lg-right text-center"> <a href="@todo" class="btn btn-light btn-lg mt-lg-0 mt-3"> @todo </a> </div> </div> </div> </section> <footer class="bg-dark py-4 text-light text-md-left text-center cc-footer"> <div class="container"> <div class=" row mx-lg-n3"> <div class="px-lg-3 col-lg-3 col-md-6 col-sm-12"> <div class="cc-footer-title">Links</div> {% for i in "123" %} <a class="cc-footer-link-lg d-block" href="@todo"> Link #{{i}} </a> {% endfor %} </div> <div … -
Problem when trying to fill out a django form with MultiSelectField field
When filling in the field and clicking send, the message "Make sure the value has a maximum of 5 characters (it has 10) appears." I've already tried several manipulations in models.py but nothing worked. I need this field to accept more than one value selected by the user to be saved in the database.I don't think I know where to move. models.py: `from django.db import models from django.contrib.auth.models import AbstractUser from courses.models import CourseCategory from multiselectfield import MultiSelectField class CustomUser(AbstractUser): areas_of_interest_choices = ( ('TI', 'Tecnologia da Informação'), ('ADM', 'Administração'), ('CTB', 'Contabilidade'), ('EC', 'Economia'), ('FI', 'Finanças'), ('SA', 'Saúde'), ('LI', 'Linguagens'), ('GA', 'Gastronomia'), ) escolaridade_choices = ( ('FC', 'Fundamental Completo'), ('FI', 'Fundamental Incompleto'), ('MC', 'Médio Completo'), ('MI', 'Médio Incompleto'), ('SC', 'Superior Completo'), ('SI', 'Superior Incompleto') ) full_name = models.CharField(max_length=50, null=False, blank=False) cpf = models.CharField(max_length=11, verbose_name='CPF', blank=False, null=False) date_of_birth = models.DateField(blank=True, null=True, verbose_name='Data de Nascimento') email = models.EmailField(max_length=100, blank=False, null=False) telephone = models.CharField(max_length=11, blank=False, null=False, verbose_name='Telefone') zip_code = models.CharField(max_length=8, blank=False, null=False, verbose_name='CEP') education = models.CharField(max_length=2, choices=escolaridade_choices, verbose_name='Escolaridade') areas_of_interest = MultiSelectField(blank=True, null=True, max_choices=3, max_length=5,choices=areas_of_interest_choices) def __str__(self): return self.username ` forms.py: `from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser, CourseCategory from django import forms class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ("username", … -
Why would a check constraint be violated on a cascade delete?
When I delete an object ('item') in my Django app, a related object (in another table) that points to it via a foreign key should also get deleted due to its "on_delete=models.CASCADE" setting. But the cascade delete is failing because of a check constraint on the related model: MySQLdb.OperationalError: (3819, "Check constraint 'item_or_container' is violated.") My question is, why would a check constraint be triggered on a delete? Does Django modify the record somehow before deletion? The record in question does pass the constraint, and if I just delete that record directly it works as expected; it only fails during a cascade delete. The "violated" constraint is as follows: models.CheckConstraint(check=Q(item__isnull=False) ^ Q(is_container=True), name='item_or_container') (Which is an XOR ensuring that an object can EITHER have an assigned item OR be a container - not both.) My expectation is that both records should simply be deleted. Thank you for your help! -
I can't find the cause of the errors UserWarning: {% csrf_token %} was used in the template but the context did not provide a value
**My code should implement the function of user registration when entering non-existing data in the database, and when entering already existing data, the account is logged in. ** views.py: from django.http import HttpResponse, HttpResponseNotFound from django.shortcuts import redirect, render from django.template import RequestContext from django.template.loader import render_to_string from .forms import LoginForm from .models import user def register_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] if not user.objects.filter(username=username).exists(): user.objects.create_user(username=username, password=password) return redirect('login') else: # Здесь вы можете выдать сообщение о том, что пользователь с таким именем уже существует return render(request, 'main/index.html', {'form': form}) else: form = LoginForm() return render(request, 'index.html', {'form': form}) index.html: <form class="login", method="post"> {% csrf_token %} <div class="auth__form"> <input class="username__email" type="text" name="username" placeholder="Имя пользователя" autocomplete="off", maxlength="30", minlength="2"> </div> <div> <input class="user__password" type="password" name="password" placeholder="Пароль" autocomplete="off", minlength="10"> </div> <button class="enter__btn" type="submit">Войти</button> <div class="auth__footer"> <div class="auth__label"> Ещё нет аккаунта? <a class="create__pass" href="">Создать</a> </div> </div> </form>``` When running the local server, it displays the warning UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. When entering data into a form, it displays the error: Forbidden (CSRF token missing.): / I can't understand why these … -
How to Remove the Option to Add Users as Superusers to a Group in Wagtail
In my Wagtail project, I have a group that is allowed to add new users to the system. However, users belonging to this group can add others as superusers. How can I disable the option for this group to add users as superusers? Remove Admnistrador