Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Version controlling programming in django rest framework for mobile app
I am using django rest framwork. I have four version of same application and code is different depending on the version . So, I am implementing if else conditions in my code. ex: version1 = ('1.0','2.0') version2 = ('3.0','4.0') if request.META['HTTP_VERSION'] in version1: #run this code elif request.META['HTTP_VERSION'] in version2: #run this code else: # run this code Is there any better way to implement code for different app version in django rest framework. Please suggest me. -
Dynamic dictionary name in templatetag
I have a templatetag to get the dictionary name and the element in it. I have the dictionaries in dictionary.py and i've imported the same as dict inthe templatetag. Like this, import property.dictionary as dict def getlisttype(value,arg): return dict.value[arg] im passing the dictionary name as value and the element in it as arg. But what im getting is the particular alphabet in the dictionary name(like names[1]-->'a'). Is there a way to do this? -
Django migrate didn’t launch execute some migration files
I have a Postgres database full of data. And I made several changes to my Django app models. mange.py makemigrations worked fine and created the migration files. But manage.py migrate execute only one file. And when I launch it again it doesn’t execute the rest as if they are already applied. I deleted the migration files that were not applied and did another makemigration but it says no changes detected. Any ideas how to reflect the models changes on the database without losing the data ? Thanks -
Form is not getting rendered to the FrontEnd
When i am hitting the URL, only html button is getting rendered,form.as_p is now getting rendered. Please be helping me out. Thanks urls.py from django.urls import path from . import views urlpatterns = [ path('signup/',views.SignUp, name = 'signup_view'), ] my code : forms.py from django import forms from .models import Profile from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['user','bio','location','birth_date'] class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=200,required=True,help_text='Hello') last_name = forms.CharField(max_length=200,required=True) email = forms.EmailField(max_length=500,help_text='Enter a valid email address') class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2',] views.py from django.shortcuts import render,redirect from django.contrib.auth import login,authenticate from .forms import SignUpForm def SignUp(request): form = SignUpForm() if request.method == 'POST': print(request.method) form = SignUpForm(request.POST) if form.is_valid(): form.save() raw_username = form.cleaned_data.get['username'] raw_password = form.cleaned_data.get['password1'] user = authenticate(username = raw_username,password = raw_password) login(request,user) return redirect('home') else: return render(request,'registration/signup.html',{'form':form}) templates/registration/signup.html <form method="post"> {% csrf_token %} {{ from.as_p }} <button value="submit" type="submit">SignUp</button> </form> -
Django Autocomplete Light - Search Not Working on Widget
I have been following the tutorial located at here I can get the autocomplete item to load on the HTML page and it displays the results from the queryset in the dropdown, but it will not search when typing the names of the values. A warning is given in the console which states Use of Mutation Events is deprecated. Use MutationObserver instead. I am unsure of where to look next. Does this warning directly relate to the search function not working? Am I meant to use a different version of JQuery or is it related to the Python code? JQuery is currently 3.3.1. Can anyone help with this? -
Django-vote with Ajax no refresh page
I am using django-vote for my blog app, it working well when click the vote button, but it redirect to the home page after voted. so i want to using jquery ajax. Actually i am poor at JS, I searched a lot about Ajax for vote or like button, but I can't apply it to my code. so i wanna some help. This is my Django code: models.py: class Blog(VoteModel, models.Model): title = models.CharField(max_length = 100) ...... url.py: ...... url(r'^vote/(?P<blog_id>[0-9]+)/upvote/$', views.up_vote_blog, name='upvoteblog'), url(r'^vote/(?P<blog_id>[0-9]+)/downvote/$', views.down_vote_blog, name='downvoteblog'), ...... view.py ...... @login_required def up_vote_blog(request, blog_id): blog = Blog.objects.get(pk=blog_id) blog.votes.up(request.user.id) return HttpResponseRedirect(reverse('blog:index')) @login_required def down_vote_blog(request, blog_id): blog = Blog.objects.get(pk=blog_id) blog.votes.down(request.user.id) return HttpResponseRedirect(reverse('blog:index')) ...... html: <div class="col-md-6 col-xs-6"> <a class="downvote" href="{% url 'blogs:downvoteblog' blog_id=blog.pk %}"><i class="fa fa-thumbs-down"></i></a> <span class="vote">{{ blog.vote_score }}°</span> <a class="upvote" href="{% url 'blogs:upvoteblog' blog_id=blog.pk %}"><i class="fa fa-thumbs-up"></i></a> </div> The function that I wanna is that when I click upvote or downvote icon, it only update blog.vote_score. I don't need to refresh the page or redirect and no need any message out. -
How start start celery worker in Django project
I have a Django project with the directory structure mentioned below. I am trying to use Celery for running tasks in the background. I have facing some trouble while running the worker. Whenever I issue the following command, I get an error. Command $ celery -A tasks worker --loglevel=info From the projectdirectory where manage.py resides ModuleNotFoundError: No module named 'tasks' From the projectdirectory where celery.py resides ModuleNotFoundError: No module named 'tasks' From the appdirectory where tasks.py resides AttributeError: module 'tasks' has no attribute 'celery' Project Structure project |-- app |-- admin.py |-- apps.py |-- __init__.py |-- models.py |-- tasks.py |-- tests.py |-- urls.py |-- views.py |-- project |-- celery.py |-- settings.py |-- __init__.py |-- urls.py |-- wsgi.py |-- manage.py -
Django MySQL connection Error on windows Server
I have tried using pip install mysqlclient and it says Requirement already satisfied: mysqlclient in c:\program files\python37\lib\site-packages (1.3.12) I have MySQL installed with the connector as well but when i try to pip install MySQL-python It Throws an error. it says Failed building Wheel for MySQL-python... it also throws this exception try: import MySQLdb as Database except ImportError as err: raise ImproperlyConfigured( 'Error loading MySQLdb module.\n' 'Did you install mysqlclient?' ) from err When i try to migrate the database, it doesnt migrate because it says mysql is not linked... -
(callable not found or import error) no app loaded. going in full dynamic mode
This has been bothering me for hours and have no idea what is going on. When I tried visiting the site through only ip. I get the word internal server error I get this error log when I restart daemon and uwsgi *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** Python version: 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] Set PythonHome to /root/wxr/wxr *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0xe0db20 uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 437520 bytes (427 KB) for 5 cores *** Operational MODE: preforking *** Traceback (most recent call last): File "./main/wsgi.py", line 10, in <module> import os ImportError: No module named os unable to load app 0 (mountpoint='') (callable not found or import error) Traceback (most recent call last): File "/root/wxr/wxr/main/wsgi.py", line 10, in <module> import os ImportError: No module named os unable to load app 0 (mountpoint='') … -
how to have dynamic modal in datatable
{% for key,value in config.items %} <button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-id={{ key }} data-target="#myModal"><i class="glyphicon glyphicon-pencil" aria-hidden="true"></i></button>{{key}} </td> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true"> <div class="modal-dialog" id= {{ forloop.counter }> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title custom_align" id="Heading">Edit Your Version for <strong>{{key}}</strong></h4> </div> <div class="modal-body"> <div class="form-group"> <input class="form-control " type="text" placeholder={{key}} {{ forloop.counter }}> {{ forloop.counter }} </div> </div> <div class="modal-footer "> <button type="button" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-ok-sign"></span> Accept</button> <button type="button" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove-circle"></span> Reject</button> </div> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> {% endfor %} //I have a datatable where the rows are getting populated based on the loop values. Now inside the datatable in one particular row I have a button upon clicking it I should display the values of the particular row. But the problem I am facing is only the first value is getting displayed in the modal. when i am trying to check through {{ forloop.counter }} The value is always 1 inside the modal.But if i check outside the modal it is incrementing. Can anyone guide me -
Can I delete an object of a model from view even though the user doesn't have permission? Django
I have created a model X, now created a user U, I assigned a group to this user G, G has only create and change permissions for the model X, Now I created a view where it lists all model X objects and delete button across each object, now when I am logging in with my user U, he can access that view( I am not restricting him here ) and he is able to delete that object from that model? Is it how it works? I need to restrict him from view too as well as at user permission level(groups)? -
How to send file to response in Django?
I have such php function which I try to rewrite in my Django project. What should be an analogue in python for php methods like header() and show_error()? Also how to send file to response? php: function waprfile($date=false) { if(!isset($date) || $date==false) $date = date("d.m.y"); $timestmp = date2timestamp($date); $filepath = "https://www.example.com/files/".$this->lang_code."/"; if(file_get_contents($filepath.date("dmy",$timestmp).".xls")) { header("Location: ".$filepath."wapr".date("dmy",$timestmp).".xls"); } else { show_error(_langWrite("No file for specified date", "Файл на указанную дату отсутствует")); } } python: import urllib.request import datatime import time from django.utils import translation def isset(variable): return variable in locals() or variable in globals() def waprfile(request, date): if(not isset(date) or date==False): date = datetime.datetime.now().strftime('%d.%m.%Y') timestmp = time.mktime(datatime.datetime.strptime(date, "%d.%m.%Y").timetuple()) filepath = "https://www.example.com/files/" + str(translation.get_language()) + "/" formatted_date = datetime.datetime.fromtimestamp(timestmp).strftime('%d%m%y') if(urllib.request.urlopen(filepath + formatted_date + '.xls')): # What must be here? else: # What must be here? response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=' + fileName return response -
Nested API View of Django REST Framework?
At the moment I developed the following code, for me to get the Contact List of each user. The views return the ID numbers of the Contacts of the User. I need to get, instead of the ID numbers, the 'name' and 'last_name' attribute of said contacts. I am quite new to Django's REST Framework and I'm not quite sure what to do next but I believe I have to nest the APIView. I would really appreciate some help! views.py def list_contacts(request, id_profile): url = request.build_absolute_uri(reverse('api_users:contact_list', kwargs={'pk':id_profile})) response = requests.get(url) profile = Profile.objects.get(pk=id_profile) if response.status_code == status.HTTP_200_OK: data = response.content user = json.loads(data) return render(request, 'profiles/contact_list.html', {'user':user}) models.py class Profile(models.Model): id_user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birthday = models.DateField(auto_now=False) description = models.CharField(max_length=100) profile_picture = models.ImageField(upload_to='images/profiles/%Y/%m/%d', blank=False) active = models.BooleanField(default = False) contacts = models.ManyToManyField('self', blank=True, default='null') created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) deleted_at = models.DateTimeField(blank=True, null=True) class Meta: ordering = ('-id',) def __str__(self): return self.name+' '+self.last_name def active_profiles(): return Profile.objects.filter(active=True) api/views.py class ContactListView(generics.ListAPIView): queryset = Profile.objects.all() serializer_class = UserContactListSerializer filter_backends = (filters.SearchFilter,) search_fields = ('name', 'last_name',) def get(self, request, pk, format=None): contacts = Profile.objects.get(pk=pk) serializer = UserContactListSerializer(contacts) return Response(serializer.data) api/serializers.py class UserContactListSerializer(serializers.ModelSerializer): class Meta: model = … -
Linked to a valid external css but display was not styled
My project forum structures its files as: forum ├── __init__.py ├── settings.py ├── static │ └── css │ └── bootstrap.min.css ├── templates │ └── index.html ├── urls.py └── wsgi.py I linked "bootstrap.min.css" to index.html like: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Forum Home Page</title> <link rel="stylesheet" href="/static/css/bootstrap.min.css" /> </head> <body> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-12"> <h2>Coding Journey</h2> </div> </div> <div class="row"> <div class="col-xs-12 col-md-2">Concepts <button type="button" class="btn btn-success">Submit</button> </div> <div class="col-xs-12 col-md-2">Reading</div> <div class="col-xs-12 col-md-2">Coding</div> </div> </div> <!--container--> </body> </html> However, when open the index.html in browser, it's not styled at all. What's the problem with my operations? -
Django js.stripe populating visiblie html class when it shouldn't
I'm trying to implement this example. When I load the page, I see that the class outcome/success is displayed even before the submit button is clicked. However, on the example, it doesn't appear until the submit button is clicked. What am I doing wrong? When I look at the html, it looks like it should appear automatically, however when I look at the example (above) it only appears after the submit button is given. Code: {% extends 'base.html' %} {% block content %} <script src="https://js.stripe.com/v3/"></script> <div class='col-10 col-md-6 mx-auto'> <!-- <form action="//httpbin.org/post" method="POST"> --> <form method="POST"> {% csrf_token %} <input type="hidden" name="source" /> <div class="group"> <label> <span>Name</span> <input id="name" class="field" placeholder="Jenny Rosen" /> </label> <label> <span>Type</span> <select id="type" class="field"> <option value="individual">Individual</option> <option value="company">Company</option> </select> </label> <label> <span>Routing number</span> <input id="routing-number" class="field" placeholder="110000000" /> </label> <label> <span>Account number</span> <input id="account-number" class="field" placeholder="000123456789" /> </label> </div> <button type="submit">Submit</button> <div class="outcome"> <div class="error"></div> <div class="success"> Success! Your Stripe token is <span class="token"></span> </div> </div> </form> </div> <script> var stripe = Stripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh'); var elements = stripe.elements(); function setOutcome(result) { var successElement = document.querySelector('.success'); var errorElement = document.querySelector('.error'); successElement.classList.remove('visible'); errorElement.classList.remove('visible'); if (result.token) { // Use the token to create a charge or a customer // … -
Permission problems with Django/Celery on Elastic Beanstalk
My application (clads) runs on Django and uses Celery for timed and asynch tasks. Unfortunately, I can’t seem to figure out some permission issues that are preventing the Celery processes from writing to the Django application logs or from manipulating files created by the Django application. The Django application runs in the wsgi process and I have some configuration files that set up the application log directory so that the wsgi process can write to it (see below). However, it seems the celery processes are running as a different user that doesn’t have permission to write to these files (which it automatically tries to do when it sees the log file configuration – also below. Note I tried to change this to run as wsgi but didn’t work). This same permissions issue seems to be preventing the Celery process from manipulating temporary files created by the Django application – a requirement of the project. I’m admittedly very rusty on Unix type OSes so I’m sure I’m missing some simple thing. I’ve been searching this site and others on and off for a few days and while I have found many posts that have gotten me close to the issue, I … -
How to Generate Barcode for Django Models?
I want to generate barcode for Django Models and save them as pdf or png format. I tried pybarcode and reportlab . It was easier to generate barcode for one instance whereas i want to generate for all the item in a particular model . Help please . -
save the user input field to another model - django
I have two models Product and Category. There is a user field in the product and while purchasing the user can select the category from a list (populated from category model). But if the user cannot find the desired category, and enters it in a text box, can you suggest me on how to add it to the category model ? models.py class Product(models.Model): buyer = models.ForeignKey(User, on_delete = models.CASCADE) desc = models.CharField(max_length=100) cant_find_your_categ = models.BooleanField(blank=True,default=False) please_fill_in_your_categ = models.CharField(max_length = 50, blank = True) def get_absolute_url(self): return reverse("product_detail",kwargs={'pk':self.pk}) def __str__(self): return self.desc class Category(models.Model): name = models.CharField(max_length=200) product = models.ManyToManyField(Product, blank=True, related_name="categ") def __str__(self): return self.name forms.py class ProductForm(forms.ModelForm): categ = ModelMultipleChoiceField(queryset=Category.objects.all(), widget=CheckboxSelectMultiple()) class Meta(): model = Product exclude = ('buyer', ) widgets = { 'desc': TextInput(attrs={'class' : "form-control form-control-sm",}), 'categ': CheckboxSelectMultiple(),} -
Error ImportError: No module named 'encodings' in virtual environment using pyenv
I am trying to publish the site created by Django using apache. The settings of the server are as follows. ・ CentOS 7.2 ・ Python 3.6 ・ Django 2.0 ・ apache 2.4 I am preparing a virtual environment using pyenv as follows. git clone https://github.com/yyuu/pyenv.git ~/.pyenv … pyenv install anaconda3-5.1.0 pyenv rehash pyenv global anaconda3-5.1.0 … yum install httpd httpd-devel systemctl start httpd systemctl enable httpd …. wget https://github.com/GrahamDumpleton/mod_wsgi/archive/4.5.14.tar.gz tar -zxvf 4.5.14.tar.gz cd mod_wsgi-4.5.14/ ./configure --with-python=/home/username/.pyenv/versions/anaconda3-5.1.0/bin/python make sudo make install … ■ httpd.conf NameVirtualHost *:80 LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so WSGISocketPrefix /var/run/wsgi <VirtualHost *:80> ServerName xxx.com DocumentRoot /var/www/html WSGIScriptReloading On WSGIDaemonProcess xxx python-path=/home/username/.pyenv/versions/anaconda3-5.1.0/lib/python3.6/site-packages python-home=/home/username/.pyenv/versions/anaconda3-5.1.0 WSGIProcessGroup xxx WSGIScriptAlias / /var/www/html/xxx/xxx/wsgi.py <Directory "/xxx/"> Order deny,allow </Directory> </VirtualHost> The following error will occur with this setting. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Setting chmod should be fine. What other reasons can be considered? -
'webpack_loader' is not a registered tag library
I am starting to learn some react, and trying to learn how to combine ReactJS and Django. I am currently following the proposed tutorial here After setting up the django urls, and installing django-webpack-loader, I am stuck with the following error when running the django server: TemplateSyntaxError at / 'webpack_loader' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz I already tried going on, and setting up the rest, but nothing seems to work. The error I am getting is different from the one in the tutorial and both in the github page of django-webpack-loader package and here I can't see any problem like this. The solutions for similar errors I found here did not solve my problems, so I am not sure what or where the error is lying. I tried: Literally copy-pasting the tutorial code remaking the entire project several solutions like creating a custom tag checking if the react(webpack) server is running Info: Django version 2.0.5 django-webpack-loader==0.6.0 Python version 3.6.5 Running on Ubuntu x64 18.04 LTS Thanks for any help, and sorry if this is a stupid, simple to solve mistake. -
Django Form doesn't Get Correct Columns
I have struggled with this for about an hour and cannot seem to find a solution. I have a django model that I have created form with using ModelForm. The form is inside a view and I want to manipulate the form variables before submitting to the database. The problem is that I cannot seem to get the correct columns to reference from the database for the form. Instead it looks like it is referencing the columns from another related table. Any suggestions? Models class RoutinePlans(models.Model): routine = models.ForeignKey(Routines, on_delete='CASCADE') exercise = models.ForeignKey(WeightExercises, on_delete='PROTECT') set = models.IntegerField() set_type = models.ForeignKey(SetType, on_delete='PROTECT') reps = models.IntegerField() day = models.IntegerField() week = models.IntegerField() def __str__(self): return self.routine.name class Routines(models.Model): name = models.CharField(max_length=50) level = models.ForeignKey(RoutineLevels, on_delete='PROTECT') creator = models.ForeignKey(User, on_delete='CASCADE') status = models.TextField(max_length=50) description = models.TextField(max_length=255, null='TRUE', default=None) def __str__(self): return self.name Forms class PlanForm(forms.ModelForm): DAY_CHOICES = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7')) day = forms.ChoiceField(widget=forms.Select, choices=DAY_CHOICES) class Meta: model = RoutinePlans exclude = ['routine'] Views def editplan(request, routine_id): form = forms.PlanForm() routine_name = Routines.objects.get(id=routine_id).name if request.method == 'POST': form = forms.PlanForm(data=request.POST) if form.is_valid(): obj = form.save(commit=False) #this is where I want to put obj.routine … -
I have downloaded eclipse and pydev, but I am unsure how to get install django
I am attempting to learn how to create a website using python. I have been going off the advice of various websites including stackoverflow. Currently I can run code in eclipse using pydev, but I need to install django. I have no idea how to do this and I don't know who to ask or where to begin. Please help -
django Modelform not returning datetime object but forms.Form does?
I have a form that asks users for a due date and stores that date into the model. I get a match = time_re.match(value) TypeError: Expected string or byte sized object error if I use Modelforms in my models.py but i don't get this error and everything works fine if I use forms.Form However I need fields from my model to complete the form. Is there anyway around this or can someone please explain to me why this is? Thanks so much, blow is the code that throws an error: class UpdateKeyRequestForm(ModelForm): class Meta: model = KeyInstance fields = ['request_status', 'status'] due_date = forms.DateField(help_text='Enter a date (YYYY-MM-DD) between now and 4 weeks (default 3). ') def clean_due_date(self): due_date = self.cleaned_data['due_date'] approved_status = self.cleaned_data['request_status'] availability = self.cleaned_data['status'] # Check date is not in past. if due_date < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) if due_date > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) if approved_status == 'a' and availability != 'o': raise ValidationError(_('Please Mark Key Status To ON LOAN if you would like to approve')) return due_date, approved_status, availability -
Django server on Digital Ocean connection reset by peer
I'm trying to set up a django server on my digital ocean instance with Django 2.0.4 and a Ubuntu 16.0.4 droplet. I ssh into the droplet as root and start the server with python manage.py runserver 0.0.0.0:80 And the django server would start up fine. But a few seconds later without me doing anything, these errors would come up repeatedly: ---------------------------------------- ---------------------------------------- Exception happened during processing of request from ('175.100.8.37', 12774) Traceback (most recent call last): File "/usr/lib/python3.5/socketserver.py", line 625, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.5/socketserver.py", line 681, in __init__ self.handle() File "/root/website/back-end/env/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 139, in handle self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.5/socket.py", line 575, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- ---------------------------------------- Exception happened during processing of request from ('175.100.8.37', 12775) Traceback (most recent call last): File "/usr/lib/python3.5/socketserver.py", line 625, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.5/socketserver.py", line 681, in __init__ self.handle() File "/root/website/back-end/env/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 139, in handle self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.5/socket.py", line 575, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- This is my ALLOWED_HOSTS settings: ALLOWED_HOSTS = [ "tedxuwa.com", "www.tedxuwa.com", "localhost:8000" … -
Count of posts with users list - django
How can I display the count of total posts made by a user. I have used django's built in user model. Can I display a list of users with their total count? models.py class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) title = models.CharField(max_length=100) def publish(self): self.published_date = timezone.now() Tag.name = self.please_fill_in_your_tag self.save() def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title