Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using widgets to change the CSS of label in Django forms
I am trying to apply CSS styling to the admin login form in Django (version 3.1.3). I am able to customise the inputs easily enough using Widgets via the 'forms.TextInput(attrs={'class':'textinputclass'}) method however there seems to be no way to add CSS class to the labels? I can set the label to "false" so that it doesnt show up at all, but ideally I would like to be able to associate a CSS class to it. My code below shows the widgets being used for the text input for username and password. How do I do something similar for the label? ''' class MyAuthForm(AuthenticationForm): class Meta: model = Lesson fields = ['username', 'password'] def __init__(self, *args, **kwargs): super(MyAuthForm, self).__init__(*args, **kwargs) self.fields['username'].widget = forms.TextInput(attrs={'class': 'input', 'placeholder': 'Username'}) self.fields['username'].label = False self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'input', 'placeholder': 'Password'}) self.fields['password'].label = False ''' -
How to populate model's new fields from OneToOneField in Django?
In Django 3.1.2, I would like to copy data in a OneToOneField to multiple fields. I want to change class A(models.Model): name = models.TextField() description = models.TextField() class B(models.Model): a = models.OneToOneField(A, on_delete=models.CASCADE, related_name='b_a') to class A(models.Model): name = models.TextField() description = models.TextField() class B(models.Model): name = models.TextField() description = models.TextField() while keeping existing data. Thank you for your time in advance! -
NameError: name 'TypeError' is not defined in Apache logs
My apache error logs are full of this repeating error message. While my app works fine and apache continues to serve it I am unable to find the cause of other errors because for some reason this is the only thing being logged. My app is a Django app running apache2 and mod-wsgi NameError: name 'TypeError' is not defined Exception ignored in: <function BaseEventLoop.__del__ at 0x7fefd6b13040> Traceback (most recent call last): File "/usr/lib/python3.8/asyncio/base_events.py", line 654, in __del__ NameError: name 'ResourceWarning' is not defined Exception ignored in: <function Local.__del__ at 0x7fefd6b0b430> Traceback (most recent call last): File "/srv/example/env/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ -
Django - StringRelatedField() not applied to query results when .values() provided
In my Django app, I'm finding that a StringRelatedField() on a serializer class isn't being applied when that serializer is used on a filter query where a set of field values have been specified - though it does work if the query returns all fields. Whew, that's a mouthful, let me break it down - I have two models, Report and User; each Report is associated with a User. Ideally, I want to query reports via get_queryset and in each report record, the value of the associated user should be the result of StringRelatedField(), the return value of the __str__ method on the User model (which is the user's first and last names). If my query returns all fields, this works perfectly... so the query Report.objects.filter(location__within=some_other_model.region) does the trick. However, I've found that querying only for the values that I actually need vastly improves performance, so my preference is to query like so: Report.objects.filter(location__within=some_other_model.region).values('id', 'location', 'user',) but the results of that query have the UUID foreign key of the record from the User table, they do not seem to have been replaced with the StringRelatedField(). Below, I have the view and serializer for Report, as well as the User model. … -
Square client sdk returns KeyError:'' when using list_customers
I have this get function below that pulls the list of customer profile associated in a Square account. def get(self, request, format=None): result = customers_api.list_customers() if result.is_success(): return Response(result.body) elif result.is_error(): return Response(result.errors) I also have a simple test for it. def test_square_customer_list_get(self): url = reverse('get_customers') response = self.client.get(url) assert response.status_code == 200 For some reason it is failing and I can't seem to find the issue on my code. And based on the response from the terminal (Attached below) it is pointing to the Square SDK function. self = <core.tests.test_views.TestCoreViews testMethod=test_square_customer_list_get> def test_square_customer_list_get(self): url = reverse('get_customers') > response = self.client.get(url) core/tests/test_views.py:280: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.8/site-packages/rest_framework/test.py:286: in get response = super().get(path, data=data, **extra) .venv/lib/python3.8/site-packages/rest_framework/test.py:203: in get return self.generic('GET', path, **r) .venv/lib/python3.8/site-packages/rest_framework/test.py:231: in generic return super().generic( .venv/lib/python3.8/site-packages/django/test/client.py:470: in generic return self.request(**r) .venv/lib/python3.8/site-packages/rest_framework/test.py:283: in request return super().request(**kwargs) .venv/lib/python3.8/site-packages/rest_framework/test.py:235: in request request = super().request(**kwargs) .venv/lib/python3.8/site-packages/django/test/client.py:710: in request self.check_exception(response) .venv/lib/python3.8/site-packages/django/test/client.py:571: in check_exception raise exc_value .venv/lib/python3.8/site-packages/django/core/handlers/exception.py:47: in inner response = get_response(request) .venv/lib/python3.8/site-packages/django/core/handlers/base.py:179: in _get_response response = wrapped_callback(request, *callback_args, … -
Django auto_now vs auto_now_add
some problem when you confuse auto_now and auto_now_add different. How are auto_now or auto_now_add work? auto_now : Time will be created every time when use models.save() or models.create() but it don't work if you use query.update(). it only update some data but it do not update date automatically auto_now_add : Time will be create only first time when use models.save() or models.create() how to use it ? auto_now_add should use with created_date and auto_now should use with updated_date created_date = models.DateTimeField(auto_now_add = True) updated_date = models.DateTimeField(auto_now = True) -
Open-edX: staff@example.com with default password: could not login
Anyone has installed Oped-edX & have login issues resolved? Have Open-edX installed. Navigate to the login page. Input default login staff@example.com & default password "edx". Observe "could not login" error. open-edx login issue -
how to use django forms and models to save multiple checked data for the user?
Hey guys I am trying to develop a subscription based news aggregrator using django where user can login and subscribe to different news topics which appear in their dashboard based on their subscription. Can anybody help me with how to take multiple selected form data for topic selected by user and save it to the database for that user so that the specific subscription topics can also be retrieved later for dashboard news content ? ![Image link for form] [1]: https://i.stack.imgur.com/4o5J3.png -
How can I speed up batch creating of multiple related objects?
I use this for simplicity. Let say I have 2 models here A and B. I want to use A.objects.bulk_create(a_list) and B.objects.bulk_create(b_list) to batch create both A and B objects. But, B reply on A. So, I have to batch creating those objects in a for loop like this: for _ in some_list: a = A.objects.create(**kwargs) B.objects.create(a=a, **kwargs) The problem is that the speed is too slow and I wannt speed up. So, is there a workaround to speed up this? -
How to dynamically query and visualize postgis data using GeoDjango and Openlayers?
I am trying to implement dynamic query functionality in GeoDjango and OpenLayers. First, I filter the data and return it in GeoJSON format using Django serialize. Then, the return GeoJSON data visualize using OpenLayers 6. It works fine. But, When I try to filter data dynamically, it is not working. I don't understand the problem. Can anybody help me please? // GeoDjango Model from django.contrib.gis.db import models class Boundary(models.Model): division = models.CharField(max_length=50) district = models.CharField(max_length=50) upazila = models.CharField(max_length=50) union = models.CharField(max_length=50) geom = models.MultiPolygonField(srid=4326) def __str__(self): return self.division // views.py def boundary_data(request): """ bnd = Boundary.objects.filter(district="Khulna")""" // it is working fine name=request.GET.get("district") bnd = Boundary.objects.filter(district__iexact=name) // not working boundary = serialize('geojson', bnd) return HttpResponse(boundary, content_type='JSON') // urls.py from django.urls import path from . import views urlpatterns = [ path('boundary-data/', views.boundary_data, name="boundary-data"), path('bgd/', views.MapView.as_view(), name="bgd"), ] // query form <form method='GET' class="form-inline" action=""> <input class="form-control mr-sm-2" id="district" name="district" type="text" placeholder="Search"> <button class="btn btn-success" type="submit">Search</button> </form> //OpenLayers Code var style = new ol.style.Style({ fill: new ol.style.Fill({ color: 'gray', }), stroke: new ol.style.Stroke({ color: 'white', width: 1, }), text: new ol.style.Text() }); var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }), new ol.layer.Vector({ source: new ol.source.Vector({ format: … -
How can I fix my REST view to PATCH and serialize updates to an ArrayField() in my model?
I have a view that is used to update a field in my model. It's represented as follows: stock_list = ArrayField(models.CharField()) Each value in the ArrayField is separated by commas. I used a custom serializer method to allow for my backend to separate the elements in my PATCH obj by commas. serializers.py: class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation(obj) # convert list to string return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") # convert string to list return super().to_internal_value(self, data) class StockListSerializer(serializers.ModelSerializer): stock_list = StringArrayField() class Meta: model = Bucket fields = ("stock_list",) Below is my view that I use, the URL's are linked up correctly, however I'm setting up my view wrong: view.py: class EditBucketSymbols(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = StockListSerializer def get_queryset(self): return Bucket.objects.all() def get_object(self, queryset=None, **kwargs): item = self.kwargs.get('pk') return get_object_or_404(Bucket, pk=item) def patch(self, request, *args, **kwargs): item = BucketDetail.get_object(self) data = request.data item.stock_list = data.get("stock_list", item.stock_list) serializer = StockListSerializer(data=item.stock_list, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is the PATCH error I get: { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } I'm not sure … -
Trying to create my first Django webpage but nothing loads when I run manage.py
I am following this tutorial: https://realpython.com/get-started-with-django-1/. I followed everything exactly the same but when I run manage.py, localhost:8000 only displays a blank webpage. I have a very simple HTML file that should display "Hello, World!" but it's not loading. Here is the code in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello_world', views.py: from django.shortcuts import render # Create your views here. def hello_world(request): return render(request, 'hello_world.html', {}) My hello_world.html file: <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <h1>Hello, World!</h1> </head> <body> </body> </html> The code in my project "personal_portfolio" personal_portfolio\urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('hello_world.urls')), ] And finally hello_world\urls.py: from django.urls import path from hello_world import views urlpatterns = { path('', views.hello_world, name = 'hello_world'), } I've made sure all the files are in the right place, but I can't figure out why localhost:8000 only displays a white page. When I run the hello_world.html file locally, it works just fine. Like this: local html file Any tips would be much appreciated. I'm frustrated I can't get this to work. -
Querying Models in Django Channels
I have been trying to query my database from my consumers.py but seems the query isn't working as I keep getting this error which shows that query wasn't sent. Here is the error : File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/generic/websocket.py", line 196, in websocket_receive await self.receive(text_data=message["text"]) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/Kitchen_Order/Order_app/consumers.py", line 52, in receive info = order_data_json['info'] KeyError: 'info' WebSocket DISCONNECT /ws/orders/ [127.0.0.1:53953] Here is my consumers.py set up: import json from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async def _get_order_info(self, number): return Order.objects.get(order_number = number) async def connect(self): self.groupname = 'kitchen' await self.channel_layer.group_add( self.groupname, self.channel_name, ) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard( self.groupname, self.channel_name, ) await super().disconnect(code) async def take_order(self, event): number = event['number'] details = event['details'] info = await self._get_order_info(number) await self.send(text_data=json.dumps({ 'number' : number, 'details' : details, 'info' : info, })) async def receive(self, text_data): order_data_json = json.loads(text_data) number = order_data_json['number'] details = order_data_json['details'] info = order_data_json['info'] await self.channel_layer.group_send( self.groupname, { 'type': 'take_order', 'number' : number, 'details' : details, 'info' : info, } ) Websocket code on the front end: document.querySelector('#submit').onclick = function(e) { const numberInputDom = document.querySelector('#id_order_number'); … -
Django: Adding multiple inline instances to a form
I want to have a button that allows the user to add another model instance to a parent model in a CreateView. In other words, I would like a button that works the same as the "Add another evidence" button in this screenshot of the admin page: My relevant views are: class EvidenceInline(InlineFormSet): model = Evidence factory_kwargs={ 'extra': 0, } form_class = NewClaimForm class ClaimCreateView(CreateWithInlinesView): model = Claim inlines = [EvidenceInline,] fields = ['claim_text', 'category'] template_name = 'bothsides/claim_form.html' def forms_valid(self, form, inlines): self.object = form.save() if 'add' in form.data: print(form.data['add']) return HttpResponseRedirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super(CreateWithInlinesView, self).get_context_data(**kwargs) context['num_extra'] = self.model.num_evidence return context And my template is: {% load crispy_forms_tags %} <form method="POST" name="add-form"> {% csrf_token %} {{ form|crispy }} <div> {% for form in inlines %} {{ form|crispy }} {% endfor %} <input type="submit" value="Add Supporting Evidence" name="add"/> </div> </form> Incrementing the 'extra' property of EvidenceInline works except for it refreshes the page which I do not want. I am new to Django and understand that I may have made numerous mistakes here. Any help is appreciated. -
Django - How to automatically create a .docx file and save it to a model's FileField?
Here's my use case. I have a rental contract template (.docx file). I want to populate the fields of this contract by pulling data from my models and injecting them into the template (using Jinja tags), then save the output file directly to the database. So far so good. My problem is that I currently do this as a two step process; 1) open template, populate and save as new file; 2) upload the file as a FileField to my Model, thereby creating a duplicate... Is there a way for me to create and store the formatted file without first having to save it? (thus avoiding duplicates) According to this thread, the suggested approach is to use django.core.files.base.ContentFile and pass the content of the file as a string, like so. self.lease_draft.save("Name of the file", ContentFile("A string with the file content")) My problem is that ContentFile() only accepts strings or bytes as parameters. My input is a populated .docx file (DocxTemplate object), not a string. Any suggestions on how to approach this? Models.py class Booking(models.Model): lease_draft = models.FileField(upload_to='lease_drafts/', null=True) Views.py from django.core.files import File def populate_docx(self, template_path, context): draft_lease = DocxTemplate(template_path) /// Gets the template draft_lease.render(context) /// Populates the template self.lease_draft.save('Lease … -
Can you add a Browsable API into an ASP.NET application?
The Django web framework has a Browsable API and I would like to implement something similar in my ASP.NET (with ReactJS) application. Essentially, suppose that there's an API endpoint called api/test; I would like to be able to navigate to https://.../api/test in a web browser and be presented with a web page (React component) that contains what api/test normally returns but in a better, human-readable format like Django does. But when accessed as an API, it returns the content without the surrounding HTML page. The simple controller would look like: [ApiController] [Route("api/[controller]")] public class TestController : ControllerBase { [HttpGet] [Produces("text/json")] public IList<string> Get() { return new string[] { "hello", "world" }; } } It seems that something similar to Content Negotiation would work. So, I would either have to implement a custom formatter (which I'm not sure is the right approach) or make a middleware of my own. Does this sort of thing already exist somehow? Any suggestions on how to implement it if it doesn't already exist? Thanks in advance! -
how to display products from every seller and make it changing every time page reloading?
The default displaying in django is for the latest product first . how can I change the viewing way ? my view.py coding @login_required() def products(request): f = ForSaleProductFilter(request.GET, queryset=Product.objects.filter(status=ProductStatus.LISTED).order_by('-pub_date')) paginator = Paginator(f.qs, NB_PER_PAGE) page = request.GET.get('page') pproducts = paginator.get_page(page) request.session['products_filters'] = request.GET return render(request, 'products/products.html', {'filter': f, 'pproducts': pproducts}) sale = PorductSale() sale.product = product sale.buyer = buyer sale.seller = seller -
Django IntegrerField +1 by viewing page
I need to make object view counter, how i can make +1 to django models.IntegerField by viewing page with using of DetailView -
Typeerror in Django-Channels
I am trying to send data from client-side in my django app but I keep getting this error and the socket disconnects. I am lost to why this is so, This is the error: Exception inside application: receive() got an unexpected keyword argument 'text_data' Traceback (most recent call last): File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/routing.py", line 160, in __call__ send, File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/generic/websocket.py", line 196, in websocket_receive await self.receive(text_data=message["text"]) TypeError: receive() got an unexpected keyword argument 'text_data' WebSocket DISCONNECT /ws/orders/ [127.0.0.1:49984] This is the consumers.py: import json from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async … -
Django rest framework do I need to close file before the response
I have an endpoint returning a FileResponse. When I use a code like the following I get an error 'read of closed file' The code looks like this: @action(detail=True, methods=['get'], url_path='download') def get_file(self, request, pk=None): instance = self.get_object() fa = getattr(instance, file_location) if fa: with open(fa.path, 'rb') as f: response = FileResponse(f, as_attachment=True) return response else: raise FileNotFound when I remove the with-block it works. Do I need the with block? -
How to display an avatar?
I made a function that generates avatars for users when they create a profile: users/models.py def random_image(): directory = os.path.join(settings.BASE_DIR, 'media') files = os.listdir(directory) images = [file for file in files if os.path.isfile(os.path.join(directory, file))] rand = choice(images) return rand class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar_new = models.ImageField (default=random_image) def __str__(self): return f'{self.user.username} Profile' For changing avatar i am using django-avatar There is a line like this (settings): DEFAULT_URL = ("avatar/img/default.jpg") I would like to display not a static image (default.jpg), but the result of the random function, which assigned the user an avatar. How can I make sure that the default url contains not a static image, but the result of the field avatar_new? Tried itDEFAULT_URL = Profile.avatar_new error. Need help pls -
GithubOauth gives "non_field_errors": [ "Incorrect value" ] after posting code to GithubLogin view
I am using GitHub OAuth to login to my django_RESTFRAMEWORK api. with front end React js. Oauth works fine when i try to login with my github account. but gives "non_field_errors": [ "Incorrect value" ] i am very certain that code is correct. and the fact this works for my github account. please help http://localhost:8000/accounts/dj-rest-auth/github/?code=***************** -
Adding Websockets to Django server deployed on Azure Appservice
I have a Django application which starts a server using the websockets https://websockets.readthedocs.io/en/stable/index.html library for Python. The manage.py file looks like this: import os import sys import asyncio import threading if __name__ == '__main__': os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'UPH_Chart_Re.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc try: from WebsocketClass import StartServer x = threading.Thread(group=None, target=StartServer, name="Websocket Thread") x.daemon=True x.start() except ImportError as exce: raise ImportError("Importing WebsocketsClass failed") from exce execute_from_command_line(sys.argv) The StartServer function starts a websocket server using asyncio: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) start_server = websockets.serve(Receive, "localhost", 5001) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() The Django webpages and websocket server work perfectly on my local machine. The problem I'm running into now is that when deploying to Azure Web App Service, I don't seem to be able to access the sockets. My Web App Service has Websockets set to enabled, and I get no errors on my deployment. However, I can't seem to connect to the websocket at all. I have tried setting the port to 443, which is considered a forbidden port since … -
Django and chartjs using json (doesn't show chart)
I'm trying to display a chart in Django with data from database using JSON. When I go to /distancechart I see my data printed. But when it comes to chart I get blank screen, nothing shows. I was using some tutorials from internet and I have no idea what is wrong here... views.py fragment def distancechart(request): labels = [] data = [] queryset = Distance.objects.values('day', 'distance') for entry in queryset: labels.append(entry['day']) data.append(entry['distance']) return JsonResponse(data={ 'labels': labels, 'data': data, }) distance.html {% extends 'index.html' %} {% block content %} <canvas id="distancechart" width="1000" height="400"></canvas> <script> $.get('{% url "distancechart" %}', function(data) { var ctx = $("#distancechart").get(0).getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets: [{ label: 'Distance', data: data.data, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> {% endblock %} -
Django checkbox form does not update
I have form where I want to let users add their skills by using check boxes. I can get the check boxes to render in the template but I can't get it to update if the user select a check box, nor am I able to let it show current active skill. I am a bit confused what's wrong, any ideas? My models.py file class Skills(models.Model): math = models.BooleanField(default=None) language = models.BooleanField(default=None) driving = models.BooleanField(default=None) account = models.ForeignKey( Account, on_delete=models.CASCADE, default=None, null=False ) My forms.py file class SkillsForm(forms.ModelForm): SKILLS = ( (True, 'math'), (True, 'language'), (True, 'driving'), ) skills = forms.MultipleChoiceField(choices=SKILLS, widget=forms.CheckboxSelectMultiple) def clean_skills(self): print(self.cleaned_data["skills"], self.cleaned_data["skills"][0]) return self.cleaned_data["skills"][0] class Meta: model = Skills fields = ( 'math', 'language', 'driving', ) My views.py file @login_required def userSkills(request): if request.user.is_authenticated: if request.method == "POST": skills = SkillsForm(request.POST, instance=request.user) if skills.is_valid(): skills.save() return HttpResponseRedirect(request.path_info) else: skills = SkillsForm(instance=request.user) return render(request, 'page/userprofile.html', { "skills": skills, }) My template file <ul class="list-group"> <form method="POST" action=""> {% csrf_token %} <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>math</label> {{ skills.math }} </div> </li> <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>language</label> {{ skills.language }} </div> </li> <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>driving</label> {{ skills.driving }} </div> </li> <input class="btn btn-primary" type="submit" …