Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django Channels application to Heroku and setting Redis up
I've built a simple chat application in Django using Channels and Redis. Now I'm trying to deploy it to Heroku and I'm looking for some guidance on how to set up the Channel Layers using Redis. I've already deployed the application and tested it in the browser. I've managed to resolve my errors, and now the application is fully functional except for the messaging because I haven't set up a Redis server yet. I use Daphne as a web server if this provides any valuable information. I'm looking for an overview of all the steps I have to make to set up the Redis server, and how to configure the Channel Layers to work with it. I'd greatly appreciate any help on this, thank you in advance. -
Django has installed my system but not displayed version type
I have use Ubuntu 20.04.5 LTS. when i install django this commend "pip install django" that's installed properly but when i check django version this commend"python -m django --version" there displayed this "/usr/bin/python: No module named django" . django install but i have not run it my system -
ValueError: while trying to use the crispy forms
I am trying to make use of the crispy forms to display the form for inserting the data. I have a model as: class Athlete(models.Model): athlete_name=models.CharField(max_length=50) GENDER_CHOICES=( ('M','Male'), ('F','Female'), ('O','Others') ) gender=models.CharField(choices=GENDER_CHOICES,max_length=100) age=models.IntegerField() athlete_category=models.ForeignKey(Category,on_delete=models.CASCADE) image=models.FileField(upload_to='static/athlete_img', null=True) COUNTRY_CHOICES=( ('np','nepal'), ('in','india'), ('uk','united kingdom'), ('sp','spain'), ('ch','china') ) medals=models.IntegerField country=models.CharField(choices=COUNTRY_CHOICES,max_length=100) def __str__(self): return self.athlete_name In the forms.py...I have modelform as: class AthleteForm(ModelForm): class Meta: model:Athlete fields='__all__' In my views.py I have the following function: def add_athlete(request): if request.method == 'POST': form = AthleteForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Athlete added sucessfully') return redirect('/admin/athletes') else: messages.add_message(request, messages.ERROR, 'Enter the appropriate values') return render(request, 'forgame/addathletes.html', { 'form': form }) context = { 'form': AthleteForm } return render(request, 'forgame/addathletes.html', context) Inside my templates/forgame I have created addathletes.html {% extends 'layouts.html' %} {% load crispy_forms_tags %} {% block title %} <title>Game Category</title> {%endblock%} {% block main_content %} <div class="container-fluid mt-4"> <div class="d-flex justify-content-center"> <div class="col-md-6"> <h2>Add Categories Here!</h2> {% for msg in messages %} {% if msg.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %} <div class="alert alert-success"> {{msg}} </div> {%endif%} {% if msg.level == DEFAULT_MESSAGE_LEVELS.ERROR %} <div class="alert alert-danger"> {{msg}} </div> {%endif%} {%endfor%} <form action="" method="post" class="shadow-lg p-3"> {%csrf_token%} {{form | crispy}} <div class="mt-3"> <input type="submit" value="Add Category" class="btn btn-primary"> </div> … -
Unclosed tag on line 6: 'with'. Looking for one of: endwith
I'm learning how to use Django Templates but im getting this error Unclosed tag on line 6: 'with'. Looking for one of: endwith. this is my html code <!DOCTYPE html> <html> <body> <h1>Favorite rapper:</h1> {% with person="2pac" %} <h1>{{person}}</h1> </body> </html> this is the tutorial that I'm doing -
Animated pictures in JavaScript, problem: flickering screen and resizing
As I mentioned in the title I have a problem properly embedding my animation in my Django project. At some point, I decided to update the logo used by my web page built-in Django. Having small experience with JavaScript I was looking for approaches that fit my needs. I built an animation engine having some inspiration from this StackOverflow answer. (Thanks to user gilly3). My approach is, though, different in this topic because I realised that if I would have a lot of pictures then sticking/concatenating them together in one file might be difficult. I've decided to use another approach and use a bunch of files instead of one. For that sake, I built a function with a generator which I could call in another function to display all pictures in order. This animation engine looks like this: function* indexGenerator() { let index = 1; while (index < 28) { yield index++; } if (index = 28) yield* indexGenerator(); }; var number = indexGenerator(); setInterval(function animationslider() { var file = "<img src=\"../../../static/my_project/logos/media/slides_banner_f/slide_" + number.next().value + ".jpg\" />"; document.getElementById("animation-slider").innerHTML = file; $("#animation-slider").fadeIn(1000); }, 100); $("#animation-slider").fadeIn(1000); doesn't do the trick with values from 10-1000. I record what this looks like: https://youtu.be/RVBtLbBArh0 I … -
Protecting Rest API Routes against expired token using Django Rest Framework and JWT Authentication
I am pretty new to Django Rest Framework and I have created JWT Authentication. I have set the access token expiry time to 4 seconds. After when the token expires, I am still able to access the API route. It is not restricting me, nor it is throwing any error such as 401 unauthorized. Please someone help if you can. This is my SimpleJwt settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=4), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(seconds=4), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=90), } This is my route which I am protecting against expired tokens: @api_view(['GET']) @permission_classes([IsAuthenticated]) def get_notes(request): user = request.user notes = user.notes_set.all() serializer = NoteSerializer(notes,many=True) return Response(serializer.data) -
Can I iterate my context at view to put into my template?
I've created this function at my views to iterate through my pages. for chapter in chapters: context["chapter_page"] = math.ceil((changelogs.index(changelog) + 1) / 2) context["chapter"] = chapters return context I am still making a for a loop in my template, so I cannot remove him. I added this context, but the only returned page is the last page, which means, that my context["chapter_page"] is not iterating. {% for chapter in chapters %} <li> <a href="?page={{ chapter_page }}&#{{ chapter.number }}"> {{ chapter.number }} </a> </li> {% endfor %} Of course, I could not add this logic direct to my template, it is not accepted by Django. {% for chapter in chapters %} <li> <a href="?page={{ math.ceil((chapters.index(chapter) + 1) / 2) }}&#{{ chapter.number }}"> {{ chapter.number }} </a> </li> {% endfor %} I am expecting to do a loop and return each iterated number at my href=page -
Referencing a specified attribute in a model using related field
Assuming you have a Person model with attributes id and username amongst others. class Person(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(unique=True) # other fields In Django Rest Framework there exists the PrimaryKeyRelatedField which represent the target of the relationship using its primary key. When using it in a serializer, it would look something like this class PersonSerializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField( queryset=User.objects.all(), ) username = serializers.CharField(required=True) However I would like a field that would target the username as well. Something similar to class PersonSerializer(serializers.Serializer): username = UsernameRelatedField(queryset=User.objects.all()) One potential solution I have come across is creating a custom relational field but it doesn't seem to work as expected. I would like to check if a username exists for a user. -
In my virtual environment pip is not working
(env) PS C:\Users\ZEWDU\Documents\EthLink> pip Fatal error in launcher: Unable to create process using '"C:\Users\ZEWDU\Documents\env\Scripts\python.exe" "C:\Users\ZEWDU\Documents\EthLink\env\Scripts\pip.exe" ': The system cannot find the file specified. I was working on my django project and when I try to install packages using pip I get the above error. Not tried anything yet? -
Django queryset mysql
in want and equivalent of this sql query in Django SELECT Gender, ServCode FROM [openimisproductTestDb_16_08_22].[dbo].[tblInsuree] JOIN [openimisproductTestDb_16_08_22].[dbo].[tblServices] ON [openimisproductTestDb_16_08_22].[dbo].[tblInsuree].AuditUserID = [openimisproductTestDb_16_08_22].[dbo].[tblServices].AuditUserID WHERE Gender = 'F' AND ServCode = 'F4' data = Service.objects.filter(code = 'F4').count() | Insuree.objects.filter(gender = 'F').count() I tried like that but the one just adds when I want the women included in the insured table and the F4 code contained in the service table. both tables have the auditUserID column in common -
Two forms on same template in django. How to collaborate the template with the views.py?
I have a template with two forms like this and two textareas where the uploaded content will be returned: <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_pdf" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </div> </form> <textarea class="inline-txtarea form-control" cols="70" rows="25"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_excel" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" class="btn btn-warning">Upload!</button> </div> </form> <textarea class="inline-txtarea form-control" cols="65" rows="25"> {{content_excel}}</textarea > and the views.py: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/controle_punt140.html", { "form": form }) def post(self, request): types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) name_of_file = str(request.FILES['upload_file']) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): pass else: content = f.read() return render(request, "main/controle_punt140.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/controle_punt140.html", { "form": submitted_form, }) and forms.py: class ProfileForm(forms.Form): upload_file = forms.FileField() and urls.py: urlpatterns = [ path('', views.starting_page, name='starting_page'), path('controlepunt140', views.ReadingFile.as_view(), name='controlepunt140') ] So this works for the first upload function(pdf). The output is returned to the textarea. But how to have it also work with the second upload function content_excel? I.E: … -
Modify request query string in django decorator
I have a very specific/custom requirement. I have a decorator that is validating request parameters, based on some checks to database I need to add some additional parameters to the request. def validate_request(): """APIkey/uuid or a user session must be present to call api end points Else return a 403""" def decorator(func): def wrapper(request, *args, **kwargs): api_key = request.META.get("HTTP_X_API_KEY") if api_key is not None: //Based on some checks in db, update/add request params return func(request, *args, **kwargs) else: return HttpResponseForbidden('api_key header or user session not found') return wrapper return decorator -
How to insert an item into a Queryset which is sorted by a numeric field and increment the value of the field of all subsequent items
Let´s say, there is a Django model called TaskModel which has a field priority and we want to insert a new element and increment the existing element which has already the priority and increment also the priority of the following elements. priority is just a numeric field without any special flags like unique or primary/foreign key queryset = models.TaskModel.objects.filter().order_by('priority') Can this be done in a smart way with some methods on the Queryset itself? -
How can i resolve django fraudulente site in chrome?
In fact i have a django web app that i host in continous deployment. When i try to open this app in chrome i have a warning red page which notice that the site is fraudulent and in addition i have to enabled the chrome advance protection to be protect of malicious site. In the show more button i can access the site by clicking on open the insecure site. Trying to open the site in edge browser i didn't see any kind of warning and the site open successfully. By this point i think that it's something relative to the security settings of chrome. bellow is the error: *fraudulent website Attackers at xxxxxxxxxxx might trick you into doing something dangerous, like installing software or revealing your personal information (for example, passwords, phone numbers, or credit cards). know more To use Chrome's highest level of security, enable enhanced protection Recently, Google's "Safe Browsing" feature detected phishing from bluecamp.azurewebsites.net. Phishing sites pretend to be other sites to trick you. * You can report a detection issue or, if you understand the risks to your security, access this unsafe site. Then i navigate to the security settings of chrome and disabled the … -
Load all elements of a page at once
I set up a countdown goal when the page loads my countdown is the last to load. How could I make my countdown timer load along with the rest of the page. .html <head> <script type="text/javascript" src="{% static 'js/timer.js' %}" defer></script> </head> <body> <h1> TIMER </h1> <div id="timer"></div> <script type="text/javascript"> let timerQuestion = 1.5; </script> </body> timer.js let temps = timerQuestion * 60 const timerElement = document.getElementById("timer") setInterval(() => { let minutes = parseInt(temps / 60, 10) let secondes = parseInt(temps % 60, 10) minutes = minutes < 10 ? "0" + minutes : minutes secondes = secondes < 10 ? "0" + secondes : secondes timerElement.innerText = `${minutes}:${secondes}` temps = temps <= 0 ? 0 : temps - 1 }, 1000) -
'DateField' object has no attribute 'value_from_datadict'
I've been researching everywhere for an answer for this, but I'm just trying to add a widget to my DateField created on my models.py, where you can see the actual calendar, as if you were doing it directly through html with an input type=date. Since I have a few date fields, this has become a problem because they all need to have the same format as the rest of the form and the widget. Feel like the question has been answered but none of the answers or things I've found have returned a correct answer. models.py class InfoPersonal(models.Model): Fecha = models.DateField() cargo_act = models.CharField(max_length=100) Nombres_y_Apellidos_completos = models.CharField(max_length=100) Lugar = models.CharField(max_length=100) Fecha_de_Nacimiento = models.DateField(null=True) Discapacidad= models.BooleanField() grado = models.CharField(max_length=100, blank=True) Edad = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(80)]) Tipo_de_Sangre = models.CharField(max_length=50, choices=sangre_choice) Estatura = models.FloatField(validators=[MaxValueValidator(3.0), MinValueValidator(0.5)]) Direccion_Domicilio_actual = models.CharField(max_length=100) Manzana = models.CharField(max_length=100) Villa = models.CharField(max_length=100) parroquia = models.CharField(max_length=100) Telefono_Domicilio = models.IntegerField(blank=True, null=True) Telefono_Celular = models.IntegerField(blank=True, null=True) Telefono_Familiar = models.IntegerField(blank=True, null=True) cedula = models.IntegerField() estado_civil = models.CharField(max_length=50, choices=list_estado_civil) #Conyuge Nombre_completo_del_conyuge= models.CharField(max_length=100,blank=True) Direccion_Domiciliaria=models.CharField(max_length=100,blank=True) Telefono=models.IntegerField(blank=True, null=True) Cedula_de_Identidad=models.IntegerField(blank=True, null=True) Fecha_de_NacimientoC=models.DateField(blank=True, null=True) Direccion_Trabajo=models.CharField(max_length=100,blank=True) Telefono_del_trabajo=models.IntegerField(blank=True,null=True) #Hijos Nombres= models.CharField(max_length=100,blank=True) Lugar_y_Fecha_de_NacimientoH = models.CharField(max_length=100,blank=True) Esposo_con_Discapacidad = models.BooleanField(blank=True) Hijos_con_Discapacidad= models.BooleanField(blank=True) #InfoFamiliares Apellidos_y_Nombres_1= models.CharField(max_length=100,blank=True) Telefono_Familiar_1 = models.IntegerField(blank=True,null=True) Fecha_Nacimiento_1 = models.DateField(blank=True,null=True) Relacion_de_Parentesco_1 = models.CharField(max_length=100,blank=True) Apellidos_y_Nombres_2= models.CharField(max_length=100,blank=True) Telefono_Familiar_2 … -
lower() was called on None
I have created a custom function to create custom username in a class Inheriting DefaultSocialAccountAdapter. The code is as follows. def _build_username(self,data): from allauth.utils import generate_unique_username if(not data.get('username')): first_name=data.get('first_name','').lower() last_name=data.get('last_name','').lower() suggested_username = (f"{first_name}{last_name}",) username = generate_unique_username(suggested_username) return username But it throws lower() was called on None I was trying to convert the name to lowercase because that is how our database supports usernames. This happens when i try to perform google login authentication method. -
django MultiValueDictKeyError when trying to retrieve "type"
I have a django page that exports the contents of a list to a csv. The filename is set up to include the organization name, but I want it to also include the type of file as well. As far as I can tell, the values are being pulled from here: <div class="p-1 col-12 fw-bold mb-2"> <label class="text-r mb-1">Select File Type:</label> <select name="type" class="form-select" aria-label="Default select example"> <option value="accounts">Accounts</option> <option value="contacts">Contacts</option> <option value="membership">Membership</option> <option value="cg">Community Group</option> <option value="cgm">Community Group Member</option> <option value="so">Sales Order</option> <option value="item">Item</option> <option value="event">Event</option> <option value="tt">Ticket Type</option> <option value="si">Schedule Item</option> <option value="attendee">Attendee</option> </select> </div> <div class="p-1 col-12 fw-bold mb-2"> <label class="text-r mb-1">Organization Name:</label> <input class="form-control" placeholder="Organization Name" type="text" name="name" required /> </div> The python function that calls it is as follows: class CsvView(View): def post(self, request, *args, **kwargs): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() data = request.POST["raees"] name = request.POST["name"] d_type = request.POST["type"] data = list(data.split(",")) last = data[-1] first = data[0] data[0] = first.replace("[", "") data[-1] = last.replace("]", "") row = 0 col = 0 for i in data: i = i.replace("'", "") worksheet.write(row, col, i) row = row + 1 workbook.close() output.seek(0) filename = f"{name} {d_type} Issue Tracker.xlsx" response = HttpResponse( output, … -
Django querry set sql
please i want to whrite this sql code in a django code to extract data inside SELECT * FROM tblInsuree FULL JOIN tblServices ON tblInsuree.AuditUserID = tblServices.AuditUserID -
linux shell script won't change to directories/sub directories as expected
I trying to build a shell script to setup a Django directory structure. I know the PC/DOS batch language fairly well and I'm trying to accomplish a directory structure setup. I'd like help having my sh script change/create directories and to run commands.. However... I'm getting an error far below when I run the script immediately below... $ sh setup3.sh proj222 app222 mkdir $1 cd $1 python3 -m venv venv$1 source venv$1/bin/activate pip install django && pip install django-oso && pip install django-debug-toolbar && sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib && pip install Django psycopg2 && python3 -m pip install Pillow django-admin startproject config . mkdir apps mkdir templates mkdir tests mkdir utils cd apps ls django-admin startapp $2 ls cd $2 touch urls.py ls # cd .. python3 manage.py migrate python3 manage.py runserver No such file or directory thalacker@HPLaptop17Linux:~/codeplatoon/djangoProjects$ sh setup3.sh proj222 app222 setup3.sh: 28: source: not found Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django in /home/thalacker/.local/lib/python3.10/site-packages (4.1.1) Requirement already satisfied: asgiref<4,>=3.5.2 in /home/thalacker/.local/lib/python3.10/site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /home/thalacker/.local/lib/python3.10/site-packages (from django) (0.4.2) Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django-oso … -
Django rest framework ModelViewSet displying cuttom HTML instead of default
I am new to Django & DRF and I am trying to replace the default api view given from ModelViewSet (scr1,scr2,scr3) with custom HTML templates. Default view works just fine, i've tested with postman and it can do CRUD functions(at least it seems so), but I have no idea how to substitute the default views with custom html pages. I did follow DRF docs - it worked, also searcged solutions(this one was promising), but I simply can't adopt it my situation. Please help! models.py: from django.db import models class Package(models.Model): prod_name = models.CharField(max_length=255, default=0) quantity = models.IntegerField(default=0) unit_price = models.IntegerField(default=0) def __str__(self): return self.prod_name class Orders(models.Model): order_id = models.CharField(max_length=255, default=0) package = models.ManyToManyField(Package) is_cod = models.BooleanField(default=False) def __str__(self): return self.order_id serializers.py: from rest_framework import serializers from .models import Package, Orders class PackageSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField() prod_name = serializers.CharField(max_length=255, default=0) quantity = serializers.IntegerField(default=0) unit_price = serializers.IntegerField(default=0) class Meta: model = Package fields = "__all__" class OrderSerializer(serializers.HyperlinkedModelSerializer): package = PackageSerializer(many=True) def get_or_create_packages(self, packages): print("this is package in gocp:", packages) package_ids = [] i = 0 for package in packages: print("i=", i) i += 1 package_instance, created = Package.objects.get_or_create(pk=package.get('id'), defaults=package) print("package id:", package.get('id')) package_ids.append(package_instance.pk) print("package_ids:", package_ids) return package_ids def create_or_update_packages(self, packages): package_ids = … -
Django - How to style search filter?
I am having issues styling the search filter. I tried using widget and i was only able to adjust the size of the search filter. My search filter still looks very generic and as a beginner, i have trouble understanding how to style it. I know how to style it using css which is shown in the code below This is my filter code: class Product (django_filters.FilterSet): search = CharFilter( field_name="search", lookup_expr="icontains", widget=forms.TextInput(attrs={ 'size': 100, }) ) css for search bar: .search{ float: right; padding: 6px; border: none; margin-top: 8px; margin-right: 16px; font-size: 17px; } -
How to validate the json format of request in django middleware?
I am creating a new middleware in django. In that I am checking the input in request_body. For that I need to check if the request body is json or not. But while raising exception like malformed request or bad request data I am getting 500 server error. How to handle this? def validate_json(request): try: req_data = json.loads(request) except: raise api_exception.BadRequest() json_body = validate_json(request) You can refer to above psuedo code. I want bad rrequest data 400 as response but getting 500 server error. -
How can I post HTML element value to MySQL Database in Django using Ajax (Without using Form)
I am new to Django and currently facing a problem to post html tag data into database. tables.html <div class="containers pt-5 pb-3 px-4 py-4"> <input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' /> <div class="d-none"> <p>User ID: </p><p class="user-id">{{id}}</p> </div> <h3>Case Number:</h3><h2 id="number"></h2> <h4>Description:</h4> <p class="mb-5" id="display"></p> <div class="button d-inline-block" style="max-width: 50%;"> <button type="submit" id="pick" class=" pick-button btn btn-outline-primary border-radius-lg p-3">Pick Case</button> </div> <div class="d-inline-block float-lg-end" style="max-width: 50%;"> <button class="btn btn-outline-danger border-radius-lg p-3">Close</button> </div> </div> <script> $("#pick").click(function(){ var user = $('.user-id').text(); var ca = $('#number').text(); ca = $.trim(ca); $.ajax({ type:"POST", url:"{% url 'dashboard:pick_case' %}", data:{ user_id:user, case_id:ca, csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function(data){ alert(data); } }); }); </script> Views.py def pick_view(request): if request.method == 'POST': case_id = request.POST.get('case_id') print(case_id) status = 2 picked = Transaction() picked.Case_ID = case_id picked.Status = status picked.save() return HttpResponse("Case Picked Successfuly!") else: return HttpResponse("POST ERROR") urls.py urlpatterns = [ path('dashboard', views.dashboard_view, name='dashboard_view'), path('tables', views.case_view, name='case_view'), path('tables', views.pick_view, name='pick_case'), ] models.py class Transaction(models.Model): ### Case Progress Table Case_ID = models.ForeignKey(CaseTable, on_delete=models.CASCADE) Status = models.ForeignKey(Status, on_delete=models.CASCADE) Date_Time = models.DateTimeField(default=timezone.now) I tried the above code and i am able to retrieve the data from the HTML tags but not able to store in the Database. Please Help!! -
change attrs in a CheckboxSelectMultiple widget on every item with django form
I need to build a pre-filled field in a form that have CheckboxSelectMultiple widget. I thought to use different attrs={"checked":""} value on each id of the form filed. Is possible to loop on items? from django import forms from myapp.models import MyModel class MyForm(forms.Form): qs = MyModel.object.value_list("id","value") qsa = MyModel.object.value_list("id", "is_checked") myfield = forms.ModelMultipleChoiceField(queryset=qs, widget=form.CheckboxSelectMultiple) extrafield = forms.CherField(widget=forms.Textarea) def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) for id, is_checked in self.qsa: if is_checked is true: self.fields["myfield"].widget.attrs["checked"] = "" <form action="some_action"> <input type="checkbox" id="1" name="1" value="value_1"> <label for="value_1"> value_1</label><br> <input type="checkbox" id="2" name="2" value="value_2"> <label for="value_2"> value_2</label><br> <input type="checkbox" id="3" name="3" value="value_3"> <label for="value_3" checked="checked"> value_3</label><br><br> <input type="submit" value="Submit" > </form>