Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sending email from_email arguments
Why is there from_email argument in send_email django function, when we specify EMAIL_HOST_USER in settings.py module? -
How to get all objects in datetime range of every hour?
I want to get the objects with datetime range of every hour any suggestions? summary_exists = table_name.objects.filter(summary_date__range=(date_from, date_to) -
Django sessions behave differently locally and on Heroku
I am sending data from one HTML template to another using a session. Basically, I have something like request.session['send_input'] = send_input in one template and sent_input = request.session.get('send_input') in the other one. The input I'm sending is send_input = { 'artists': context['chosen_artists'], 'songs': input_songs, 'ids': input_ids, } However, I also want to be able to delete data, so I'm doing if not ('chosen_artists' in context) or reset_button: context['chosen_artists'] = [] context['chosen_ids'] = [] context['chosen_songs'] = [] context['ready'] = False context['pasted'] = False del request.session['send_input'] when a user clicks the reset button. Locally, this works fine. The lists containing chosen_artists etc. become empty. But on the server running on Heroku, the behaviour is different and doesn't make sense. Both 'ready' and 'pasted' truly become False, but the lists are not emptied. The only reason I think this might have is that some variables are cached on the server and not locally. Is it possible that local variables created in views.py are cached somehow? P.S. I'm a Django beginner and doing this for a school project. -
Paddle Payments Cancel Subscription url not working
Fairly new to django and I've implemented subscription payments to my django app using dj-paddle module and by reading this guide. I've tried using the subscription update and cancel url's from the guide but clicking on them nothing happens, the page just refreshes. <a href="{{ subscription.update_url }}" class="btn btn-lg btn-primary"> Update Payment Method </a> <a href="{{ subscription.cancel_url }}" class="btn btn-lg btn-danger"> Cancel Subscription </a> The only way i can cancel a subscription so far is via the admin dashboard. -
django admin keeps raising Validation Error when using separate forms for adding and updating
I have two forms : one for adding and the other for updating class UserAddForm(forms.ModelForm): class Meta: model = User fields = [] email = forms.CharField() first_name = forms.CharField() last_name = forms.CharField() password = forms.CharField(widget=forms.PasswordInput(render_value=False), required=True, label='Mot de passe') is_teacher = forms.TypedChoiceField(coerce=lambda x: x == 'True', choices=((True, 'OUI'), (False, 'NON')), widget=forms.RadioSelect, label='Enseignant ?') class UserChangeForm(forms.ModelForm): class Meta: model = User fields = [] email = forms.CharField() first_name = forms.CharField() last_name = forms.CharField() password = forms.CharField(widget=forms.PasswordInput(render_value=False), required=False, label='Mot de passe') is_teacher = forms.TypedChoiceField(coerce=lambda x: x == 'True', choices=((True, 'OUI'), (False, 'NON')), widget=forms.RadioSelect, label='Enseignant ?') This is the ModelAdmin class UserAdmin(UserUploadAdmin): fields = ['email', 'first_name', 'last_name', 'password', 'is_teacher'] form = UserChangeForm def get_form(self, request, obj=None, **kwargs): if not obj: return UserAddForm return super(UserAdmin, self).get_form(request, obj, **kwargs) The idea is to handle the case of empty password. If it's a new user then the password is required and if I'm updating then it will be empty and therefore ignored. The problem is that the add form keeps raising validation errors, even when the fields are not empty The update form however works fine without any problems. -
Pytest does not see files in folders in Django
I have a following question: I have a test function written in Pytest for Django project: @pytest.mark.django_db def test_class(): path = Path(r'ascertain\tests\csv') handler = DatabaseCSVUpload(path, delimiter=',') handler() ascertain\tests\test_upload_csv.py:19 (TestUploadCSVtoDatabaseNegative.test_class) Traceback (most recent call last): File "C:\Users\hardcase1\PycharmProjects\telephone_numbers\ascertain\tests\test_upload_csv.py", line 27, in test_class handler() File "C:\Users\hardcase1\PycharmProjects\telephone_numbers\ascertain\handle_csv.py", line 129, in __call__ for file in self.get_csv_files(): File "C:\Users\hardcase1\PycharmProjects\telephone_numbers\ascertain\handle_csv.py", line 48, in get_csv_files raise EmptyFolder() telephone_numbers.custom_exceptions.EmptyFolder: It basically expects *.csv files be inside directory ‘path’ and handle them to upload to DB. Problem is that Pytest can’t see any files in this directory as well as in other directories. I have tried multiple times with different folders. In fact file is there: list(Path(r'ascertain\tests\csv').glob('*.csv')) [WindowsPath('ascertain/tests/csv/test.csv')] Same test function written in unitests works correctly: from rest_framework.test import APITestCase class TestCase(APITestCase): def test_open(self): path = Path(r'ascertain\tests\csv') handler = DatabaseCSVUpload(path, delimiter=',') handler() System check identified no issues (0 silenced). Destroying test database for alias 'default'... Process finished with exit code 0 Question is -what I need to do to make Pytest see this file? Thank you! -
Union of two querysets results in Programming error if one of them is empty
To save some db hits I'm trying to use django union to merge two querysets into one, like this: qs1 = Model1(...) # complicated stuff going on here qs2 = Model2(...) # complicated stuff going on here qs1.union(qs2) Of course I'm making sure the fields in both querysets are the same. When querysets are not empty, my code works properly - I'm receiving a single, merged queryset with all the fields I need. The problem only appears when either of the querysets happens to be empty. When that happens I receive: def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: > return self.cursor.execute(sql, params) E django.db.utils.ProgrammingError: each UNION query must have the same number of columns E LINE 1: ...app_model1"."id" IS NULL)) UNION (SELECT "app_model1... E ^ /usr/local/lib/python3.7/site-packages/django/db/backends/utils.py:84: ProgrammingError I feel like the columns should stay in the queryset even if there are no records. Is there any way to achieve that? -
Adding comments with Ajax and Django
I am trying to ajaxify my comment form so that it can be submitted without refreshing the page. I have a Comment model which has a ForeignKey to the Post model: class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=500) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Post(models.Model): content = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='posts') Here is my template: {% for post in posts %} ... <div id="comList""> {% if post.comment_set.all %} {% for c in post.comment_set.all %} <p>{{ c.body }}</p> {% endfor %} {% endif %} </div> <form id="addComForm" action="{% url 'posts:comment' %}" method="post"> {% csrf_token %} <input type="hidden" name="post_id" value={{ post.id }}> {{ c_form }} <button id="addComBtn" type="submit" name="submit_c_form">Send</button> </form> {% endfor %} <script> $(document).ready(function() { $('#addComBtn').click(function() { var serializedData = $('#addComForm').serialize(); const url = $('#addComForm').attr('action') $.ajax({ url: url, data: serializedData, type: 'POST', success: function(response) { $('#comList').append('<p>' + response.c.body + '</p>') }, error: function(error) { console.log(error) } }) }); }); </script> Here is my view: def comment_view(request): profile = Profile.objects.get(user=request.user) if 'submit_c_form' in request.POST: c_form = CommentModelForm(request.POST) if c_form.is_valid(): instance = c_form.save(commit=False) instance.user = profile instance.post = Post.objects.get(id=request.POST.get('post_id')) instance.save() return JsonResponse({'comment': model_to_dict(instance)}, status=200) return redirect('posts:index') And for … -
I need help from a Python Django EXPERT
I created a post that allows me to upload multiple image and the post contain title, description and image but im trying to be display in this template , but on every post are being displayed all photos not only the photos that have been upload for that post here is my template code {% for post in posts %} <section class="container" style="margin-top: -0.8rem;"> <div class="carousel-inner"> <div style="background-color: #000000" class="card text-center"> <div class="card-body"> <h1 class="card-title" style="color: #FFFFFF; letter-spacing: 6px; font-size: 20px; margin-bottom: -0.7rem;">{{ post.title }}</h1> </div> </div> <div id="{{ post.id }}" class="carousel slide" data-interval="false" data-ride="carousel"> <ol class="carousel-indicators"> {% for p in photos %} <li data-target="#carouselExampleIndicators" data-slide-to="{{forloop.counter0}}" class="{% if forloop.counter0 == 0 %} active {% endif %}"></li> {% endfor %} </ol> <div class="carousel-inner" role="listbox"> {% for p in photos %} <div class="carousel-item {% if forloop.counter0 == 0 %} active {% endif %}" style="background-color: #000000"> <img class="d-block w-100" src="{{ p.image.url }}" alt="First slide"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#{{ post.id }}" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#{{ post.id }}" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div style="background-color: #000000" class="card text-center"> <div class="card-body"> <p class="container" style="color: #FFFFFF; font-size: 10px; letter-spacing: 2px; text-align: justify; … -
AttributeError at /customer/api/register/ 'NoneType' object has no attribute '_meta'
I am creating register api in DRF and facing the following problem and I tried a lot to find the solution but could not be able to find the answer. please help me so that I can solve my solution. please help me. this is my model models.py: from django.db import models from django.utils import timezone from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractUser ,PermissionsMixin # Create your models here. class CustomUser(BaseUserManager): def _create_user(self, email, password, **extra_fields): """ It will create a custom user with email and password and save it. """ if not email: raise ValueError(_('Please Register yourself with a valid E-mail.')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_active', True) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) user = self._create_user(email, password, **extra_fields) return user class Customer(AbstractUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=50) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone_number = models.IntegerField(null=True, blank=True) city = models.CharField(max_length=50, blank=True, null=True) shipping_address = models.CharField(max_length=100, blank=True, null=True) billing_address = models.CharField(max_length=100, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff … -
database options in django settings file are not working
I was setting AWS EC2 instance on our company's new AWS account. and I've been faced some issue with database connection. below is occurred warning message on terminal. (django_mysql.W003) The character set is not utf8mb4 for database connection 'default' HINT: The default 'utf8' character set does not include support for all Unicode characters. It's strongly recommended you move to use 'utf8mb4'. See: https://django-mysql.readthedocs.io/en/latest/checks.html#django-mysql-w003-utf8mb4 so I checked database options in the settings file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': DB_HOST, 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4', 'use_unicode': True, }, 'CONN_MAX_AGE': 30, } } I thought It would be fine but terminal shows me same warning message. and then database is also set to utf8mb4 enter image description here how can I resolve this issue? thanks for reading :) -
Problems caused by django quick access interface
1.linux django use : gunicorn --timeout 100 --keep-alive 100 -w 2 -b ...:8001 bigfish.apps.bigfish.wsgi & get 2 process 2.then i click 200/s api: def create(self,request,*args,**kwargs): if User.objects.exists(): User.objects.create() return Response() 3.sometimes create 2 times User object,how to limit 1? -
How pass the variable from template to view?
template.html <input type="text" id="text"> <input id="submit" name="submit" type="submit"> <div id="roro"></div> <script type="text/javascript"> $('#submit').click(function(){ $.ajax({ url:'', data : {'text':$('#submit').val()}, type: 'POST', dataType : 'json', success:function(data){ $('#roro').text(result['data']); }, error:function(r){ alert(text); } }); }); </script> view.py @csrf_exempt def construction(request): if request.method == 'POST': text = request.POST['text'] return render(request, 'pybo/construction_compare.html', text) return render(request, 'pybo/construction_compare.html') It's a test for pass of variables. So if it's failed I want see variable on alert.. I found many of articles but I failed.. And It has many fault because I studying alone and My brain is not good :( -
After Pull project from Github getting below error comes after runserver command in django
I pull project from GitHub and getting below error during runserver command. other project are working fine. -$ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): > File > "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\threading.py", > line 950, in _bootstrap_inner > self.run() File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'NEWDOOR.apps' Traceback (most recent call last): File "E:\Python_Tutorial\NewDoor\manage.py", line 22, in <module> main() File "E:\Python_Tutorial\NewDoor\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Faraz\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in … -
Old password field is not shown in th browsable api django rest auth
I'm using Django rest framework with django rest auth. When I access rest-auth/password/change it prompts me to enter new password 1 and new password 2. But in the serializer there's a field for old password also. But I can't see it in the browsable api window. What is the resaon for that -
Django: Serializer raises exception in migration if model does not exist yet
I have this issue with django-rest-framework serializer where I have a choicefield that gets a list from a model/table. But when migrating the project for the first time it raises an exception. I've managed it for now using a try/except method but was wondering if there is maybe a better solution considering I would like to use more choicefields using data from a model query. Bellow is what I currently have: class FooSerializer(Serializer): try: bar = serializers.ChoiceField([foo.name for foo in Bar.objects.filter(active=True)], required=True) except Exception as error: handle_error(error) bar = serializers.ChoiceField([]) surely this can't be the best solution for handling an issue like this? -
save json as array in postgres db in django
i got problem that i can't handle. i have a JSON file that include some hotel data such rooms, name, city and so on. some of this fields include more than one data and separate with " | " like this one : "image_urls": "//imghtlak.mmtcdn.com/images/hotels/201512081111224987/exterior.jpg|//imghtlak.mmtcdn.com/images/hotels/201512081111224987/room.jpg|//imghtlak.mmtcdn.com/images/hotels/201512081111224987/download.jpg", or like this one: "highlight_value": "1 lift|24 hour business centre|24 hour coffee shop|24 hour reception|24 hour room service|24 hour security|24 hours front desk|24-hour business center|24-Hour Front Desk|24-hr Coffee Shop|24/7 Power|Activities desk|Activity centre|Airport Transfer Available With Charges Rs.200/- Per Trip|Arrangements Of Kitty Parties & Birthday Party|Auditorium|Ballroom|Banqueting|Bar|Board Room|Boardroom|Breakfast buffet|Children's Playground|Doctor on Call|Dry Cleaning|Dry Cleaning Service|Dry cleaning/laundry service|Free garage parking|Free Parking|Free Wi-Fi|Free Wi-Fi Icon|Handicap Facilities|Hot tub|In-room safe (some rooms)|Laundry Service|Newspaper|Non-smoking rooms|Room Service|Room service (24 hours)|Room Service (24 Hours)(after 11:00pm.round The Clock Menu)|Room Service 24 Hrs|Room Service 6 Am - 12 Night|Room Service 7 Am To 9 Pm|Room Service 7am-11:30pm|Room Service, 24 Hour Reception|Room Service, 24 Hour Reception And Laundry Service|Room Services 7 Am To 9 Pm|Wake up call|Wheelchair access" and i want to separate them to save in postgres db as array and i have django project that my frontend colleague told me it should be array that he can use them and show them and i'm new … -
django polymorphic update formset queryset 'owner_ptr' problem
problems: CopyrightApplication instance owners update formset queryset passing problem I want to update all owners belongs to CopyrightAplication instance FieldError at /accounts/copyright/secondpart/2020111101/update/ Cannot resolve keyword 'owner_ptr' into field. Choices are: address, applications, constitution, created_at, designation, email, id, institute, institute_address, institute_email, institute_mobile, institute_name_in_bangla, institute_name_in_english, is_active, memorandum, mobile, name_in_bangla, name_in_english, nationality, nid, nid_number, owner_proportion, passport_number, person, photo, polymorphic_ctype, polymorphic_ctype_id, social_security_number, tin_certificate, trade_licence, updated_at models.py class Owner(PolymorphicModel): """ Copyright application Owner model """ # person type owner attributes name_in_english = models.CharField( help_text='Name in English', max_length=100, null=True, blank=True ) name_in_bangla = models.CharField( help_text='Name in Bangla', max_length=100, null=True, blank=True ) designation = models.CharField( help_text='Designation', max_length=100, null=True, blank=True ) mobile = models.CharField( help_text='Mobile Number', max_length=16, null=True, blank=True ) email = models.EmailField( help_text='Email Address', max_length=100, null=True, blank=True ) nationality = models.CharField(max_length=100, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Person(Owner): """ Person Type Copyright Owner """ pass def __str__(self): return str(self.name_in_english) class Institute(Owner): """ Person Type Copyright Owner ForeginKey/ManyToOne Relation with Owner Model """ pass def __str__(self): return str(self.institute_name_in_english) class CopyrightApplication(models.Model): """ Copyright Application main model """ owner = models.ManyToManyField( Owner, blank=True, help_text='Please Select or Create', related_name='applications' ) views.py class CopyrightStepTwoCreateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): ''' Copyright part create or update ''' template_name = 'accounts/copyright_parttwo_create_update.html' … -
how can i get the my real geo-position in leaflet
Am new to geodjango and am using leaflet to display map on template when i locate my position on map it shows me some meters from the point but i need the real position any help please // placeholders for the L.marker and L.circle representing user's current position and accuracy var current_position, current_accuracy; function onLocationFound(e) { // if position defined, then remove the existing position marker and accuracy circle from the map if (current_position) { map.removeLayer(current_position); map.removeLayer(current_accuracy); } var radius = e.accuracy / 2; current_position = L.marker(e.latlng).addTo(map) .bindPopup("You are within " + radius + " meters from this point, Lt: "+e.latlng).openPopup(); current_accuracy = L.circle(e.latlng, radius).addTo(map); } function onLocationError(e) { alert(e.message); } map.on('locationfound', onLocationFound); map.on('locationerror', onLocationError); // wrap map.locate in a function function locate() { map.locate({setView: true, maxZoom: 16}); } // call locate every 3 seconds... forever setInterval(locate, 3000); -
How to get user message before disconnecting websocket. django channel
How i can get last user message before disconnecting. I want to create a tracking system with real time and for this using Django channels library for websockets and I need to save the last user location before disconnecting but in function disconnect I can't get user messages. How i can solve this problem maybe creating objects in receive function and call it on disconnect function? -
Heroku collect static manual
Is there a way that I can run collectstatic manually in my terminal and disable heroku from doing it automatically? I want to run python3 manage.py collectstatic However, on Heroku, it defaults to python manage.py collectstatic If I disable collectstatic on heroku, can someone give me steps to do it manually please. -
Enable PATCH requests to HyperlinkedModelSerializer
I've a HyperlinkedModelSerializer defined as follows: class FooSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Foo fields = '__all__' When I try to send a PATCH request, I get the following response, {"detail":"Method \"PATCH\" not allowed."} How do I enable PATCH request to this serializer? Or does the update method get triggered by some other http call? -
How to write postgre query in django?
I am trying to fetch user id who has multiple skill. below is the postgre query which is giving me correct result, I m stuck while implementing the same in Django. SELECT "Extractor_usr_skills"."user_id" FROM "Extractor_usr_skills" WHERE "Extractor_usr_skills"."skill_id" IN (356, 360) GROUP BY "Extractor_usr_skills"."user_id" HAVING COUNT("Extractor_usr_skills"."user_id") = 2 I am able to do this by following (Django queryset - column IN() GROUP BY HAVING COUNT DISTINCT ). Do we have any better solutions? -
DoesNotExist at /folder/ Userdata matching query does not exist. DJango Problem
When i use my super acc, this error does not shows up, but when I tried to use other acc. this error shows up. where did I do wrong? The error : DoesNotExist at /voting/ Userdata matching query does not exist. My Model : class Userdata(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) faculty = models.ForeignKey(Fakultas, on_delete=models.CASCADE, default=1) is_voted = models.BooleanField(default=False) def __str__(self): return self.user.username My views : @login_required def voted(response): user = Userdata.objects.get(id=response.user.id) # get the username if user.is_voted: return render(response, 'Main/voting.html', {'calon': Voting.objects.order_by('id'), 'hasil': 'You Have Voted'}) if response.method == 'POST': id = response.POST['idcalon'] calon2 = Voting.objects.get(id=id) # get user selection in html user.is_voted = True calon2.voters += 1 user.save() calon2.save() return render(response, 'Main/voting.html', {'calon': Voting.objects.order_by('id')}) # balik ke sendiri -
increasing and decreasing button not working
I am trying to build a cart using django and javascript for that I added two button to increase and decrease cart items, but its not working.I am not suitable with javascript for that I followed a tutorial.I did the same but still its not working. Here is my cart.html: {% load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static 'css/cart.css' %}" type="text/css" /> <link href="https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap" rel="stylesheet" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>GnG</title> <script type="text/javascript"> var user = "{{user.username}}"; function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent( cookie.substring(name.length + 1) ); break; } } } return cookieValue; } const csrftoken = getToken("csrftoken"); </script> <script src="{% static 'js/cart.js' %}"></script> </head> <body> <!--cart start--> <div class="table"> <div class="layout-inline row th"> <div class="col col-pro">Product</div> <div class="col col-price align-center">Price</div> <div class="col col-qty align-center">QTY</div> <div class="col">DELIVERY CHARGE</div> <div class="col">Total</div> </div> {% for item in items %} <div …