Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I send all form data from one view to another with sessions in Django
So I already know how to send and receive one value from InputWebView to DisplayWebView but I need to send all values from my form and receive it on the other side to process further. How do I do that? <form method="POST" action=""> {% csrf_token %} {{ form.non_field_errors }} {{ form.web_input }} <input type="submit"> </form/> def InputWebView(requests): form = WebInputForm(request.POST or None) if request.method == 'POST': if form.is_valid(): request.session['web_input'] = request.POST['web_input'] return redirect('add_web') def DisplayWebView(request): var = request.session.get('web_input') -
ValueError at /cart/ Cannot assign "'admin'": "CartItem.user" must be a "User" instance
I get ValueError when i try and save an object, The error is related to User being assigned to a model. When i use without string method (only user=request.user) it says TypeError at /cart/ str returned non-string (type User) when i apply string method (user=str(request.user)) it gives me ValueError at /cart/ Cannot assign "'admin'": "CartItem.user" must be a "User" instance. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem from django.contrib.auth.decorators import login_required from .forms import BookForm # Create your views here. def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html', {'error':'You are already logged in'}) elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signinuser.html', {'form':AuthenticationForm()}) elif request.method == "POST": user = authenticate(request, username=request.POST['username'], password=request.POST['password']) … -
Unable to login as a vendor in django rest framework
I have three types of users in CustomUser model each provided with an integer value. Also, I have made a separate view for login for vendor. I registered a user as vendor from default django admin. But I am unable to login as a vendor when I call the login as vendor api. I get the error message saying this is not a seller account. My models: class CustomUser(AbstractUser): username = None first_name = models.CharField(max_length=255, verbose_name="First name") last_name = models.CharField(max_length=255, verbose_name="Last name") email = models.EmailField(unique=True) Type_Choices = ( (1, 'Customer'), (2, 'Vendor'), (3, 'Admin'), ) user_type = models.IntegerField(choices=Type_Choices, default=1) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() def __str__(self): return self.email My serializers: class CustomLoginSerializer(LoginSerializer): username = None email = serializers.EmailField(required=True) password = serializers.CharField(style={"input_type": "password"},) user_type = serializers.IntegerField() My views: class VendorLoginUserView(LoginView): permission_classes = [AllowAny] serializer_class = CustomLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = CustomLoginSerializer(data=data) data['user_type'] = request.user.user_type user_type = data['user_type'] if user_type is 2: serializer.is_valid(raise_exception=True) new_data = serializer.data user = serializer.validated_data["user"] serializer = self.get_serializer(user) token, created = Token.objects.get_or_create(user=user) # return response.Response(new_data, status=status.HTTP_200_OK) return response.Response({"token": token.key, "serializer.data": serializer.data}, status=status.HTTP_200_OK) else: message = "This is not a seller account" return Response({'message':message,}, status=status.HTTP_400_BAD_REQUEST) My urls: path("api/vendorlogin/",views.VendorLoginUserView.as_view(), … -
How to translate the name of days of the week and months in Django calendar
I would like to ask how can I change the name of the days of the week and month from the original English to e.g. Polish in the calendar rendered in Django I tried to find a solution in changing the language in the settings but nothing works I also tried to use LocalHTMLCalendar but it didn't work this is my utlis.py file class Calendar(LocaleHTMLCalendar): def __init__(self, year=None, month=None): self.year = year translation.activate('pl') self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) print() return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal and this is my views.py … -
Correct way to read data for a graph
What i want to do is to show some data in a graph. the data is from a pandas data frame that i generated in my main.py file when crunching some numbers. Now i want to show this in a chartsJS graph in another html. Is the correct way to leave my data frame that i generated in my main.py file and generate the graph by looking at the main.py file an reading the data frame. or is the correct way to generate a django model and have the graph read the data from a django model? The data frame will change everyday, hence the graph will be changing daily. If the latter is correct could someone show me how they would make the model if the data frame is just some text with numbers print(df["my_data"]) pass: 20 fail: 50 n/a: 8 -
How to write a bitbucket-pipelines.yml for react and django application to deploy on heroku
On the bitbucket, my all build scripts are running perfectly but when I am deploying the app on heroku then I am getting this build error: -----> Building on the Heroku-20 stack -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/nodejs.tgz ! ERROR: Application not supported by 'heroku/nodejs' buildpack ! ! The 'heroku/nodejs' buildpack is set on this application, but was ! unable to detect a Node.js codebase. ! ! A Node.js app on Heroku requires a 'package.json' at the root of ! the directory structure. ! ! If you are trying to deploy a Node.js application, ensure that this ! file is present at the top level directory. This directory has the ! following files: ! ! backend/ ! myapp/ ! db.sqlite3 ! manage.py ! media/ ! ! If you are trying to deploy an application written in another ! language, you need to change the list of buildpacks set on your ! Heroku app using the 'heroku buildpacks' command. ! ! For more information, refer to the following documentation: ! https://devcenter.heroku.com/articles/buildpacks ! https://devcenter.heroku.com/articles/nodejs-support#activation More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed My project file format is this : /backend /backend /myapp /media -manage.py -db.sqlite3 -runtime.txt -requirements.txt /frontend /src /node_modules -index.html -package.json -package-lock.json … -
Is it possible to get the coverage for the functions and classes for the unit tests for a Django Project?
I am working on a Django project and I would like to know if it is possible to get the coverage for the functions and the classes ? I tried to do that : But I cannot achieve to get the coverage for functions and classes like I can do it using php unit : Could you help me please ? Thank you very much ! -
Django Rest Framework - How to get the json response in a way, so that it is easier to access in frontend?
Hey guys I have this serializer to get the list of pending users, class UserInfo(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'username',] class PendingRequestSerializer(serializers.ModelSerializer): other_user = UserInfo(read_only=True) class Meta: model = PendingRequest fields = ['other_user', ] views.py class PendingRequestListApiView(APIView): permission_classes = (IsAuthenticated,) def get(self, *args, **kwargs): user = PendingRequest.objects.filter(user=self.request.user) serializer = PendingRequestSerializer(user, many=True) return Response(serializer.data, status=status.HTTP_200_OK) I am getting the json response like this. [ { "other_user": { "id": 8, "username": "testuser5" } }, { "other_user": { "id": 4, "username": "testuser2" } } ] I want the json response to look like this instead. "results": [ { "id": 4, "username": "testuser2", }, { "id": 8, "username": "testuser5", } ] That is instead of having the user information in separate other_user, is it possible to combine it like it is in the second response? Thanks -
Why select_related in Django ORM apply join before where clause?
Consider I have two tables namely Class Department(model.Models): id = models.AutoField(primary_key=True) Class Employee(model.Models): dep = models.ForeignKey(Department) exp = models.IntegerField() Now in views class I am using get_queryset function def get_queryset(self): return Employee.objects.using(schema).filter(exp_gte=date).select_related('dep') Sql statement create is in this form Select `Employee`.`dep`, `Employee`.`exp`, `Department`.`id` from `Employee` Inner Join `Department` on `Department`.`id`= `Employee`.`dep` Where `Employee`.`exp` >= date; Why is join before where clause. And how can I apply join after where clause using Django ORM -
NoneType object is not callable django admin
I have an app in django admin, im trying to make some validations, Transaction model and its a parent for 2 models, FamilyGroup and FamilMember class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) number_of_family_group = models.PositiveSmallIntegerField( null=True) class FamilyGroup(models.Model): name = models.CharField(max_length=10, choices=name_choices) transaction =models.ForeignKey(Transaction,on_delete=models.CASCADE,related_name='family_groups') class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True, related_name='family_members') name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) Im trying to make custome validations in the transaction model like this @property def clean(self): b = FamilyGroup.objects.filter(transaction__id=self.id).count() if self.number_of_family_group != b: raise ValidationError('worng family') when im trying to do this im getting an error NoneType object is not callable -
'WSGIRequest' object has no attribute 'build_absolute_url'
I am building a BlogApp AND I am building Post Share Feature AND I am stuck on an Error. When i click on Share Button then it is showing me this error :- 'WSGIRequest' object has no attribute 'build_absolute_url' views.py def post_share(request, post_id): post = get_object_or_404(Post,id=post_id) sent = False if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_url(post.get_absolute_url()) subject = f"{cd['name']} recommends you read "\ f"{post.post_title}" message = f"Read {post.post_title} at {post_url}\n\n" \ f"{cd['name']}\'s comments, {cd['comments']}" send_mail(subject, message, 'admin@myblog.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'post_share.html', {'post':post,'form':form}) models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') date_added = models.DateTimeField(auto_now_add=True,null=True) description = models.CharField(max_length=10000,default='') post_share.html {% extends 'base.html' %} {% block title %}Share a Post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p> "{{ post.post_title }}" was successfully sent to {{ form.cleaned_data.to }}. </p> {% else %} <h1>Share "{{ post.post_title }}" by e-mail</h1> <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send by e-mail"> </form> {% endif %} {% endblock content %} The Problem When i click on Send by Email then it keeping showing me 'WSGIRequest' object has no attribute 'build_absolute_url' … -
the use of the underscore : q.choice_set.all()
I am working on the Django "Writing your first Django app, part 2", in the section "2.4.4 Playing with the API". If someone could explain to me how does the underscore works in this code "q.choice_set.all()" -
Django 'ManagementForm data is missing or has been tampered with' foreign manytomany foreign key
I'm getting this error after submitting my form(it uses inlines and foreign keys). This is a follow up to my question: How to save a model in ModelForm with two ForeignKey fields in Django Now my views.py looks like this: def CreateFlo(request): EstadosInlineFormSet = inlineformset_factory(Listaflor, Flora2Estado, form=Flo2Form) floForm = FloForm(request.POST) if request.method == 'POST': if floForm.is_valid(): new_flo = floForm.save() estadosInlineFormSet = EstadosInlineFormSet(request.POST, request.FILES, instance=new_flo) if estadosInlineFormSet.is_valid(): estadosInlineFormSet.save() else: estadosInlineFormSet = EstadosInlineFormSet() floForm = FloForm() context = {'floForm': floForm} return render(request, 'accounts/enviar_flora.html', context) -
Separate two forms' values in django
I'm working on an ecommerce website. Currently, I'm trying to add variations for products. Variations are dynamic. For adding products to the cart I have two forms, one for general details of the product, and the other for the variations. The problem is when I add a product with specific variations I can't separate these two forms' values from each other. The post request's data is like this --> <QueryDict: {'quantity': ['1'], 'override': ['False'], 'Color': ['1'], 'Size': ['3']]}> As I said color and size are dynamic and it could be more variations, and these are variation items so if I could change post request data to be like this --> {'variations': [1, 3]} it could solve the problem. # forms.py class VariationForm(forms.Form): def __init__(self, variation_fields, *args, **kwargs): super(VariationForm, self).__init__(*args, **kwargs) for field in variation_fields: self.fields[field.name] = forms.ModelChoiceField( queryset=field.item_variations.all()) # views.py @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) # Variation form should come here if form.is_valid(): cd = form.cleaned_data cart.add( product=product, quantity=cd['quantity'], override_quantity=cd['override'], ) return redirect('cart:cart_detail') -
is configured to read a sid, but the database has changed to service_name. What changes should I make?
is configured to read a sid, but the database has changed to service_name. What changes should I make? -
How to use django_crontab with os.environ['SECRET_KEY']?
I'm using a django_crontab library and it worked fine until I decided to export my SECRET_KEY to an environmental variable. Summing up what I have done in bash (while in my venv): export SECRET_KEY='some_secret_key_from_settings' In settings.py: SECRET_KEY = os.environ['SECRET_KEY'] In addition, I use venv, so I've also added this to settings: CRONTAB_PYTHON_EXECUTABLE = '/path_to_my_venv/venv/bin/python3' This is the error that I have: SECRET_KEY = os.environ['SECRET_KEY'] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 681, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' The closest solution I found was this: https://github.com/kraiz/django-crontab/issues/74 However, I'm not too experienced in this stuff and didn't understand what I should do. I will be very grateful for answers with explicit steps I could take to make it work -
How to convert string to list in python. Like "['a']" to ['a']
I get list form database as a string. But how to convert string to list. For example I get '["a","b"]' but it is string format how to convert it ["b","b"]. i was also trying list() method. userf = user.pending print(userf) #userf is "['animation']" userf.append(tosend).save() -
I am unable to connect one of the .html files from the quiz application to the django application. (Page not found (404))
I have a quiz app (QuizApp) inside my django app. (basic_app) Everything is working fine up to the moment, where the game ends and the quiz_end.html page is not displaying. Here is a link to quiz_game.js inside the quiz_game.html file - (quiz_js is in this case a folder situated inside the django´s static folder) <script src="{% static "quiz_js/quiz_game.js" %}"> Here is some kind of link to the end.html file inside the quiz_game.js file - (the game is finished, when there are no questions left) if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) { localStorage.setItem("mostRecentScore", score); //go to the end page return window.location.assign("/end.html"); }; (You can see the full code of this file here - https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript/blob/master/Quiz%20App%20Master/game.js - it´s just called game.js instead of quiz_game.js + You can see all of the files from the Quiz App here - https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript/tree/master/Quiz%20App%20Master) But since I am using Django, I was trying to incorporate template tag into the quiz_game.js file like this - (I am not sure, if I am doing it right) getNewQuestion = () => { if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) { localStorage.setItem("mostRecentScore", score); //go to the end page return window.location.assign("{% url 'quiz_end' %}"); }; The thing is, that this … -
Django + Nginx + Uwsgi see Nginx default page then run on 80 port
I have Django app that runs on VPS using Nginx + Uwsgi. The Symlink nginx config # the upstream component nginx needs to connect to upstream django { server unix:///root/ubergf/client/uwsgi_nginx.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name my-site.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /root/ubergf/client/media; # your Django project's media files - amend as required } location /static { alias /root/ubergf/client/staticfiles; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /root/ubergf/client/deployment/uwsgi_params; # the uwsgi_params file you installed } } uwsgi_params uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME … -
Splitting a monolith file Django
First to set the scene a little. I am working on piece of software that has been worked on by a number of developers over the years, each making improvements, and compromises along the way. We have about 30 apps in the project, but about 60% of all of the code is in one models file. In recent years we have been moving away from this monolithic architecture, but we have not had the time/willingness to actually spilt this file up. It is causing issues just loading and searching the file at the moment. I am looking for any advice or strategies that could help with this. I have been looking into three methods/paths, but I am not sure if they are a good idea, or if there is a better one. Moving Models out 1-by-1. Hard code in the database name, and then overwrite the migration so no data is deleted, and move out each model one by one to their new home. Make the file into a directory. Instead of being one file, split this up into a number of files. This will alleviate the current issues we are having with the file size. And will also spilt … -
`basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute
I'm new in Django stuff and would like to build an API Server. However, when I register the ModelViewSet I get the error shown in the title. Model: from django.db import models from django.core.exceptions import ValidationError class User(models.Model): telegram_id = models.CharField(max_length=50) mail = models.CharField(max_length=100, default="None") password = models.CharField(max_length=100, default="None") is_group = models.BooleanField(default=False) priority = models.IntegerField(default=10) max_watches = models.IntegerField(default=5) current_watches = models.IntegerField(default=0) notification_rate = models.IntegerField(default=3600) watches = models.ManyToManyField('Url', through="Watch") def save(self, *args, **kwargs): if self.current_watches > self.max_watches: raise ValidationError("Límite de enlaces alcanzado") super().save(*args, **kwargs) def __str__(self): return self.telegram_id Serializer: from rest_framework import serializers from hermes.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' ViewSet: from rest_framework import viewsets import hermes.models as models import hermes.serializers.UserSerializer as UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = UserSerializer router: from hermes.ViewSets import UserViewSet from rest_framework import routers router = routers.DefaultRouter() router.register(r'users/', UserViewSet) router in app: from django.contrib import admin from django.urls import path, include from hermes.urls import router urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) ] I have also added the basename param at the end of the router as it suggested me but is fails again saying that it has no attribute get_extra_actions. And when I define that method it … -
Reduce the range of minutes displayed in the user form. Django
I have a problem with the correct display of data picker for the user, exactly I mean if I am able to reduce the range of displayed time to choose this is my forms.py file class EventForm(ModelForm): class Meta: model = Event widgets = { 'start_time': DataInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DataInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M',), } exclude = ['user'] # def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',) In the template, the user has a choice of dates and times from this range Is it possible to add some restrictions when selecting dates, e.g. selecting only days of a given month or only days of a given week? The same question about time selection e.g. am I able to limit the range only to 9:00-9:30 with a half-hour interval and not with a minute interval -
django formset not valid in edit mode
i can save a formset in post method, but when i try to edit it in my "put" method, my formset.is_valid returns false ... i excluded some logic in this code samples and replaced it with .... so it is easier to read... hope this is enough information to get an idea of my problem my view.py class AngebotView(View): def get(self, request, id=None): if id: ................. raum_formset = RaumFormSet(queryset=objekt.t_raum_set.all()) raum_formset.extra = 0 template = 'angebot/edit_angebot.html' else: ..................... # Create an instance of the formset raum_formset = RaumFormSet(queryset=T_Raum.objects.none()) template = 'angebot/new_angebot.html' context = {'kunde_form': kunde_form ,'angebot_form': angebot_form, 'objekt_form': objekt_form, 'raum_formset': raum_formset} return render(request, template, context) def post(self, request, id=None): # Post = Speichern/Ändern context = {} if id: return self.put(request, id) #Forms aus Request holen kunde_form = KundeForm(request.POST, instance=T_Kunde()) angebot_form = AngebotForm(request.POST, instance=T_Angebot()) objekt_form = ObjektForm(request.POST, instance=T_Objekt()) formset_raum = RaumFormSet(data=self.request.POST) #wenn die Eingabe der Formen passt if kunde_form.is_valid() and angebot_form.is_valid() \ and objekt_form.is_valid() \ and formset_raum.is_valid(): .................. #Alle Instanzen des Formsets in raum_instances #Mit den Instanzen kann man dann weiterarbeiten, Foreign Key setzen etc... raum_instances = formset_raum.save(commit=False) for new_raum in raum_instances: new_raum.objektid = new_objekt new_raum.save() messages.success(request, 'Angebot wurde gespeichert!') return HttpResponseRedirect(reverse('angebot:angebot_details', kwargs={'id': new_angebot.id})) else: #TODO: Errorhandling raise Http404 context = {'angebot_form': … -
How do I make this appear in Djanog-Python?
I'm currently in the process of building a hospital management app with using Django and Python In the index page, I want to show the total patient numbers, yet the code I've inputted does not make that happen. Also, I've cut most of the HTML code for this since the full code went over the word count limit. The following are the code: index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Lifesaver</title> <!-- Custom fonts for this template--> <!-- <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> --> <link href="{% static 'startbootstrap-sb-admin-2-gh-pages/vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <!-- <link href="css/sb-admin-2.min.css" rel="stylesheet"> --> <link href="{% static 'startbootstrap-sb-admin-2-gh-pages/css/sb-admin-2.css' %}" rel="stylesheet"> </head> <body> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <!-- {% include 'lifesaver/sidebar.html' %} --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-laugh-wink"></i> </div> <div class="sidebar-brand-text mx-3">LifeSaver </ul><div> </a> <!-- Divider --> <hr class="sidebar-divider my-0"> <!-- Nav Item - Dashboard --> {% include 'lifesaver/navbar_user.html' %} </ul> <!-- End of Sidebar --> <!-- Content … -
Users are not highlighted when they presses the like button and also doesn't show the count of likes ..in django. Can You suggest me any solution
registration and login page is working properly but mine like button is not working it doesn't highlight users who presses like button and also doesn't show the count of like .. I don't know why... Can somebody help me to solve this issue … it will be great help please help Thank you! Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required # Create your views here. @login_required def likes(request, pk): post = get_object_or_404(Post, id=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity', args=str(pk))) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} def __init__(self, *args, **kwargs): stuff = get_object_or_404(Post, id = self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() context={"post":post} return render(request, "datasecurity/blogHome.html", context) 2.urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"), ] Models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes = models.ManyToManyField(User, related_name='likes') @property def total_likes(self): return self.likes.count() def __str__(self): return self.title + …