Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django crispy forms "helper object provided to {% crispy %} tag must be a crispy.helper.FormHelper object" when using a Layout Slice
I am getting a helper object provided to {% crispy %} tag must be a crispy.helper.FormHelper object error when trying to access a slice of the form. As shown in forms.py below, I would like to access the first Div using a layout slice (https://django-crispy-forms.readthedocs.io/en/latest/dynamic_layouts.html), so that I can display ONLY that Div within a tab in my HTML. In ref_detail.html below, I have tried to accomplish this with {% crispy form form_helper.0 %}. I've also tried {% crispy form form_helper[0] %} but that doesn't work either. python version 3.8.3 django version 3.1.2 views.py: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy from crispy_forms.utils import render_crispy_form from .models import reference from .forms import ReferenceForm def ref_detail(request, ref_id): try: ref = reference.objects.get(pk=ref_id) except ref.DoesNotExist: raise Http404("Reference does not exist") #If this is a POST request, process the form data if request.method == 'POST': #create a form instance and populate it with data from the request form = ReferenceForm(request.POST) #check whether it's valid if form.is_valid(): #process the data in form.cleaned_data as required (i.e. save to database, etc.) #... print(form.cleaned_data) new_reference = form.save() #save a new reference object to the database, from the form's data #redirect to a … -
failed (13: Permission denied) while connecting to upstream[nginx]
I am working with configuring Django project with Nginx and Gunicorn. I am following this tutorial: https://www.alibabacloud.com/blog/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04_594319 this nginx-error log 2020/11/06 15:09:33 [crit] 13566#13566: *1 connect() to unix:/root/projectdir/automation/nacm.sock failed (13: Permission denied) while connecting to upstream, client: 1xx.1xx.xx.xx, server: xxx.xxx.xxx.xx, request: "GET / HTTP/1.1", upstream: "http://unix:/root/projectdir/automation/nacm.sock:/", host: "xxx.xxx.xxx.xx" and this is my gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/otomasiJaringan/automation ExecStart=/root/otomasiJaringan/env/bin/gunicorn --access-logfile --workers 3 --bind unix:/root/projectdir/automation/nacm.sock nacm.wsgi:application [Install] WantedBy=multi-user.target this site-available/gunicorn server { listen 80; server_name xxx.xxx.xxx.xx; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/projectdir/automation/website; } location / { include proxy_params; proxy_pass http://unix:/root/projectdir/automation/nacm.sock; } In the HTML page I am getting 502 Bad Gateway. What mistake am I doing? -
Django tests - a test in classA fail when i run classB (which is subclass of classA)
I have a test suite with multiple classes - ClassA and ClassB. ClassB is a subclass of classA and when I run classA tests, they all pass. However when i run ClassB, a classA test fails. I'm not sure how or why this is happening. class ClassA(TestCase): def test1(self): # run test def test2(self): # run test class ClassB(ClassA): def test3(self): # run test def test4(self): # run test python manage.py test app.tests.test_views.ClassA all pass python manage.py test app.tests.test_views.ClassB FAIL: test1 (app.tests.test_views.ClassA) Test 1 ---------------------------------------------------------------------- Traceback (most recent call last): File "/path/to/test_views.py", line 1435, in test1 obj.evidence, "This is the evidence entered by user." AssertionError: 'Generic evidence' != 'This is the evidence entered by user.' - Generic evidence + This is the evidence entered by user. This is obviously a simplified example, and I know the best thing would be to not subclass ClassA in ClassB, however in my actual code there are ClassB tests that require some methods of ClassA. I understand this would be better handled with fixtures, but this is how it is set up at the moment and it would be a big revamp to rework this. My understanding is that all ClassA tests are run … -
Making migration in Django
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Am getting this error when making migrations in Postgresql -
How to filter a foreign key field in django?
I'm working on a basic social media project ideally where user gets to join a group and post posts in it. Here's the models i have created: class Group(models.Model): name = models.CharField(max_length=255,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True,default='') description_html = models.TextField(editable=False,default='',blank=True) members = models.ManyToManyField(User,through="GroupMember") class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE) class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete=models.CASCADE) This works fine. Problem is when i create an instance of Post. This design lets me post in any/every group. But what i want is, to let the user post only in group(s) which he's/she's a member of. I don't know how to implement this. Help me out guys. -
Validate geometry field before saving in database
models1.py class Model1(models.Model): geometry = models.GeometryCollectionField(null=True) geojson = JSONField() model_2 = models.ForeignKey('other_app.model2', on_delete=models.CASCADE, blank=True) def save(self, *args, **kwargs): if self.geojson is not None: self.geometry = create_geometry(self.geojson) super().save(*args, **kwargs) models2.py class Model2(models.Model): geometry = models.GeometryCollectionField(null=True) 'geometry' field in Model1 is created from geojson sent by user. I have a custom validation func for geometry field in Model1 in validators.py: from django.core.exceptions import ValidationError def validate_geom(model1_geom, model2_geom): if not model1_geom.within(model2_geom): raise ValidationError("Geom1 is not within geom2") In views.py I have: class Model1Create(ListCreateAPIView): model = Model1 serializer_class = Model1Serializer def perform_create(self, serializer): instance = serializer.save() try: validate_jurisdiction(instance.geometry,instance.model2.geometry) except ValidationError as err: return Response(err.message, status=status.HTTP_400_BAD_REQUEST) But it doesn't work, model1 instance is saved in db. When I delete try-except block error is raised but I keep getting server error (500). I'd like that when validation fails (ValidationError is raised) user recieves 'Geom1 is not within geom2' message with 400 status code. -
Python for in loop only returning initial value
I have added this function to my User model in models.py. For some reason, it is not looping through the whole queryset but instead it seems it is going through one iteration cycle and then breaking out of the loop and I'm not quite sure why? This is the function: def get_following_users_posts(self): following_users = self.following.get(user=self).profile.all() for person in following_users: return person.post_set.all() And this is the output: <QuerySet []> I know that it shouldn't be returning an empty set so I added print statements to help debug: def get_following_users_posts(self): following_users = self.following.get(user=self).profile.all() print(following_users) if following_users: for person in following_users: print(person) return person.post_set.all() The output for this is: <QuerySet [<Profile: Moderator>, <Profile: Animator>, <Profile: Curator>]> Moderator <QuerySet []> How can I get it to iterate through the entire following_users QuerySet? -
Django REST How to Hash Password Correctly
I'm using dj_rest_auth to authenticate my users and there is a problem with registration. After I create a user with RegisterView that dj_rest_auth gives, django creates the user without a problem but password hashing is incorrect and thus I can not login with new created user. This is my Register View: registerview.py class UserRegisterAPIView(RegisterView): def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # user.set_password(make_password(request.data.get('password'))) Didn't work user = self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(self.get_response_data(user), status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): user = serializer.save(self.request) create_token(self.token_model, user, serializer) complete_signup(self.request._request, user, allauth_settings.EMAIL_VERIFICATION, None) return user -
django.db.models.query_utils.InvalidQuery: Raw query must include the primary key
I have given customized name to id(primary key) and used as String eg custId=models.CharField(primary_key=True,max_length=10) I am using raw queries to execute SQL. But Django gives me an error raise InvalidQuery('Raw query must include the primary key') django.db.models.query_utils.InvalidQuery: Raw query must include the primary key. The Query is cust=Customer.objects.raw("""SELECT "custCity" FROM customer where "custId"= 'Cust101' """) for c in cust: print(c) I have searched for this but didn't get the expected answer. Thank you in advance. -
Render ManyToManyField by model filter - Django: 'ManyRelatedManager' object is not iterable
I am try to use the below code to render ManyToManyFields in Django Template but it's giving an error, saying that 'ManyRelatedManager' object is not iterable. template.html {% for tag in order_data.tags %} {{Tags.tag}} {% endfor %} model.py class Order(models.Model): ... slug = models.SlugField(blank=True, unique=True) view.py def order_post_view(request, customer_username, slug): .... order_data = Order.objects.get(slug=slug) required_dict = { ... 'Order': order_data, } return render(request, "themes/order/order_post_details.html",required_dict) -
In Django how do i get a choice field to update when new records are added?
I have the following form: class EditDiary(forms.ModelForm): class Meta: CHOICES = Customers.objects.all().order_by('Name') USERS = User.objects.all() model = Diary fields = ['Customer_ID', 'Staff_ID', 'Date', 'Time1', 'Time2', 'Details'] widgets = { 'Customer_ID': Select(choices=((x.id, x.Name) for x in CHOICES)), 'Staff_ID': Select(choices=((x.id, x.username) for x in USERS)), } Works great and all my customers appear in the list when i call the form Only problem is, if i add a new customer they don't appear in the choice field How do i refresh the Customer_ID choice field? Thank you -
Django transactions doesn't work with raw SQL queries
Because I'm tired of Django DB driver implicit behaviour I've the following code with a plain Postgres transaction: from django.db import transaction, connection from concurrent.futures.thread import ThreadPoolExecutor def commit_or_rollback(commit: bool): query = "COMMIT" if commit else "ROLLBACK" with connection.cursor() as cursor: cursor.execute(query) def insert(query, parameter): with connection.cursor() as cursor: cursor.execute(query, parameter) def insert_with_threads(): insert_pool = ThreadPoolExecutor(max_workers=4) query = 'INSERT INTO a_table VALUES (%s)' parameters = [...] for parameter in parameters: insert_pool.submit(insert, query, parameter) # "Main" program try: with connection.cursor() as cursor: cursor.execute("BEGIN") insert_with_threads() # Could raise any of the caught exceptions except CustomException1: commit_or_rollback(False) except CustomException2: commit_or_rollback(False) except Exception as e: commit_or_rollback(False) # Some general stuff else: commit_or_rollback(True) But nothing is rolled back, I've tried with transaction.atomic(), set_autocommit(), set_autocommit() and raw BEGIN but nothing. Is threading breaking things? Is a problem with opening multiple cursors? Any kind of help would be really appreciated -
How to print a Django List on react js frontend
I have a list as follows: ["test1","test2","test3","test4"] I have the following serializer class: class ListSerializer(serializers.Serializer): key=serializers.ListField() This is views.py file: class ListView(APIView): def get(self, request,*args, **kwargs): serializer_class = ListSerializer #print("The serializer is:",serializer_class) #print(printList()) return Response({"keywords":printList()}) Under the frontend,I have the following method for API: static listFormUser() { const TOKEN = getItem("accessToken"); return axios({ method: "get", url: `${BASE_URL}/api/listtopics/`, headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `Token ${TOKEN}`, }, }).then((res) => res); } } Following is my React class code for displaying the list class printForm extends Component { constructor(props){ super(props); this.state={ items:[], isLoaded:false, key:"", } } componentDidMount(){ this.setState({ isLoding: true }, () => { RestAPI.listForm() .then((response) => { let keywordArray = []; for (let i = 0; i <= response.data.length; i++) { keywordArray.push({ text: response.data[i].key, }); } if (response.data.length === 0) { this.setState({ isData: false, }); } this.setState({ isLoding: false, items: keywordArray, }); }) .catch((error) => { this.setState({ isLoding: false }); handleServerErrors(error, toast.error); }); }); } render(){ return(<ListGroup> <ListGroupItem>Cras justo odio</ListGroupItem> <ListGroupItem>Dapibus ac facilisis in</ListGroupItem> <ListGroupItem>Morbi leo risus</ListGroupItem> <ListGroupItem>Porta ac consectetur ac</ListGroupItem> <ListGroupItem> {items.map(item => { return <li>{items[0]}</li>; })} </ListGroupItem> </ListGroup> ) } The list is not printed.What could be the error here? I have tried many ways but none of … -
How to add styling to the imagefield in django template?
Here i am using bootstrap template but i don't understand how can my form fields work with this template ,Since i have never styled image field before in django , Please tell me how can i upload image by clicking on image icon ? form.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('tag',"title","description","image_data") widgets ={ 'title' : forms.TextInput(attrs={'class':'textinputclass','class':'control-flow'}), 'description':forms.Textarea(attrs={'class':'postcontent'}), } post_form.html <div class="box" > <form method="POST" enctype="multipart/form-data">{% csrf_token %} <textarea class="form-control no-border" rows="3" placeholder="Type something..."></textarea> <div class="box-footer clearfix"> <button class="kafe-btn kafe-btn-mint-small pull-right btn-sm">Upload</button> <ul class="nav nav-pills nav-sm"> <li class="nav-item" ><a class="nav-link" href="#"><i class="fa fa-camera text-muted"></i></a></li> <li class="nav-item"><a class="nav-link" href="#"><i class="fa fa-video text-muted"></i></a></li> </ul> </div> </form> </div> -
"detail": "method \delete\ not allowed" django
I made a view that can use put, delete request using modelviewset and mapped it with url. I have clearly made it possible to request put and delete request to url, but if you send delete request to url, I return 405 error. What's wrong with my code? Here's my code. views.py class UpdateDeletePostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated, IsOwner] queryset = Post.objects.all() def update (self, request, *args, **kwargs) : super().update(request, *args, **kwargs) return Response({'success': '게시물이 수정 되었습니다.'}, status=200) def destroy (self, request, *args, **kwargs) : super().destroy(request, *args, **kwargs) return Response({'success': '게시물이 삭제 되었습니다.'}, status=200) feed\urls.py path('post/<int:pk>', UpdateDeletePostView.as_view({'put': 'update', 'delete': 'destroy'})), server\urls.py path('feed/', include('feed.urls')), and error "detail": "method \delete\ not allowed" -
Hwo to structure css files in django python?
for better overview I created subfolders in the static folder of my django project with css files for each page like this: static --- landing_page -------landing_page.css -------landing_page_mobile.csss If I want to use all the css files I need to import a lot of files in the base.html file like: <link rel="stylesheet" href="{% static '/css/global.css' %}"> <link rel="stylesheet" href="{% static '/css/landing_page/landing_page.css'%}"> <link rel="stylesheet" href="{% static '/css/main_page/main_page.css'%}"> <link rel="stylesheet" href="{% static '/css/landing_page/landing_page_mobile.css'%}"> Is there any other way to keep the css structured without the need of 1000 imports in the base.html ? How are you structuring your projects ? -
gunicorn <HaltServer 'Worker failed to boot.'
I have read the posts with similar tittles and nothing seem to solve my issue. We are running a django app with gunicorn, supervisor and nginx for a few months now without any problems. This morning, out of the nowhere (I repeat out of nowhere!), I get a 502 bad gateway error when trying to access any page of the site. after looking into it, I found that gunicorn was at fault, as shown in this gunicorn.err.log Traceback (most recent call last): File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 209, in run self.sleep() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 357, in sleep ready = select.select([self.PIPE[0]], [], [], 1.0) File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld self.reap_workers() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/exo/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/app/base.py", line 228, in run super().run() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 229, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 342, in halt self.stop() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop time.sleep(0.1) File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld self.reap_workers() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line … -
Django redirection to specific view only in multi user app
I have an app that have different user roles. I want the user to access only the urls specified in his view only and unable to access others. For example: view1.py a.function1 b.function2 view2.py a. functionA b. functionB I want the user who access all the function in view1.py not to access the function in view2.py. when try to access them the system should redirect to its home page. Note that I am using Function Based View. And idea please -
deploying Vue.js and Django api (DRF) using Nginx
I am trying to deploy a Vue app and a Django REST api using Nginx and uwsgi. I am having issues setting up the reverse proxy in Nginx to route all traffic sent to mysite.com/api to the Django app. I am getting 404 error when I try to access the api and I am also unable to access the Django admin site. Here is my docker-compose file and Nginx config. version: "3" services: web: stdin_open: true tty: true build: context: . volumes: - ./app:/app command: bash -c " python manage.py makemigrations && python manage.py migrate && uwsgi --socket :8000 --master --enable-threads --module settings.wsgi" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db restart: on-failure db: image: postgis/postgis environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword restart: on-failure proxy: build: context: ./nginx ports: - "80:80" depends_on: - web volumes: static_data: Here is the Nginx config file: server { listen 80; location / { root /usr/share/nginx/html; try_files $uri /index.html; } location ^~ /api/ { uwsgi_pass web:8000; include /etc/nginx/uwsgi_params; } } -
How to set the url while passing array from jquery to python function?
How can I pass a parameter from jquery to python method? JQUERY const fruits = ['Apple', 'Mango', 'Orange', 'Grapes'] function sendfruitstoPython() { $.ajax({ url: 'Getfruits', type: "POST", data: { Fruit : fruits } , success: callbackFunc }); function callbackFunc(response) { console.log("demo"); } } PYTHON def Getfruits(request): demo = request.GET.getlist('Fruit') print("this is ", demo) OUTPUT this is [] URL PATTERN : path('Getfruits', views.Getfruits, name='Getfruits') It tried this as well... JQUERY function sendfruitstoPython() { $.ajax({ url: 'Getfruits'+ fruits , type: "POST", success: callbackFunc }); PYTHON def def Getfruits(request, fruits : demo = request.POST.getlist('fruits') print("this is ", demo) URL PATTERN path(r'^Getfruits/(?P<Fruit>\w+)/$', views.Getfruits, name='Fruit'), It gives me error he current path, Extractor/Getfruits[object set] , didn't match any of these. -
Unable to install r package inside django docker container
I'm developing a web service by cookie-cutter django For some reason, I have to call R-script to response user requests. So, at first, I tried to add a R's Dockerfile into local.yml. (in the last section) version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: webservice_local_django container_name: django depends_on: - postgres - mailhog volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: webservice_production_postgres container_name: postgres volumes: - local_postgres_data:/var/lib/postgresql/data:Z - local_postgres_data_backups:/backups:z env_file: - ./.envs/.local/.postgres docs: image: webservice_local_docs container_name: docs build: context: . dockerfile: ./compose/local/docs/Dockerfile env_file: - ./.envs/.local/.django volumes: - ./docs:/docs:z - ./config:/app/config:z - ./webservice:/app/webservice:z ports: - "7000:7000" mailhog: image: mailhog/mailhog:v1.0.0 container_name: mailhog ports: - "8025:8025" redis: image: redis:5.0 container_name: redis celeryworker: <<: *django image: webservice_local_celeryworker container_name: celeryworker depends_on: - redis - postgres - mailhog ports: [] command: /start-celeryworker celerybeat: <<: *django image: webservice_local_celerybeat container_name: celerybeat depends_on: - redis - postgres - mailhog ports: [] command: /start-celerybeat flower: <<: *django image: webservice_local_flower container_name: flower ports: - "5555:5555" command: /start-flower R: image: r_local container_name: r_local build: context: . dockerfile: ./compose/local/R/Dockerfile And here is the ./compose/local/R/Dockerfile FROM r-base WORKDIR /app ADD . /app RUN Rscript -e … -
Serve TLS certificate dynamically per Django view instead of via nginx/gunicorn
I'm using Django's request.get_host() in the view code to differentiate between a dynamic number of domains. For example, if a request comes from www.domaina.com, that domain is looked up in a table and content related to it is returned. I'm running certbot programmatically to generate the LetsEncrypt certificate (including acme challenge via Django). I store the cert files as base64 strings in PostgreSQL. That works perfectly fine, but I can't figure out how to 'apply' the certificate on a dynamic per-domain basis. I know that this is normally done using TLS termination, nginx or even in gunicorn. But that's not dynamic enough for my use-case. The same goes for wildcard or SAN certificates (not dynamic enough) So the question is: Given I have valid LetsEncrypt certs, can I use them to secure Django views at runtime? -
How to do location based query with simple Django filter?
I've saved user's coordinates in the User model. Post model has latitude, longitude and radius field. Only the users in that vicinity(of Post) will be able to see that post. I don't know how to use filter() here so I used the following approach: post=Posts.objects.all() for a in post: distance= geopy.distance.geodesic((lat1,lng1), (a.latitude, a.longitude)).km print(distance) if distance < a.radius: p.append(a) else: continue Here, lat1 and lng1 are the coordinates of current User. Suggest if there is any better way as this seems very inefficient. -
Annotate with django: send form with ajax, render div with new item and restart
I want to create a simple annotation web app, where I want the user to see one item, annotate with a simple radio form, submit the form, see the next item, annotate, and so on. I'm using Django but I'm not able to make it work. The problem is that it works with first submission but with the second one gives the error: Forbidden (403) CSRF verification failed. Request aborted. This is what I have for testing: An app called anotar with the following urls.py: app_name = 'anotar' urlpatterns = [ path('',views.dashboard,name = 'dashboard'), ] in views.py: def dashboard(request): template = 'anotar/dashboard.html' tweet_id = '1323646485200850945' if request.is_ajax(): print("AJAX") # I will save the anotation here and pass the another id for new anotation template = 'anotar/tweet.html' tweet_id = '1324423455002005505' html = render_to_string(template,{'tweet_id':tweet_id}) return JsonResponse({'html':html},safe=False) return render(request, template, {'tweet_id':tweet_id}) Then, the dashboard.html: {% extends 'base.html' %} {% load static %} <div id="teste-include"> {% include "anotar/tweet.html" %} </div> {% block domready %} $('#post-form').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check save_anotation(); }); function save_anotation() { console.log("create post is working!") // sanity check console.log($('.form-check-input:checked').val()) $.ajax({ url :'{% url "anotar:dashboard" %}', // the endpoint type : "POST", // http method data : { option … -
Django multiple boolean fields on ForeignKey model in form as checkboxes
I have a Django app that has the following models: class ProductNotification(models.Model): question_asked = models.BooleanField(default=False, help_text='Receive messages when a question is added') question_delete = models.BooleanField(default=False, help_text='Receive messages when question is deleted') # There are more boolean fields in here class Product(models.Model): name = models.CharField(max_length=255, unique=True) #... product_notification = models.ForeignKey(ProductNotification, on_delete=models.CASCADE, default=True) Each Product should have its own notification setting. My forms: class ProductNotificationForm(forms.ModelForm): question_added = forms.BooleanField(help_text='Receive messages when question is added.', required=False) question_delete = forms.BooleanField(help_text='Receive messages when question is deleted.', required=False) # same fields to come as in the model class Meta: model = ProductNotification fields = ['question_added', 'question_delete', ...] class ProductForm(forms.ModelForm): name = forms.CharField(max_length=50, required=True) # ... product_notification = forms.ModelChoiceField(queryset=ProductNotification.objects.all(), required=False) The problem is: The form adds the new "sub form" product notifications, but instead of a bunch if checkboxes for all the boolean fields, there is only one drop-down menu. I have tried ModelMultipleChoiceField too, without success. Can someone help me to get all the checkboxes displayed instead of one drop-down menu? Thanks a lot :)