Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having trouble running django on Pycharm
I'm sure you guys have heard enough of these questions but I am a new programmer looking to start using Django. I have done pip install django and by the time it's almost done download I received a warning. WARNING: The script django-admin.exe is installed in 'C:\Users\bryan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. I have ignored this earlier and ran the command django-admin startproject and of course I receive another error. The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Not quite what to do. I need your help. Or at least direct me to a post similar to this matter. Thank you! I have tried redirecting the PATH with pip install--install-option="--prefix=C:\Users\bryan\PycharmProjects\mySite" django I saw this on another post and thought it would help but nothing really worked. -
Beginner question. Started learning Django without knowing HTML, CSS and Javascript. is it possible? If not why?
Beginner question. Started learning Django without knowing HTML, CSS and Javascript. is it possible? If not why? Beginner question. Started learning Django without knowing HTML, CSS and Javascript. is it possible? If not why? -
How to create a single API which takes data of all Employees
I am new to django. I have a model like this: class Standup(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) standup_time = models.DateTimeField(auto_now_add=True) class StandupUpdate(models.Model): standup = models.ForeignKey("Standup", on_delete=models.CASCADE) employee = models.ForeignKey("Employee", on_delete=models.CASCADE) update_time = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=50) work_done_yesterday = models.TextField() work_to_do = models.TextField() blockers = models.TextField() If I write view for this model, every employee will have to hit API for his/her standup update. But I am supposed create a single API which takes updates of all the employees and saves it into database. In frontend, it will be something like this: Employee will select on a team as one employee can be a part of multiple teams. Then the employee will give his/her stadup updates. Then another employee will do the same thing and so on. At the end,by clicking on submit button, whole data will be saved together. Any guidance on how to do it? -
is there a way to make an infinite loop in django
I want to make a countdown for my website and I can't do it. Please help me I try with a tag "for" but you need the "while" loop which has no tag in django -
overriding validate_unique not raising a ValidationError
I am trying to override the validate_unique for on of my models to validate that a record doesn't exist with duplicate fields (labeler, date), but It's not raising any validation error when i enter duplicate (labeler, date). I've already looked through the issues here and here and constructed my view and model as follows: my view: class AttendanceCreateView(CreateView): model = Attendance template_name = "attendance/attendance_form.html" fields = [ "team_lead", "labeler", "attendance", ] def get_success_url(self): return reverse("attendance-home") my model: class Attendance(models.Model): id= models.AutoField(primary_key=True) attendance = models.IntegerField(blank=True, choices= CHOICES_ATTENDANCE, null=True) labeler = models.ForeignKey('Labelers', models.CASCADE, blank=True, null=True) team_lead = models.ForeignKey('TeamLeads', models.CASCADE, blank=True, null=True) date = models.DateField(auto_now_add=True, null=True) class Meta: managed = False db_table = "attendance" def validate_unique(self, *args, **kwargs): super().validate_unique(*args, **kwargs) if self.__class__.objects.filter(labeler= self.labeler, date= self.date).exists(): raise ValidationError(message='a already record exists for date and labeler',) any idea why my code is not behaving as expected ? thanks is advance. -
Django - stop logout with javascript pop-up confirm box
In my django site I have a logout button that redirects to the view logout. When the button is clicked it instantly logs the user out, but I would like a JS pop-up confirm box to appear then the logout button is clicked. When the user clicks 'Ok' OR 'Cancel' it logs the user out. How can i prevent the logout view being called when the user clicks 'Cancel'? views.py def logout(request): if "user_info" in request.session: del request.session["user_info"] #redirect to login so the user can log back in return redirect("login") script.js function logout_popup() { if (confirm("Are you sure?")) { window.location.reload() } } base.html <li onclick="logout_popup()" id="logout-tab"><a href="{% url 'logout' %}">Logout</a></li> -
Hi, I am using Django rest framework and when I want to encrypt my videos inside sections view I get error can someone help me
I am using Django rest framework and when I want to encrypt my videos inside sections view I get error and I installed cryptography package and I write the code for encrypting and decrypting but when I run the code it gives me error also I add encrypt key inside settings.py here is my code views.py `class ChapterSectionList(generics.ListAPIView): serializer_class=SectionSerializer def get_queryset(self): chapter_id=self.kwargs['chapter_id'] chapter=models.Chapter.objects.get(pk=chapter_id) l=[] for i in chapter_id: i['encrypt_key']=encrypt(i['chapter_id']) i['chapter_id']=i['chapter_id'] l.append(i) return models.Section.objects.filter(chapter=l) ` encryption_util.py `from cryptography.fernet import Fernet import base64 import logging import traceback from django.conf import settings def encrypt(text): try: txt = str(txt) cipher_suite = Fernet(settings.ENCRYPT_KEY) encrypted_text = cipher_suite.encrypt(txt.encode('ascii')) encrypted_text = base64.urlsafe_b64encode(encrypted_text).decode("ascii") return encrypted_text except Exception as e: print(e) logging.getLogger("error_logger").error(traceback.format_exc()) return None def decrypt(txt): try: txt = base64.urlsafe_b64encode(txt) cipher_suite = Fernet(settings.ENCRYPT_KEY) decoded_text = cipher_suite.decrypt(txt).decode("ascii") return decoded_text except Exception as e: logging.getLogger("error_logger").error(traceback.format_exc()) return None` urls.py path('chapter-section-list/<str:chapter_id>/', views.ChapterSectionList.as_view()), I want to get solution to my problem -
how can I get habit count by user in django orm
I would like to get num of habitlog by owner. so, coding api this is my models.py #Models.py class MakingHabit(SoftDeleteModelMixin, TimestampMixin): owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name="making_habits" ) title = models.CharField(_("title"), max_length=255) method = models.CharField(_("method for recording"), max_length=255) class HabitLog(SoftDeleteModelMixin, TimestampMixin): habit = models.ForeignKey( MakingHabit, on_delete=models.CASCADE, related_name="logs" ) date = models.DateField(default=date.today) image = models.FileField(_("evidence image"), null=True, blank=True) this is viewsets.py @action(methods=["GET"], detail=False, url_path="habitrank", url_name="habitrank") def habitrank(self, request, *args, **kwargs): logs = HabitLog.objects.values('habit__owner').annotate(habit_count=Count('date')) for log in logs: print(log) this print enter image description here it's not working what i want. so, I coding different @action(methods=["GET"], detail=False, url_path="habitrank", url_name="habitrank") def habitrank(self, request, *args, **kwargs): logs = HabitLog.objects.values('date').annotate(habit_count=Count('habit__owner')) for log in logs: print(log) it work what i want this print enter image description here why the first query not working? -
Syntax for using {{ article.image }} inside {% static %} with django templates
Trying to display an image on a webpage with django templates {% for article in article_roll %} <li><div class="blog-post" id="blog{{ forloop.counter }}"> {% load static %} <img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}"> <div class="blog-post-preview"> <span class="blog-title">{{ article.image }} {{ article.title }}</span> <span class="blog-date">{{ article.date }}</span> </div> <span class="blog-text">{{ article.preview }}</span> </div></li> {% endfor %} This is the part that's giving me trouble <img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}"> {{ article.image }} is an ImageField in an SQLite Database setup with the default configurations django has. My main concern is loading up the correct image for each article as the for loop progresses, but I can't even get {{ article.image }} to evaluate to anything useful within the {% static %} braces. the static url comes out as <img src="/static/%7B%7B%20article.image%20%7D%7D" alt="image thing"> When what I'm trying to get is <img src="/static/value_of_{{article.image}}" alt="image thing"> I've tried escaping characters, avoiding using ' ', and rewriting the urls. I feel like I might be approaching this problem entirely wrong and there's a better way to do it, but I've been looking through the documentation and haven't seen anything obvious to me. -
Can You store a Django model in an ElasticSearch index?
Can I store a Django model in an ElasticSearch index? If yes, then how can I do that? -
Django how to have the command ./manage.py in Windows
I have saw a lot of posts regarding about how to do ./manage.py for windows and linux but i find the instructions unclear as a beginner. I have tried using "chmod +x manage.py" in my django project directory ("C:\Users\user\Django\Project") in windows command prompt and it does not work as it is not recognised by an internal or external command. So how would you be able to remove the keyword "Python" from "python manage.py" and run it as ./manage.py -
Check if the "tag" from the flash message match inside the template
I am currently attempting to create a global message using tags from Django messages. Globaly: I would like to use the tags from the messages to determine if the message is a warning, success, or something else. for example, my message inside my view)* : messages.success(self.request, f'Success, your account has been deleted', 'success') my template : <p> {% if message.tag == success %}Success {% elif message.tag == welcome %}Welcome {% else %}Warning {% endif%} </p> Alternatively, is it possible to directly display the tag string in my template, without condition ? -
Django postgresql adminer import sql file syntax error
Firstly I exported the database in sql file and without changing anything, I tried to import same sql file to empty postgresql database using adminer. But I get some errors and don't know what is the problem Any ideas? -
Django admin download reportlab PDF
I use this guide(https://docs.djangoproject.com/en/4.1/howto/outputting-pdf/) to download PDF. It works on regular public page. But I am trying to get it working in the admin for a specific model and have model data on the PDF. In my admin I have: cakes/models.py from django.db import models class Cake(models.Model): date = models.DateField("Date ordered") name = models.CharField() def pdf_link(self): from django.utils.html import format_html return format_html("<a href='pdf/%s/'>Download PDF</a>" % self.pk) Dislay the PDF link in the django admin. The link is showing up in admin, it just doesn't link to the PDF yet(pass pdf_link)... cakes/admin.py from django.contrib import admin from .models import Cake @admin.register(Cake) class OrderAdmin(admin.ModelAdmin): list_display = ( 'id', 'customer', 'date', 'pdf_link', ) On my cakes.views.py I have the generate_pdf function from the django docs. How do I connect/link my view function(generate_pdf) with the pdf_link function in my model? I can download the PDF outside the admin. I'm just not sure how to tie it all together in the admin. -
jsONDecodeError. AJAX + Django. Comment system
I'm trying to implement a comment system in Django. The problem is that I can add a comment to the very first post and AJAX will work, that is, the comment will be published without reloading. But if I try to leave a comment on the following posts, I stumble upon an error: jsONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0). In data = json.loads(request.body), there is a post_id and a body, but only if you leave a comment on the first post. To the rest of the request.body is just an empty string models.py from django.utils import timezone from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=30) body = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=timezone.now()) def __str__(self) -> str: return self.title class Comment(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comments') body = models.CharField(max_length=255) post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments', blank=True) created_at = models.DateTimeField(auto_now_add=timezone.now()) def __str__(self) -> str: return self.body views.py from django.utils.formats import date_format from django.shortcuts import get_object_or_404 from django.http import JsonResponse from .models import * from django.shortcuts import render import json def post_detail(request): quotes = Post.objects.all() context = { 'quotes': quotes, } return render(request, 'app_one/post_detail.html', context) def comment_create(request): … -
Collect data from multiple Django signals in session or cache
I have a view in views.py that hits multiple database models. Each model has its own signals registered with it (pre_save, post_save, post_delete, ...etc). Each signal collects the changes in data for each model. Now, I want to collect all those changes to use them somehow at the end of my view. So, I though about saving such data temporarily in the user's session or cache to retrieve them just at the ned of my view, but unfortunately the signal functions doesn't take request parameter with it. So, how can I do such? -
Delete a user from a room Django
In my app, I have created rooms where participants(users) can message. (In models.py) from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self) : return self.name class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(User, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] Now, in the participants section, I have added a user whenever the user sends a message sends a message for the first time in that room. (In views.py) def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all().order_by('-created') participants = room.participants.all() print(participants.all()) if request.method == 'POST': message = Message.objects.create( user=request.user, room=room, body=request.POST.get('body') ) room.participants.add(request.user) return redirect('room', pk=room.id) context = {'room':room, 'room_messages':room_messages, 'participants':participants} return render(request, 'base/room.html', context) Now I want to delete a user from participants when that user deletes all his messages from the room. I am not getting an idea how to proceed here. (In views.py) @login_required(login_url='login') def deleteMessage(request, pk): message … -
docker compose ignores that a service depends on another
Here's the current docker-compose.yml version: '3' services: db: image: postgres environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=my_app ports: - '5432:5432' web: build: . image: my-app ports: - "8000:8000" depends_on: - db command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code environment: - DB_USER=postgres - DB_PASSWORD=postgres - DB_HOST=db - DB_NAME=my_app When I run the app for the first time, this happens: % docker compose build && docker compose up [+] Building 2.5s (10/10) FINISHED => [internal] load build definition from Dockerfile 0.1s => => transferring dockerfile: 189B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 150B 0.0s => [internal] load metadata for docker.io/library/python:3.11.1-bullseye 2.0s => [1/5] FROM docker.io/library/python:3.11.1-bullseye@sha256:cc4910af48 0.0s => [internal] load build context 0.2s => => transferring context: 1.21MB 0.2s => CACHED [2/5] COPY requirements.txt requirements.txt 0.0s => CACHED [3/5] RUN pip install -r requirements.txt 0.0s => CACHED [4/5] COPY . /app 0.0s => CACHED [5/5] WORKDIR /app 0.0s => exporting to image 0.0s => => exporting layers 0.0s => => writing image sha256:d7b4a64b01b9de03dec4a0732eaf975b7bc68f1daefb4 0.0s => => naming to docker.io/library/my-app 0.0s Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them [+] Running 3/3 ⠿ … -
I kindly ask to help me populate my many-to-many relation in Django
I am new in Django and Python at all. I kindly ask to help me with my case. There are three models in my study project among a number of others: models.py class Protein(models.Model): protein_id = models.CharField( max_length=256, null=False, blank=False, db_index=True) taxonomy = models.ForeignKey( Taxonomy, on_delete=models.DO_NOTHING, null=True, blank=True) length = models.IntegerField(null=True, blank=True) access = models.IntegerField(null=False, blank=False, default=0) def __str__(self): return self.protein_id class Pfam(models.Model): domain_id = models.CharField( max_length=256, null=False, blank=False, db_index=True) domain_description = models.CharField( max_length=256, null=True, blank=True) def __str__(self): return self.domain_id class Domain(models.Model): pfam = models.ForeignKey(Pfam, on_delete=models.CASCADE) description = models.CharField(max_length=256, null=True, blank=True) start = models.IntegerField(null=True, blank=True) stop = models.IntegerField(null=True, blank=True) protein = models.ManyToManyField( Protein, related_name='domains', through='ProteinDomainLink') def __str__(self): return self.pfam.domain_id class ProteinDomainLink(models.Model): protein = models.ForeignKey(Protein, on_delete=models.DO_NOTHING) domain = models.ForeignKey(Domain, on_delete=models.DO_NOTHING) Class Domain has ManyToMany field, linked to class Protein through class ProteinDomainLink. There are three csv files to retrieve data from, and my populate script looks like: populate_data.py data_sequences_file = '../..source_file_1'; pfam_descriptions_file = '../..source_file_2'; data_set_file = '../..source_file_3'; pfam = defaultdict(list) domains = defaultdict(list) proteins = defaultdict(list) ... with open(pfam_descriptions_file) as pfam_descriptions_csv_file: pfam_descriptions_csv_reader = csv.reader( pfam_descriptions_csv_file, delimiter=',') for row in pfam_descriptions_csv_reader: pfam[row[0]]=row[1:2] with open(data_set_file) as data_set_csv_file: data_set_csv_reader = csv.reader(data_set_csv_file, delimiter=',') for row in data_set_csv_reader: domains[row[5]] = row[4:5]+row[6:8] proteins[row[0].strip()] = row[1:2]+row[8:9] pfam_rows = … -
Django - ListView - populate table dynamically
I am trying to create a generic table (that I can reuse for other Objects as well) by passing in the views the context "table" As part of view.py I have the following information passed on as Context: object_list = User.objects.all() table.columns that contains the Column Accessor (the property of the User object I want to access) and the Header Name e.g. {'last_name': 'Last Name', 'first_name': 'First Name'} In my template I want to loop through the objects, and find the "Column Accessor" and get the property of the object. So far I have the following, but I am not sure how I can access the property of the object from the template. I can imagine I could create a filter tag, but any help on how to accomplish that would be appreciated. #template.py {% for object in object_list %} {% for column in table.columns %} <td>{{object.????}}</td> {% endfor %} {% endfor %} -
How can I pass the id list in nested serialiazer and get dict output
I pass the list of tag ids in nested serializer during POST. I want to get all the fields of the object in Response, I got only the id. My output: { "id": 87, "tags": [ 1, 2 ]... I need it to be like this: { "id": 0, "tags": [ { "id": 0, "name": "breakfast", "color": "#E26C2D", "slug": "breakfast" } ... How can I do it? My code: class RecipesSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault()) image = Picture2Text(required=False, allow_null=True) ingredients = IngredientsSerializer(many=True, required=False) class Meta: model = Recipes fields = ( 'id', 'tags', 'author', 'ingredients', 'is_favorited', 'is_in_shopping_cart', 'name', 'image', 'text', 'cooking_time', ) def create(self, validated_data): new_recipe = Recipes.objects.create( author=self.context['request'].user, name=validated_data['name'], image=validated_data['image'], text=validated_data['text'], cooking_time=validated_data['cooking_time'], ) new_recipe.save() for ingredient in validated_data['ingredients']: ingredient_obj = Ingredients.objects.get(id=ingredient['id']) RecipeIngredients.objects.create( recipe=new_recipe, ingredients=ingredient_obj, amount=ingredient['amount'] ) amount = ingredient['amount'] ingredient_obj.amount = amount ingredient_obj.save() new_recipe.ingredients.add(ingredient_obj) for tag in validated_data['tags']: tag_obj = Tags.objects.get(id=tag.id) new_recipe.tags.add(tag_obj) new_recipe.save() return new_recipe I tried to explicit the tag serializer but it didn`t work. I did: class RecipesSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault()) image = Picture2Text(required=False, allow_null=True) tags = TagWithinRecipeSerializer(many=True, read_only=True) With: class TagWithinRecipeSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: fields = ('id', 'name', 'color', 'slug') model = Tags But it didn't work: File "/home/aladinsane/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 205, in save … -
django.urls.exceptions.NoReverseMatch: Reverse for 'watchlist' not found. 'watchlist' is not a valid view function or pattern name
I am building a django (v3.2.5) project called commerce which has an app called auctions. urls.py for commerce: from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("", include("auctions.urls")) ] urls.py of auctions: (notice that watchlist path is commented out) from django.urls import path from . import views app_name = 'auctions' urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create, name='create'), path("listing/<int:listing_id>/", views.listing, name='listing'), # path("watchlist/", views.watchlist, name='watchlist') ] views.py: (watchlist function is commented out) @login_required(login_url='/login') def listing(request, listing_id): if request.method == 'GET': listing_data = list(Listing.objects.filter(id = listing_id)) return render(request, "auctions/listing.html", context={"listings":listing_data}) else: pass # @login_required(login_url='/login') # def watchlist(request): # pass index.html: <a href="{% url 'auctions:listing' listing.id %}" class="btn btn-primary">View Listing</a> This is the only tag that points to the listing function/path in views.py. No tag points to the watchlist function/path. This is the error message when I click on the above tag to go to listing.html enter image description here The error points to this particular line of code in views.py: return render(request, "auctions/listing.html", context={"listings":listing_data}) Whenever I remove the context dictionary, that is put only the request and the template in render(),the code runs perfectly fine … -
Fail to integrate scss in my rollup build
What I try to achieve I'm trying to create a little library for private use - basically just splitting up some code into lib (product) and app (project) code. All my source code lives in /src folder which contains React, TypeScript and SCSS code. It would be great, if I can use the SCSS imports directly in React like: import './_button.scss'; I have another SCSS file: src/style/_main.scss it includes some mixins, global styles, resets etc. Config files import commonjs from '@rollup/plugin-commonjs'; import json from '@rollup/plugin-json'; import resolve from '@rollup/plugin-node-resolve'; import terser from '@rollup/plugin-terser'; import typescript from '@rollup/plugin-typescript'; import url from '@rollup/plugin-url'; import dts from 'rollup-plugin-dts'; import scss from 'rollup-plugin-scss'; import { format, parse } from 'path'; import pkg from './package.json' assert { type: 'json' }; const getTypesPath = (jsFile) => { const pathInfo = parse(jsFile); return format({ ...pathInfo, base: '', dir: `${pathInfo.dir}/types`, ext: '.d.ts', }); }; export default [ { input: 'src/index.ts', output: [ { file: pkg.main, format: 'cjs', interop: 'compat', exports: 'named', sourcemap: true, inlineDynamicImports: true, }, { file: pkg.module, format: 'esm', exports: 'named', sourcemap: true, inlineDynamicImports: true, }, ], plugins: [ resolve({ browser: true }), commonjs({ extensions: ['.js', '.jsx', '.ts', '.tsx'] }), typescript({ tsconfig: './tsconfig.build.json' }), url(), scss({ … -
Trying to upload data from python to mysql, but the insertion is not commited
I'm trying to upload some rows of data from python to mysql, using django and mysql, as we also want to show data from the database in our webpage. The connection to the server does work correctly, and so the connection to the database. The problem comes when we execute the following query to insert data from python to mysql. def addInfo(request, T, P, A, Rx, Ry, Rz, Ax, Ay, Az, Fecha, Long, Lat, Vel): """conexion = mysql.connector.connect(user='root', password='admin', host='localhost', database='datos', port='3306') print(conexion) cursor = conexion.cursor() print("T:"+str(T))""" query = "use datos; INSERT INTO datos(Temperatura, Presion, Altitud, RotacionX, RotacionY, RotacionZ, AceleracionX, AceleracionY, AceleracionZ, Fecha, Longitud, Latitud, Velocidad) VALUES ('"+T+"','"+P+"','"+A+"','"+Rx+"','"+Ry+"','"+Rz+"','"+Ax+"','"+Ay+"','"+Az+"','"+Fecha+"','"+Long+"', '"+Lat+"', '"+Vel+"');" print(query) cursor.execute(query) documento = """<!DOCTYPE html> <html> <head> --HTML PART IS OMITTED-- </html>""" print(cursor) cursor.close() return HttpResponse(documento) When we execute this code, database does not update rows, but when we execute manually in mysql, it does work and the id auto-increments as if we had uploaded the previous query. (but the previous row doesn't appear ) -
Is there any way to get the value of multiplecheckboxes that the rendering in for loop with django-template-language
How to get value of mutiplecheckboxes in django. the below code showing the groups at frontend {% for group in groups %} <tr><td>{{group.name}}</td> <td><input type="checkbox" name="superuser" id="group-{{group.id}}" value="{{group.id}}"></td> </tr> {% endfor %} I want to get the values of all checked boxes at backend when I submit the record.