Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return value instead of related object id in DynamicFieldsModelSerializer?
In django rest framework there is possibility to create serializer able to Dynamically modifying fields. Is there any chance to get value instead of related object ID? -
DigitalOcean: Django, Channels, Redis & Daphne
I am having issues with running websockets on DigitalOcean's App platform. I think I am fundamentally missing a configuration as it relates to Daphne. Here is my setup: Daphne 4.0.0 Channels-Redis 3.4.1 Settings.py INSTALLED_APPS = [ ... # Third-party 'channels', ... CSRF_TRUSTED_ORIGINS = [ 'https://blah.com', 'https://*.blah.com', ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ASGI.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev') import django django.setup() from django.core.asgi import get_asgi_application asgi_app = get_asgi_application() import api_waitlist.routing from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack application = ProtocolTypeRouter({ 'http': asgi_app, 'websocket': AllowedHostsOriginValidator(AuthMiddlewareStack( URLRouter( api_waitlist.routing.websocket_urlpatterns )) ), # new }) DigitalOcean Configurations DigitalOcean App: "run command" located under App>Settings>Run Command: daphne -b 0.0.0.0 -p 8080 config.asgi:application Redis Configuration: Redis is set up using DigitalOcean's managed Redis database. The connection string is provided by DigitalOcean. The app level variable "REDIS_URL" that contains the connection string is: rediss://default:password_here@fs-dev-redis-do-user-xxxx-0.b.db.ondigitalocean.com:25061 React Frontend (React is within the Django project scaffolding): The React frontend code to establish the websocket connection is: wb = new WebSocket("ws://127.0.0.1:8000/ws/waitlist/"); The frontend browser console error: -
AttributeError in ASGI/Daphne Django problem
I had done this tutorial for WebSocket with Django but I have this problem when I execute "python manage.py runserver": HTTP GET /chat/hello/ 200 [0.01, 127.0.0.1:65009] WebSocket HANDSHAKING /ws/chat/hello/ [127.0.0.1:65014] Exception inside application: 'int' object has no attribute 'decode' Traceback (most recent call last): File "D:\Projects\New Backend\venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\routing.py", line 116, in __call__ return await application( File "D:\Projects\New Backend\venv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "D:\Projects\New Backend\venv\lib\site-packages\channels\utils.py", line 57, in await_many_dispatch await task File "D:\Projects\New Backend\venv\lib\site-packages\channels\utils.py", line 49, in await_many_dispatch result = task.result() File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 367, in receive message_channel, message = await self.receive_single( File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 422, in receive_single content = await self._brpop_with_clean( File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 255, in _brpop_with_clean connection = self.connection(index) … -
Create child object in view as extra action
I have the following drf view: class HouseFullInfoViewSet(viewsets.ModelViewSet): queryset = House.objects.all() serializer_class = HouseSerializer permission_classes = (permissions.IsAuthenticated,) http_method_names = ['get', 'delete', 'post'] def retrieve(self, request, pk=None): house = self.get_object() serializer = self.get_serializer(house) return Response(serializer.data, HTTP_200_OK) @action(methods=['delete'], detail=True, url_name='remove_habitant') def remove_habitant(self, request,pk=None): house = self.get_object() habitant = CustomUser.objects.get(id = request.data['id']) house.habitants.remove(habitant) return Response({'msg':'Deletion success'}, status=HTTP_200_OK) @action(methods=['delete'], detail=True, url_name='remove_vehicle') def remove_vehicle(self, request,pk=None): house = self.get_object() vehicle = Vehicle.objects.get(id = request.data['id']) house.vehicles.remove(vehicle) return Response({'msg':'Deletion success'}, status=HTTP_200_OK) I am trying to make create_habitant and create_vehicle extra actions within this view, but I dont know how to do that exactly. I thought about something like this. @action(methods=['post'], detail=True, url_name='create_vehicle') def create_vehicle(self, request,pk=None): house = self.get_object() vehicle = Vehicle.objects.create(request.data) house.vehicles.add(vehicle) return Response({'msg':'Creation success'}, status=HTTP_200_OK) -
getting AttributeError: 'Settings' object has no attribute 'MODEL'
I have also installed pypi and tls using 'pip'. I am now trying to run 'python manage.py runserver' but after going to the local host and enter the url for checking whether the url is phishing or not, but getting this error after click on predict button. Any help on how to fix this and get my project running? -
django-tables2: row number ordering column not in DB
I am using django-tables2 to create a table, How to make the column row_number follow the sort of id and age columns? https://github.com/jieter/django-tables2/blob/master/docs/pages/ordering.rst import django_tables2 as tables import itertools class SimpleTable(tables.Table): row_number = tables.Column(empty_values=()) id = tables.Column() age = tables.Column() def render_row_number(self): self.row_number = getattr( self, 'row_number', itertools.count(self.page.start_index())) return next(self.row_number) def render_id(self, value): return f"<{value}" I think the best way is if statement if asc = itertools.count(self.page.start_index()) |row_number| id | age | | -------- | -------- |-------- | | 1 | id.1 | age | | 2 | id.2 | age | | 3 | id.3 | age | else desc = itertools.count(self.page.end_index(), -1) |row_number| id | age | | -------- | -------- |-------- | | 3 | id.3 | age | | 2 | id.2 | age | | 1 | id.1 | age | but i don't know how to implant that. -
Django + Docker + Postgres. FATAL: password authentication failed for user "postgres"
I don't know how to solve this simple error: django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" When I run docker-compose up, it can't connect to Postgres. I have tried stopping the service with docker-compose down -v. Please help me understand why am I getting this error. Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } docker-compose.yml: version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code env_file: - .env ports: - "8000:8000" depends_on: - db db: image: postgres:15 volumes: - ./data/db:/var/lib/postgresql/data/ environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres I've reviewed many tutorials and videos about this without success. -
Django Delete file from storage model not working from IIS but working on localhost
I have file Delete Model for deleting file chosen by user. for that after conforming from user that you want to sure delete file I have view.py code as below. @login_required(login_url='/login/') def Delete_files(request, pk): # Get the RadioFile object based on the primary key (pk) radio_file = get_object_or_404(RadioFile, pk=pk) print(radio_file) # get the file path and file object from the database file_obj = RadioFile.objects.get(id=pk).audio_file radio = radio_file.audio_file file_path =file_obj.path print(file_path) # Check that the user is the owner of the file if request.user != radio_file.uploaded_by: messages.success(request, 'File can be deleted by its owner.') # store the message in a message queue return redirect('/') elif os.path.exists(file_path) and not os.path.isfile(file_path): print(f"Error: {file_path} is not a file") response_data = {'success': False, 'error': str(e)} else: try : with transaction.atomic(): # Remove the many-to-many relationship with categories radio_file.categories.clear() radio_file.share_with.clear() # Delete the Radio object radio_file.delete() # Delete the file from the filesystem radio.close() radio.delete() messages.success(request, 'Radio and file deleted successfully.') response_data = {'success': True} except Exception as e: print(str(e)) messages.error(request, 'some error is coming while deleteing file.') # Redirect to the file list view return redirect('/') code deleting file when running from localhost. But it is giving me Win32 permission error says file already in … -
How to authenticate custom table of MySQL using Django?
I was trying to Authenticate my website using Django. Basically I am Using MySQL Database in the backend and I create a custom table that name is Signup. Data is successfully inserted into signup table but whenever I was trying to login it is showing 'No user found' my authenticate function is working properly but it did not fetch the data from signup table. What should I do? Here is so some Screenshot of my code what I have tried . This is the image of my settings.py where I connected MYSQL database using Django Login Code and Output This is image of my login page Code and the output is showing in the terminal Signup Code This is image of Signup Code where signup is correctly working MYSQL entered Datathis is the image of MySQL where I successfully entered my data from signup page -
Serializer has initial_data, but validated_data is empty
I passed some data via post request and Iwant to get the data in the key 'items' (it contains a list of objects that i need to use to create OrderItem). The problem is I don't get any data in the validated_data after calling is_valid(). However the data can be found in serializer.initial_data, Printing what is in serializer.validated_data() shows that it's empty ({}). I don't see where the issue is and why I can't get the data to be in validated_data after using is_valid(). Any help would be very much appreciated. Thanks An Order has 1 or many OrderItems. The model of OrderItem class OrderItem(models.Model): """Model for an item in an order""" order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name="items") bookedition = models.ForeignKey(BookEdition, on_delete=models.PROTECT, related_name="orderitems") quantity = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=8, decimal_places=2) price = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self): return '%s' % self.id The serializer of OrderItem class OrderItemSerializer(serializers.ModelSerializer): """Serializer for OrderItem""" class Meta: model = OrderItem fields = [ 'bookedition', 'quantity', 'unit_price', 'price' ] The model of Order class Order(models.Model): """Model for an order""" PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] payment_status = models.CharField(max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING) customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name="orders") … -
Access to the date details in a Django database
I'm currently going over the official Django tutorial. At some point we're shown how to filter keys by the year of the the automatically-filled pub_date column. >>> Question.objects.get(pub_date__year=current_year) <Question: What's up?> But somehow the syntax when calling the year of the date directly has to be with a . instead of a __... In [56]: q=Question.objects.get(pub_date__year=current_year) In [57]: q.pub_date__year --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In [57], line 1 ----> 1 q.pub_date__year AttributeError: 'Question' object has no attribute 'pub_date__year' In [58]: q.pub_date.year Out[58]: 2023 Is there some reason it has to be different when called outside of the parenthesis? -
CSRF token (in Django) vs Session token
From what I understand CSRF token is generated on the server and sent to the client on every login. When client sends the request, CSRF token is sent with it and client token is checked if it matches server token. Isn't this how Session token works as well? The only difference I see is that CSRF token isn't saved anywhere (it's in the hidden field) as opposed to session token which is saved is session cookie? If that's the case, then how Django CSRF cookie works? From other post: When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. The site should require every form submission to include this pseudorandom value as a form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An attacker cannot read any data sent from the server or modify cookie values, per the same-origin … -
DJANGO : ManyToManyField self symetrical unique together how to mange it?
I have some trouble trying to fetch some manytomanyrelated data in by Django Application Here is my model : SoftwareVersion(models.Model): id = models.AutoField( primary_key=True, db_index=True ) ... Some other fields ... incompatibilities= models.ManyToManyField( "self", symmetrical=True, blank=True, default=None, through="Incompatibilities" ) Incompatibilities(models.Model): id = models.AutoField( primary_key=True, db_index=True ) softwareversion_a = models.ForeignKey( "SoftwareVersion", models.CASCADE, db_index=True, db_column='softwareversion_a ', related_name='softwareversion_a', verbose_name="software version a", ) softwareversion_b = models.ForeignKey( "SoftwareVersion", models.CASCADE, db_index=True, db_column='softwareversion_b', related_name='softwareversion_b', verbose_name="softwareversion_b", ) status = models.BooleanField( verbose_name='Status', default=False ) class Meta: unique_together = (('softwareversion_a', 'softwareversion_b'),) To this I add in the SoftwareVersion's save method a logic to create related Incompatibilities for each new software version. I have tried several way to do it (with a loop or with a bulk_create) here is the bulk create function i use : # Inside SoftwareVersion Model class def save(self, force_insert=False, force_update=False, using=None, update_fields=None) -> None: save = super().save(force_insert, force_update, using, update_fields) Incompatibilities.objects.bulk_create( (Incompatibilities( softwareversion_a=self, softwareversion_b=software_version, status=False ) for software_version in SoftwareVersion.objects.exclude(self)), ignore_conflicts=True, batch_size=1000 ) return save First problem I have is this method ignore the unique_together constraint, it creates duplicates. Before i was using a loop on each SoftwareVersion to create an object but it was too long so i wanted to use bulk_create but it seems … -
Django Loglevel is undefined in project app views.py
I try to log something with INFO level in the views.py in a created app in my Django project. When I initialize the logger with: logger = logging.getLogger(__name__) the loglevel is set to 0 which means undefined. Why does it not read the log level defined in the settings py? I start the project in the pycharm IDE and a environment variable with name LOGLEVEL is set to INFO (I checked if the loglevel was correctly read by debugging the settings.py on startup and it is correct set to INFO) Project Structure: myApp views.py ... myproject settings.py ... settings.py loggin config: # Disable Django's logging setup LOGGING_CONFIG = None LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { # Use JSON formatter as default 'default': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', }, 'django.server': DEFAULT_LOGGING['formatters']['django.server'], }, 'handlers': { # Route console logs to stdout 'console': { 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'django.server': DEFAULT_LOGGING['handlers']['django.server'], }, 'loggers': { # Default logger for all modules '': { 'level': LOGLEVEL, 'handlers': ['console', ], }, # Default runserver request logging 'django.server': DEFAULT_LOGGING['loggers']['django.server'], } } views.py logger = logging.getLogger(__name__) def teams_overview(request): try: print(f"loglevel set: {logger.level}") print(f"info logleve: {logging.INFO}") logger.error("error") logger.info("info") logger.warning("warning") logger.critical("critical") logger.debug("debug") output: error warning … -
How to pass json data to frontend using Django
I have response from another api of json data and i want to send this json data to my frontend to parse this json there But when im using return JsonResponse it just returns html with json i dont need that, i want to return blank html with json which was send on front and frontend with js will parse it views.py def json_project_budget(request): session = requests_cache.CachedSession('project_budget_cache') url = config('REPORT_PROJECT_BUDGET') response = session.get(url=url, auth=UNICA_AUTH).json() queryset = [] for item in response: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) obj = parsed_json.ObjectGUID for budget in parsed_json.BudgetData: budget.SectionGUID = CleanSections.objects.get(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) return JsonResponse(response, safe=False) I will update bcs i think that i understand my problem I have problems in url or something like that I have ListView which renders my template and the main question how am i suppose to send this function json_project_budget in my template to get json data? views.pyy class ShowProjectBudgetList(ListView): login_url = '/login/' redirect_field_name = '' template_name = 'customer/customer_home.html' context_object_name = 'json_list' allow_empty = True # paginate_by = 5 def get_queryset(self): return None urls.py path('customer/', ShowProjectBudgetList.as_view(), name='customer_view'), path('customer/', json_project_budget, name='json_project_budget'), -
Django cannot find TemplateDoesNotExist
I am trying to create a login page using django and I am getting this error. TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 4.1.5 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/template/loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: /Library/Frameworks/Python.framework/Versions/3.11/bin/python3 Python Version: 3.11.1 Python Path: ['/Users/jasonfan/Desktop/Swe/TAPortal', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python311.zip', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages'] Server time: Mon, 20 Mar 2023 17:02:00 +0000 I have a couple ideas of where the problem may lie. I created a templates/registration/login.html. Does it matter which directory i put these subdirectories in? My file structure is attached. This is my settings.py folder. I modified TEMPLATES. I added 'DIRS': [BASE_DIR/"templates"], I also added LOGIN_REDIRECT_URL = "/" at the bottom. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/"templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I also modified urls.py adding urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include("django.contrib.auth.urls")) ] I modified the login.html to a basic login screen and that is where I am trying to get to when i run server. I do http://127.0.0.1:8000/accounts/login/ -
Django Rest Framework: Remove Appended "[]" from List Parameter
I have a django rest framework application set up with two packages: One's called djangorestframework-camel-case (to "camelizes" the parameters in the API docs) and the other is drf-spectacular (to automatically generate Swagger docs for my API). The camel case package also has the effect that it causes parameters from the request data sent from the frontend (in camelCase) to be received in the Python backend in snake_case. However, I just found out that when one of the requests from the frontend contains a list of data, lets say dataList = ["1", "2", "3"], the parameter is received in the Python backend as a dictionary with the key data_list[]. Is there a setting to remove that [] at the end? Its messing up with the rest of my logic. -
Adding items to wishlist
so Im trying to work on adding a wishlist item to the wishlist page. So Im creating a view to add a wishlist to the page and a view to show the items ive added. But the issues ocurs when i press the add to wishlist button on a product.The item i added is not showing up in the wishlist page for some reason i cant seem to figure out. I get the error of add_to_wishlist() missing 1 required positional argument: 'product' Here is my code below: views.py: @login_required def wishlist(request): wishlist, created = Wishlist.objects.get_or_create(user=request.user.userprofile) return render(request, 'products/wishlist.html') @login_required def add_to_wishlist(request, product, product_id): product = Product.objects.get(id=product_id) return redirect('wishlist') @login_required def remove_from_wishlist(request, product_id): product = get_object_or_404(Product, pk=product_id) wishlist = Wishlist.objects.get(user=request.user.userprofile) wishlist.products.remove(product) return HttpResponseRedirect(reverse('add_to_wishlist')) models.py: class Wishlist(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) product = models.ManyToManyField(Product, blank=True) wishlist.html: {% block content %} <div class="overlay"></div> <div class="container"> <h1>My Wishlist</h1> <div class="row"> {% if wishlist.products.all %} {% for product in wishlist.products.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <div class="card-body"> <h2 class="card-title">{{ product.name }}</h2> <p class="card-text">{{ product.description }}</p> <p class="card-text">$ {{ product.price }}</p> <form action="{% url 'remove_from_wishlist' product.id %}" method="POST"> {% csrf_token %} <button class="btn btn-danger" type="submit">Remove from Wishlist</button> </form> </div> </div> </div> {% endfor %} … -
Inertia Django Vite not working on deployment
I'm trying to deploy this template to fly.io (https://github.com/mujahidfa/inertia-django-vite-vue-minimal.git). Additionally I installed "gunicorn" as WSGI-server. I got it running locally but if I deploy it, I get a CORS-error because Vite ist still requesting localhost. All I see is a white page. index.html: {% load django_vite %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% vite_hmr_client %} {% vite_asset 'main.ts' %} <title>Inertia + Django + Vite + Vue minimal</title> </head> <body> {% block inertia %}{% endblock %} </body> </html> In the browser it gets resolved to: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script type="module" src="http://localhost:5173/static/@vite/client"></script> <script type="module" src="http://localhost:5173/static/main.ts"></script> <title>Inertia + Django + Vite + Vue minimal</title> </head> <body> <div id="app" data-page="{&quot;component&quot;: &quot;Index&quot;, &quot;props&quot;: {&quot;name&quot;: &quot;World&quot;}, &quot;url&quot;: &quot;http://nameless-mountain-1344.fly.dev/&quot;, &quot;version&quot;: &quot;1.0&quot;}"></div> </body> </html> I think the interesting parts are: {% vite_hmr_client %} {% vite_asset 'main.ts' %} <script type="module" src="http://localhost:5173/static/@vite/client"></script> <script type="module" src="http://localhost:5173/static/main.ts"></script> Has anybody an idea how to get it working? I couldn't figure it out for days now. I've tried fiddling with the Dockerfile, but I'm still in the eary phase with fullstack-developement. Also in the vite.config.ts I've tried many … -
why do i get Forbidden (403) CSRF verification failed. Request aborted. when I'm trying to register?
from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm def register(response): if response.method == 'POST': form = UserCreationForm(response.POST) if form.is_valid(): form.save() else: form = UserCreationForm() return render(response, 'register/register.html', {'form':form}) html {% extends 'libraryfinish/base.html' %} {% block title %} Create an account {% endblock %} {% block content %} <form method="POST", class="form-group"> {% csrf_token %} {{form}} <button type="submit", class="btn btn-success">Register</button> </form> {% endblock %} I found that I should pass the RequestContext in my render_to_response for the context processors to actually be run, but I'm not using render to response from django.views.decorators.csrf import csrf_protect @csrf_protect doesn't work -
ModelForm groupé - can_delete=True, impossible de sélectionner les checkbox par JS
Je souhaite afficher un message d'avertissement aux utilisateurs qui cochent la case correspondant à form.DELETE d'un formulaire groupé. J'utilise un script JQuery, mais impossible de filtrer les champs sur leur nom (contenant DELETE) dans ce qui est généré par Django. J'ai ajouté en début de page une checkbox avec name = Truc et utilisé le même script (avec filtrage sur le nom contenant "truc", et là, ça marche... <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('input[name*="truc"]').change(function () { alert("Checkbox cliquée. Name contient truc"); }); }); </script> <script type="text/javascript"> $(document).ready(function () { $('input[name*="DELETE"]').change(function () { alert("Checkbox cliquée. Name contient DELETE"); }); }); </script> <Div class="row"> <form method="post"> <input type="checkbox" name="truc" id="cbox"> {% csrf_token %} {{ data_form_set.management_form }} <br> <br> <table class="table table-hover table-striped" data-toggle="table" data-pagination="true"> <thead> <tr> <th>id</th> <th><i class='bx bx-trash nav_icon'></i></th> <th>Champ 1</th> <th>Champ 2</th> </tr> </thead> <tbody> {% for form in data_form_set %} <tr> <td>{{ form.id }}</td> <td>{{ form.DELETE }}</td> <td>{{ form.champ1 }}</td> <td>{{ form.champ2}}</td> </tr> {% endfor %} </tbody> </table> <br> <button name="enregistrer" type="submit" class="btn btn-primary"> <i class='bx bx-save nav_icon'></i> Sauvegarder </button> </form> </form> </div> -
Django template list not showing all the images
I am working on a Django project and its a simple product website which will look like: First page- 1.Electronics link 2.Toys link Second page after clicking on the link: For electronics I have 3 item listed and same for toys. How to show images of different product once user will click on it along with the list of items. I have index.html which will show 1.Electronics link,2.Toys link <!DOCTYPE html> {% load static %} <html> <head> <title></title> <link rel="stylesheet" href="{% static "productApp/css/index.css" %}" </head> <body> <h1>Welcome to our online shoping portal</h1> <ul> <li><a href="/electronics">Electronics<img src="productApp/images/electronics.jpeg"/></a></li> <li><a href="/toys">Toys</a></li> <li><a href="/shoes">Shoes</a></li> </ul> </body> </html> Product.html <!DOCTYPE html> {% load static %} <html> <head> <title></title> <link rel="stylesheet" href="{% static "productApp/css/product.css" %}" </head> <body> <h1>{{heading}}</h1> <ul> <!-- <img src="{% static "productApp/images/electronics.jpg"%}"/> --> <li>{{product1}}</li> <li>{{product2}}</li> <li>{{product3}}</li> </ul> </body> </html> -
NOT NULL constraint failed: app_User.user_id
I've made an abstractuser model so I can register users through email, and when I'm trying to register new user I get this error NOT NULL constraint failed: app_shahadati_user.user_id How can I fix this error? models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Shahadati_user(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) user_nID=models.PositiveIntegerField() def __str__(self): return self.user.email forms.py class CustomUserCreateForm(forms.ModelForm): password = forms.CharField() password_validation = forms.CharField() class Meta: model = CustomUser fields = ['first_name','last_name','email'] def clean_password_validation(self): pwd1 = self.cleaned_data.get('password') pwd2 = self.cleaned_data.get('password_validation') if pwd1 and pwd2 and pwd1 != pwd2: raise ValidationError("Passwords don't match") return pwd2 def save(self, *args, **kwargs): self.instance.set_password(self.cleaned_data.get('password')) return super().save(*args, **kwargs) class ShahadatiUserForm(forms.ModelForm): class Meta: model = Shahadati_user fields =['user_nID'] views.py def user_reg(request): if request.method == 'POST': form = CustomUserCreateForm(request.POST, request.FILES) form_ShU = ShahadatiUserForm(request.POST,request.FILES) if form.is_valid() and form_ShU.is_valid(): form.save() form_ShU.save() else: pass return render(request, 'Register.html', {}) -
How do I get typing working in python mixins?
I have a mixin that will always be used with a specific type of class i.e. a subclass of widgets.Input I want to override a few methods using the mixin, and I'm referencing attributes that exist on widgets.Input in my custom methods How do I tell the python type system that this mixin extends the widgets.Input interface without inheriting from widgets.Input? Bonus: Can I tell the type system that this mixin can only be used with subclasses of widgets.Input? from django.forms import widgets class MaskedWidgetMixin: def format_value(self, value): return "" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) # <--- super().get_context does not exist context["widget"]["attrs"] = self.build_attrs(self.attrs, attrs, value) # <--- self.attrs does not exist return context def build_attrs(self, base_attrs, extra_attrs=None, value: str = ""): attrs = super().build_attrs(base_attrs, extra_attrs) # <--- super().build_attrs does not exist if value: attrs.update({"placeholder": "* ENCRYPTED *", "required": False}) return attrs class EncryptedTextInputWidget(MaskedWidgetMixin, widgets.TextInput): pass class EncryptedTextareaWidget(MaskedWidgetMixin, widgets.Textarea): pass -
Django admin model
Подскажите пожалуйста, как в model переменной присвоить имя класса: Т.е. есть class abonents(models.Model) и нужно переменной name присвоить имя abonents Либо можно ли с class Meta: verbose_name = "ПРОВЕРКА ВСЕХ АБОНЕНТОВ " verbose_name_plural = " ПРОВЕРКА ВСЕХ АБОНЕНТОВ " Передать в list_display admin модели. ничего не могу найти в нете похожего