Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djanggo sass module not found
im getting this error but a few hours ago this was working just fine, when i run the local server im getting this error enter image description here and when i try to python manage.py makemigrations im getting this error enter image description here i tried pip install django_sass but same thing is happening i read somewhere to try migrations and i did but no, nothing im really confused right now any help will really be appreciated thanks in advance -
Two ManyToMany fields are not working in if statement in template
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to use if statement in template of two many fields BUT if statement is not working correctly. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) friends = models.ManyToManyField("Profile",blank=True) class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_posts',editable=False) template.html {% if request.user.profile.friends.all in post.viewers.all %} "SHOWING SOME TEXT" {% endif %} I am trying to show if request.user friends are in post viewers then show some text. When i print {{ request.user.profile.friends.all }} it show friends of request.user, It works correctly. AND when i print {{ post.viewers.all }} then it correctly shows the post viewers (users). When i try to print some text after combine both in if statement then it doesn't showing anything. I have no idea where is the Mistake. Any help would be Appreciated. Thank You in Advance. -
Ajax call in Django to see if user already exists
I am verifying if a user already exists when he puts his email address in the field on an onblur event. I am also using an external JS file which sends an ajax request to the specified url. However, it is not working. When I start typing in the field, it is telling me email address already exists. Am I doing it the right way? Here is the code: views.py def validate_stud_username(request): if request.is_ajax(): username = request.GET.get('stud_email', None) if User.objects.filter(username__iexact=username): response = { 'is_taken': User.objects.filter(username__iexact=username).exists() } return JsonResponse(response) urls.py urlpatterns = [ path('', views.home, name="home"), path('login/', views.login, name="login"), path('signup/', views.signup, name="signup"), path('validate_stud_username', views.validate_stud_username, name='validate_stud_username'), ] signup.html <form action="{% url 'signup' %}" id="stud_registration_form" method="POST" data-url="{% url 'validate_stud_username' %}"> {% csrf_token %} <input type="email" id="stud_email" style="color: black;" name="stud_email" value="" placeholder=" Email" autocapitalize="none" required> <span style="color: red;" class="error_form" id="stud_email_err"> </span> <button class="btn btn-primary btn-block login_btn" type="submit" style="padding: 2% 0;"> Sign Up </button> </form> form_validations.js $("#stud_email").blur(function () { $.ajax({ data: $(this).serialize(), url: $("form#stud_registration_form").data("url"), success: function (response) { if (response.is_taken == true) { $("#stud_email").addClass("taken"); } else { $("#stud_email").addClass("valid"); } }, error: function (response) { console.log(response.responseJSON.errors); }, }); check_stud_email(); }); function check_stud_email() { var pattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; var email = $("#stud_email").val(); if (pattern.test(email)) { $("#stud_email_err").hide(); $("#stud_email").css("border-bottom", … -
Django makemigrations getting keyerror
migration file 0001 under service class Migration(migrations.Migration): initial = True dependencies = [ ('subscription', '0001_initial'), ] operations = [ migrations.CreateModel( name='Service', fields=[ ('id', models.CharField(default=account.utils.hex_uuid, editable=False, max_length=32, primary_key=True, serialize=False)), ('subscription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='subscription.subscription')), ], migration file 0001 under subscription class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Subscription', fields=[ ('id', models.CharField(default=account.utils.hex_uuid, editable=False, max_length=32, primary_key=True, serialize=False)), ('discount', models.FloatField(blank=True, null=True)), ], ), ] I tried to run makemigrations, but I got the error, old_field = model_state.fields.pop(self.name) KeyError: 'discount' Wondering why I'm getting this error, I did some update on the subscription table before, which dropped the discount field, and already migrated that change in the database. Is it because service 0001 is referencing an old migration file that I'm getting the key error? -
how to tag posts by country efficient way in django
how can i create tag in django to tag post by country but dont create every single post id by country how it is england as tag country 1 post_id content England 2 post_id content England 3 post_id content England i think it will create milions of them in postgresql for every post and cannt find way to tag them like create tags 1 usa 2 russia 3 china 4 england and eg maybe in redis or casandra? i just want to select country and save one tag in post maybe put tag in just post scheme i adk weird but wish u all understand what i am saying thanks -
How to pass a variable from template to views in django?
index.html {% if request.session.visitor_language == 'en' %} {% with current_page=request.resolver_match.url_name %} {{current_page}} {% endwith %} My name is Khan <a style="color: blue;" href="{% url 'change_language' %}?current_page={{current_page}}">BN</a> {% endif %} Here I am trying to send the value of current_page to views through urls urls.py path('home/change_lang/$', views.change_visitor_language, name='change_language'), views.py def change_visitor_language(request,current_page): print(current_page) The Error I am getting from Screen TypeError at /home/change_lang/$ The Error I am getting in command line TypeError: change_visitor_language() missing 1 required positional argument: 'current_page' -
Django - How to check if the user has uploaded an excel file or input text and validate the form
def search_variant(request): context = { 'current_tab': '1' } if request.method == 'POST': form = SearchVariantForm(request.POST, request.FILES) if form.is_valid(): input_file = request.FILES['input_file'] if 'input_file' in request.FILES else None input_file_copy = save_input_file(input_file) context['current_file_name'] = path.basename(input_file.name) #db input hardcoded data db_input_data = [{'Chr': 'HARDCODEDchrX', 'Start': 107844640}] # run interpretation and display the result interpretations = run_intervar(input_file_copy.name, db_input_data) context['search_variant_form'] = SearchVariantForm() context['evidence_formset'] = PathogenicInterpretationFormSet(initial=interpretations) else: # display the search variant form with the errors context['search_variant_form'] = form else: context['search_variant_form'] = SearchVariantForm() return render(request, 'geneticvariants/index.html', context) The specifications of my project have changed, and now apart from an xlsx file, it is also possible that the user through the html form send strings (in a text input, with basically the same content as the xlsx file). The desired logic would be the following (semi pseudo-code): def search_variant(request): gene = request.POST.get('gene') variant = request.POST.get('variant') specimen = request.POST.get('specimen') if gene or variant or specimen: #same logic as per xlsx but with data from db_input_data (hardcoded) if request.method == 'POST': form = SearchVariantForm(request.POST, request.FILES) if form.is_valid(): input_file = request.FILES['input_file'] if 'input_file' in request.FILES else None input_file_copy = save_input_file(input_file) context['current_file_name'] = path.basename(input_file.name) #db input hardcoded data db_input_data = [{'Chr': 'HARDCODEDchrX', 'Start': 107844640}] # run interpretation and display the result … -
Check if user had filled questionnaire before with Django
I'm working on a questionnaire and I made a page where user have a list of which questionnaires to fill and which did he filled before but I have stucked. I like to check if the user filled a form/questionnaire before and if he didn't show him the questionnaire link. My solutions doesn't work because it checks the db just if the user filled the questionnaire but if he did not (no row for him in the db) it shows a blank cell in my table. (I don't know if exists query could be a solution but I can't made it work) main.html {% for i in oke_vezetoi %} {% if i.vezetoi_ok == True %} <td><button class="btn btn-sm btn-outline-info"> <a href="{% url 'stressz:vezetoi_item' %}">Kitöltöm</a></button> <td><i class="fas fa-running fa-2x text-dark"></i></td> {% else %} <td class="text-success text-uppercase">Kitöltötted</button> <td><i class="fas fa-check fa-2x text-success"></i></td> {% endif %} {% endfor %} views.py def main(request): oke_vezetoi = Vezetoi.objects.filter(user_name=request.user) oke_stressz = Stressz_teszt.objects.filter(user_name=request.user) context = { 'oke_vezetoi': oke_vezetoi, 'oke_stressz': oke_stressz, } return render(request, 'stressz/main.html', context) models.py class Vezetoi(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) vezetoi_v01 = models.IntegerField( null=True) vezetoi_v02 = models.IntegerField( null=True) vezetoi_v03 = models.IntegerField( null=True) vezetoi_v04 = models.IntegerField( null=True) vezetoi_v05 = models.IntegerField( null=True) vezetoi_v06 … -
How to save boolean value in to database while pressing html button using django
How to save the boolean value as true to database also route to another page. While we press continue button to save True value to db using django model also route to another page as welcome page. #models.py class Tutorial(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_tutorial = models.BooleanField(verbose_name=_('tutorial'), default=False) #views.py def tutorial_page(request): return render(request, "home/tutorial_page.html") #urls.py from . import views as homeview path('tutorial-page/', homeview.tutorial_page) #tutorialpage.html <article> <h2>demo</h2> <p>press <a href="https://localhost:8000/welcomepage/">continue</a> to skip the tutorial on next time </p> </article> -
Django redirect user upon login failure at /complete/auth0/
I'm using Django with Auth0 for authentication. Sometimes the login fails on Auth0 and redirected to my Django server with /complete/auth0/ with a token indicating error. This reaches my backend at the AUTHENTICATION_BACKENDS class, calling the function auth_complete, which calls process_error. This throws an exception and reaches the http500 page. The question is how should I handle that within these functions? How can I redirect the user to some page (e.g /login_failed.html) to show the client and them decide what to do -
Why can't I enter the admin interface in django after costumizing the user model?
So I have been trying to customize the user model of my django program, my model.py looks like this from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.core.validators import MaxValueValidator, MinValueValidator from django.utils.translation import gettext_lazy as _ from django.utils import timezone # Create your models here. class costumer_base_manager(BaseUserManager): def create_user(self, email, username,firstname, lastname, password, contact, **other_fields): if not email: raise ValueError("Please provide email") email = self.normalize_email(email) user = self.model(email=email, username=username, firstname=firstname, lastname=lastname, password=password,contact=contact, **other_fields) print(password) user.set_password(password) print(password) user.save() return user def create_superuser(self, email, username,firstname, lastname, password, contact, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', False) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must assign is_staff = True') return self.create_user(email, username, firstname, lastname, password, contact, **other_fields) class costumer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email"),unique=True, blank=False) username = models.CharField(max_length=100, unique=True) firstname = models.CharField(max_length=100, blank=False) lastname = models.CharField(max_length=120, blank=False) start_date = models.DateTimeField(default=timezone.now) about = models.TextField(_("about me"), max_length=500, blank=True) investing_style = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(3)]) contact = models.PositiveIntegerField(default=0,validators=[MinValueValidator(9000000001), MaxValueValidator(9999999999)]) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = costumer_base_manager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'firstname', 'lastname', 'contact'] def __str__(self): return self.username and it worked after makemigrations and migrate I am also able to create super user here after createsuperuser As you can see I actually printed … -
How to pass multiple values for query_serializer in swagger?
In the below code I am trying to give two values to query_serializer , but it throws SyntaxError: positional argument follows keyword argument, how to handle it ? class SampleView(APIView,LimitOffsetPagination): permission_classes = (permissions.IsAuthenticated,) @swagger_auto_schema( query_serializer=SampleSerializer,PaginationSerializer, responses={status.HTTP_200_OK: UserCommentsSerializer(many=True), status.HTTP_404_NOT_FOUND:[]}, operation_id="comments", ) -
For loop results line by line printing in template using django view
Hi I am newbie to django and I am trying to print the for loop results in a template using django view but I am not able to print all the lines My view: def upload(request): cells= [(1,2,3,4),(3,3,4,5)] i = 0 for cell in cells: a,b,c.d = cell[0],cell[1],cell[2],cell[3] I=[b+d,a+c] i=i+1 print(I) return render(request,'res.html',{"text":I}) res.html: {% for i in text %} <div class="row"> {{ i }} </div> {% endfor %} when I tried only for loop in python IDE my output is [6, 4] [8, 7] but when I tried in django view I am getting only first row [6, 4] and also not able to print this in res.html Please help me out from this thanks in advance -
Pyinstaller for Microservice architecture to support multiple services to one Executable file
We are developing an application driven by a microservices architecture. Django as ORM to the Mobile Application and the database. We additionally have about 4 more python micro-services communicating through WebSockets. We are trying to make these 4+1 ( 4 microservices and 1 Django application ) into one executable file. We are able to make our Django application an executable file separately but not as an integrated architecture. The other 4 microservice files are all pure python code and they communicate using WebSockets as mentioned already. Additionally, we have a caching system by Redis and a data pipeline system by RabbitMq. Is there a way to integrate them all together to one python executable file using PyInstaller or maybe any other method? Let me know if the question is not clear, I will try to explain better than this. -
django to get the field from one model to another model in serailizer
models.py class Batch(models.Model): created_date = models.CharField(max_length=20, blank=True, editable=False) description = models.CharField(max_length=200) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) def save(self, *args, **kwargs): self.created_date = str(date.today()) super(Batch, self).save(*args, **kwargs) def __str__(self): return self.description class File(models.Model): file_path = models.FileField(upload_to=upload_image) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) def __str__(self): return "%s - %s" % (self.batch.user, self.batch) serailzer.py class BatchSerializer(serializers.ModelSerializer): class Meta: model = Batch fields = "__all__" class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = "__all__" As i need to display the description in api from the Batch models output : "data": { "id": 159, "file_path": https://scanner.net/media/accounts/9/60/pexels-photo-4245826.jpeg, "batch": 60 } The expected output in the views is need to get the description from anothe model based on the batch_id expected output "data": { "id": 159, "file_path": https://scanner.net/media/accounts/9/60/pexels-photo-4245826.jpeg, "batch": 60 "description" : abc {description based on batch_id} } please help me , i'm a newbie to django-rest and API -
Python - How do I get classes that rely on each other to be defined in the same file?
I have the following code used in Django: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): groups = models.ManyToManyField(group) class group(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="course", null=True) name = models.CharField(max_length=50) description = models.CharField(max_length=300) def __str__(self): return self.name I made this code to get a user model in django that allows for more fields. However, the new user class requires the group field since a user can join many groups. This is causing an error since the group is defined after class. What do I do to fix this issue? What I really need is just a way to add extra fields to the default User class so I tried it like so from another SE post. -
Django Todo App - Filter by foreign keys results in TypeError
this is my model: from django.contrib.auth.models import User class Task(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title With the following view and URL pattern I get my the todos: class TaskView(viewsets.ModelViewSet): queryset = Task.objects.all() ## get all todos serializer_class = TaskSerializer router.register("todos", views.TaskView) However, I want the todos for a specific owner. I tried this: class TaskView(viewsets.ModelViewSet): queryset = Task.objects.filter(id=id) serializer_class = TaskSerializer router.register("todos/<int:id>", views.TaskView) This results in the following error: TypeError: Field 'id' expected a number but got <built-in function id>. using get instead of filter resulted in the same problem. Why does this error happen and how can I solve it? -
django models without primary key and id
I use two primary keys. In database, this does not result in duplicate errors unless both values are duplicated. But I don't know how to solve this problem in django model. When the primary key is removed and used, an id column is created. But I do not want this. Using unique_together results in an error because the primary key is duplicated. Is there any way to solve this problem? -
Django , how to show 'secondary property' of parent in TabularInline
I try to do tabular inline admin. In the child tab, if we include a ForeignKey field, it will show the str property of that foreign model. But how to also show another property of that foreign model? Here is my models.py class RawMaterial(models.Model): name = models.CharField(max_length=15) ubuy = models.CharField(max_length=5) usell = models.CharField(max_length=5) uconv = models.DecimalField(max_digits = 5,decimal_places=2) def __str__(self): return self.name class Coctail(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Ingredient(models.Model): coctail = models.ForeignKey(Coctail, related_name='ingredient', on_delete=models.CASCADE) rawmaterial = models.ForeignKey(RawMaterial, related_name='ingredient', on_delete=models.CASCADE) qty = models.DecimalField(max_digits = 5,decimal_places=2) def __str__(self): return self.rawmaterial def rawusell(self): return self.rawmaterial.usell rawusell.short_description = 'UOM' Here is my admin.py from django.contrib import admin # Register your models here. from .models import * admin.site.register(RawMaterial) class IngredientInline(admin.TabularInline): model = Ingredient list_display = ('rawmaterial', 'qty', 'rawusell') class CoctailAdmin(admin.ModelAdmin): inlines = [IngredientInline] admin.site.register(Coctail, CoctailAdmin) and here what I got My question is : How to show rawmaterial.usell in Ingredient tab? Sincerely -bino- -
Can i get specific fields from a model as an instance?
models.py class Medicine(models.Model): reference_no = models.AutoField company_name = models.CharField(max_length=30) medicine_name = models.CharField(max_length=50) mfg_date = models.DateField("Mfg Date (MM/DD/YYYY)*") exp_date = models.DateField("Exp Date (MM/DD/YYYY)*") price = models.FloatField() quantity = models.IntegerField() def __str__(self): return self.medicine_name class Sold(models.Model): company_name = models.CharField(max_length=30) medicine_name = models.CharField(max_length=50) mfg_date = models.DateField("Mfg Date (MM/DD/YYYY)*") exp_date = models.DateField("Exp Date (MM/DD/YYYY)*") price = models.FloatField() customer = models.CharField(max_length=30) phone = models.IntegerField() quantity = models.IntegerField() amount = models.FloatField() purchase_date = models.DateField("Purchase Date (MM/DD/YYYY)*") def __str__(self): return self.customer views.py @login_required(login_url='Login') def sellmedicine(request, id): if request.method == "POST": pi = Medicine.objects.get(pk=id) fm = SellMedicineForm(request.POST, instance=pi) if fm.is_valid(): cmp = fm.cleaned_data['company_name'] med = fm.cleaned_data['medicine_name'] mfg = fm.cleaned_data['mfg_date'] exp = fm.cleaned_data['exp_date'] prc = fm.cleaned_data['price'] cus = fm.cleaned_data['customer'] phn = fm.cleaned_data['phone'] qty = fm.cleaned_data['quantity'] amt = fm.cleaned_data['amount'] pdt = fm.cleaned_data['purchase_date'] reg = Sold(company_name=cmp, medicine_name=med, mfg_date=mfg, exp_date=exp, price=prc, customer=cus, phone=phn, quantity=qty, amount=amt, purchase_date=pdt) reg.save() item = int(qty) pi.quantity -= item pi.save() return redirect('Inventory') else: pi = Medicine.objects.get(pk=id) fm = SellMedicineForm(instance=pi) return render(request, 'store/sellmedicine.html', {"form": fm}) forms.py class AddMedicineForm(forms.ModelForm): class Meta: model = Medicine fields = ["company_name", "medicine_name", "mfg_date", "exp_date", "price", "quantity"] class SellMedicineForm(forms.ModelForm): class Meta: model = Sold fields = ["company_name", "medicine_name", "mfg_date", "exp_date", "price", "customer", "phone", "quantity", "amount", "purchase_date"] i want to have something like in which i … -
Logout function in Django not working as Expected
I have not used any middleware, when i click on logout button on my Home Page template, the logout function execute without any error.but when i go back to main page without jumping to login page.. i see myself as logged in user here is my authentiCation/views.py from django.shortcuts import render from django.http import request,HttpResponseRedirect # for user creation & login form from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login # for user related Queries from django.contrib.auth.models import User # imports for test purpose from django.http import HttpResponse # Create your views here. # register page def register_Page(request): if request.method == 'POST': form= UserCreationForm(request.POST) if form.is_valid(): form.save() username= request.POST['username'] password= request.POST['password1'] user= authenticate(request,username=username,password=password) login(request,user) return HttpResponseRedirect('/') else: return HttpResponse('Either the user name is not available or you may have filled the form incorrectly') else: form = UserCreationForm() context= {'form':form} return render(request,'authentication/register_Page.html',context) # login page def login_page(request): if request.method == 'POST': username= request.POST['username'] password= request.POST['password'] # returns user if credentials are valid user= authenticate(request, username=username, password= password) # check if user var contains the user if user is not None: login(request, user) return HttpResponseRedirect('/') else: return HttpResponse('Invalid credentials') return render(request,'authentication/login.html') # logout Page def log_out(request): logout(request) return HttpResponseRedirect('logout_page') authentiCation/urls.py from … -
Databases are not being saved on my Django app deployed on Heroku
I recently deployed my portfolio using django on heroku. The App is on automatically deploy from github settings. It contains a comment-box that looks like this. You can see for yourself at --> https://anujdhillon.herokuapp.com/ The GET and POST requests are all working perfectly fine i.e when I post a new comment, it does show up in the comment list. However, after a few hours all the new comments that are posted are removed automatically and I cannot figure out why it is happening. the django source code --> https://github.com/anujdhillon/my-portfolio The component is written in ReactJS and the following is the source code for it --> import React from 'react'; class CommentSection extends React.Component{ constructor(props){ super(props); this.state = { commentList:[], activeItem: { id:null, content: '', author: '', }, editing: false, } this.fetchComments = this.fetchComments.bind(this); this.handleContentChange = this.handleContentChange.bind(this); this.handleAuthorChange = this.handleAuthorChange.bind(this); this.postComment = this.postComment.bind(this); this.getCookie = this.getCookie.bind(this) }; getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = … -
Receiver function not answering after Signal.send in Django
I'm trying to create a simple twitter bot that recieves info from different API's and posts the tweets based on the info. I'm using a Django for this (not sure if completely needed, but I'm just trying to learn the framework) so I created 2 different apps, one that recieves the information from the API and creates an object (so far this object is just a quote) and send it to another app which handles the twitter publication. The general idea is that my quote app will generate a signal which will be sent to the posting app where I created a function with a receiver decorator so it will be listening all the time. Nevertheless, for some reason the decorator is not working and after sending the signal I get no response. This is the creation of the signal: from django.dispatch import Signal new_quote = Signal(providing_args=['author', 'content']) This is the sending of the signal: quote=Quote.objects.create(author=author, content=content) new_quote.send_robust(sender=quote, author=author, content=content) The object is being created with no problem, already check that. And this is the catching of the signal. from .models import Post from django.dispatch import receiver from quotes.signals import new_quote from quotes.models import Quote @receiver(new_quote, sender=Quote) def post_tweet(Quote, **kwargs): … -
Show only one like button for all the images of user_1
I am building a Image Gallery WebApp and I am trying to show only one like button for all the images uploaded by specific user. BUT it is showing like button for every image of the user (user_1). BUT i am trying to show only like button. models.py class Galler(modyels.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) likes = models.ManyToManyField(User, related_name='gallery_like', blank=True) views.py def gallery_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) template.html {% for video in gallery %} <div class="card-footer"> <form method="GET" class="likeForm d-inline" action="{% url 'mains:gallery_like_dislike' video.id %}" data-pk="{{ video.id }}"> <span id="id_likes{{video.id}}"> {% if user in video.likes.all %} <p style="color:#065FD4;display: inline">{{video.likes.count}}</p> {% else %} <p style="color:black;display: inline">{{video.likes.count}}</p> {% endif %} </span><button name='submit' type='submit' value="like"><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i>Like</button> </form> {% endfor %} Suppose user_1 posted 6 images then below code is showing six like buttons BUT i am trying to show only one like button for all the images. I have no idea, how can i do it. Any help would be really appreciated. -
"Confirm Form Resubmission " on pressing back in the chrome browser in my django project
This is my first web development project. It is basically an e-voting website. The index page is the login page. So, when the user login using valid credentials, the website will take the user to the voting page where that contains a voting form and some other options like feedback, news updates, etc. in the Navigation bar. The login request is "POST". The vote submission request is also "POST". Here, if the user presses other option like submitting feedback or viewing the candidates, will take the user to that respective pages. And if the user presses the back button, the website should take him to the voting page again where he can again use other facilities voting, viewing candidates, or submit feedback. But the problem I face is if the user presses the back button from the 3rd page i.e., feedback page or viewing candidates page, it shows an error "Confirm Form Resubmission". Help me fix this bug. Thank You in advance. What changes should I make? Since this is my first project, there might be a lot of poor coding techniques. So, please suggest me with better codes where I should replace in my code even though if it …