Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter Queryset Model
How can I filter my table to only show the quotes from a project. In order to display all quotes, I am using {% for quote in quotes.all %} Now, I would like to display quote relative to a site. Which means when selecting my site_id, I`ll be able to only see the quote relative to this site_id. I could write something like {% for quote in quotes.all %} {% if quote chantier.id %} {% endif %} {% endfor %} but this is wrong. Here is my model for quote: models.py class Quote(models.Model): name = models.CharField(max_length=30) site = models.ForeignKey(Site, on_delete=models.CASCADE) How can I display all quotes from this site? Many Thanks, -
Hosting Django with Apache2 on an Docker
Friday I spent 5 hours on my work setting up Django. Django works perfectly fine, but i can't acess the test environment. My Docker got an web adress where I can acess it and i want to open the Django Environment over web. I My Problem is I can't seem to get it right. What I do it does'nt work I can't acess it over web. Here is a Link of an example Guide I used where I tried linking up Django with Apache2. https://www.metaltoad.com/blog/hosting-django-sites-apache Maybe someone of you can help me to get it right. -
Django TemplateDoesNotExist at / Help! I feel I tryed everything =´ (
Im a new self taught programmer (I started a few months agos with java) from Cordoba Argentina and this is my first post here. Im stuck on this problem for the last two days, I was working on my firts project and I reinstall windows on my computer, after I install Python 3.8.3 and Django 3.0.7, anaconda, visual studio code, and a lot of shit. When I continue with my project, I follow my tutorial made some changes and after running the server I found with this error. After going back to what I think what I was the last time It works, I reinstall everything again thinking that maybe was some mistake on the installation. I tried with the templates DIRS too and I got the same error. The place where my templates are is F:\Programacion\Python\Django\ProyectoWeb\ProyectoWebApp\templates\ProyetoWebApp TemplateDoesNotExist at / ProyectoWebApp/Inicio.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.7 Exception Type: TemplateDoesNotExist Exception Value: ProyectoWebApp/Inicio.html Exception Location: D:\Python\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: D:\Python\python.exe Python Version: 3.8.3 Python Path: ['F:\\Programacion\\Python\\Django\\ProyectoWeb', 'D:\\Python\\python38.zip', 'D:\\Python\\DLLs', 'D:\\Python\\lib', 'D:\\Python', 'C:\\Users\\frua\\AppData\\Roaming\\Python\\Python38\\site-packages', 'D:\\Python\\lib\\site-packages'] Server time: Sun, 7 Jun 2020 19:23:51 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: … -
How to get a full path of web page to my views.py?
How to get a full path of web page to my views.py? http://192.168.0.178:8000/customers-orders/37/customers-orders-date/?datefilter=06%2F14%2F2020+-+06%2F26%2F2020 How to get this path to my views.py for to work with it? -
inlineformset factory only save last form
i tried many ways and searched alot(googled) but no one worked for me . whenever i save my inlineformset it only save the last form , my models.py class Book(models.Model): book = models.CharField(max_length=20,unique=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) class Author(models.Model): author = models.CharField(max_length=30,unique=True) count = models.IntegerField() this is my forms.py class AuthorForm(ModelForm): class Meta: model = Author fields = ['author','count'] class BookForm(ModelForm): class Meta: model = Book fields = ['book'] inlineformset_author = inlineformset_factory = (Author,Book,form=AuthorForm,extra=1) this is my template class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Author form_class = AuthorForm def get_context_data(self,*args,**kwargs): context = super(CreateBookView,self).get_context_data(*args,**kwargs) if self.request.POST: context['book'] = inlineformset_author(self.request.POST) context['book'] = inlineformset_author() return context def form_valid(self,form): context = self.get_context_data() context = context['book'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateBookView,self).form_valid(form) and this is my template <form method="POST">{% csrf_token %} {{book.management_form}} {{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}} <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> <div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"> <h5 class="modal-title" id="my-modal-title">BOOK</h5> <p class="close" data-dismiss="modal" aria-label="Close"> <div class="modal-body"> <button type="submit" class="btn btn-success">save</button></dic> </div> <div class='modal-footer'></form> <script> $(document).ready(function(){ $('#BOOKBTN').on('click',function () { let allValue=[]; let numberOfInput=$('#count').val(); let allContent=''; let justforName=0; let numOfContent=$('.modal-body input').length; for(let j=0;j<numOfContent;j++){ justforName=j+1; allValue.push($('input[name="BOOK'+justforName+'"').val()); … -
How to get a count of all instances of a foreign key in a different model?
I have model A and model B. Model B has a member foreign key of model A. I wish to keep try of the number of B's attached to model A. I would also like In model A we are trying to use and update the number off instances of B to A and hold that in model A num_B = models.IntegerField(default=0) In model B we have the member ForeignKey modelAInstance = models.ForeignKey(ModelA, on_delete=models.CASCADE) -
How to make custom error pages django 2.2
I am creating a blog using Django 2.2, and I have recently finished almost all of it. All that is left is making custom error pages. I have a book that shows how to do it, but it doesn't work. I have checked all over online, but nothing works. Please help? Here is the code: settings.py: """ Django settings for boy_talks_about_coding project. Generated by 'django-admin startproject' using Django 2.2.12. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8rk31cd@y065q)l9z2x@4j#a*gz6g3lw_$$g3e7#@de4xyj#xg' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost''boytalksaboutcoding.com''boytalksaboutcoding.herokuapp.com'] # Application definition INSTALLED_APPS = [ # My apps 'blog_posts', # Third party apps 'bootstrap4', # Default Django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'boy_talks_about_coding.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
What's the best way to authenticate user with a Django API?
I want to create a web application with Django as backend and react or angular as frontend, but I don't understand what's the best way to manage authentication. I heard a lot about JWT but I also read that it's insecure, so is there a way to auth with react and Django api for example ? -
Django dynamics colums forloop
I would like to know how you would solve my issue. I've managed a solution but aesthetically I don't like it I have a fix width box that I have to fill with a table (9 cols and 6 rows minimum). Some fields are fixed some others are dynamic. The results should be something similar to the following: | Order | <order_nr> | Qty | Desc | Price | Qty | Desc | Price | |----------------|--------------------|-----|------|-------|-----|------|-------| | Customer | | | | | | | | Address | | | | | | | | City | Zip code | | | | | | | | Shipping terms | Total order amount | | | | | | | | Note | <notes> | | | | | | | Qty Desc Price are dynamically generated based on the order that the customer has submitted, and potentially the order could have more than 10 lines (which my design is capable to handle) So here are my main problems and solutions: I have placed 2 tables together but I don't get the same line-height for both tables. I cannot add via CSS a fixed height since I don't know how … -
Easy editable table in django
I am new to programming and learning as I build more... I am working on creating a view to show a data table on the html page and used the below code so far.. Models.py from django.db import models class MySetters(models.Model): mytsettername = models.CharField(max_length=100) Allowed = models.BooleanField(default=False) def __str__(Self): return self.mytablename views.py def setterveiew(request): context = {'setterlist':MySetters.objects.all} return render(request,'setterspage.html',context) I was able to add it to the template and display the table and data. However, this table is currently readyonly.. is there a way to make it editable in line. read a lot of articles online however all of them are using ajax and jquery and I have no clue in that language and how to implement that. Also, Can someone please advise how to add a check box to the table so that users can select multiple of them and hit a button so that an action can be performed. Please advise. Thank you -
uwsgi: RuntimeError: cannot release un-acquired lock
I am running uwsgi (with django in a docker container), and every worker that spawns comes with this error: spawned uWSGI master process (pid: 1) web_1 | spawned uWSGI worker 1 (pid: 18, cores: 2) web_1 | Exception ignored in: <function _after_at_fork_child_reinit_locks at 0x7fd944954ca0> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/logging/__init__.py", line 260, in _after_at_fork_child_reinit_locks web_1 | spawned uWSGI worker 2 (pid: 19, cores: 2) web_1 | _releaseLock() # Acquired by os.register_at_fork(before=. web_1 | File "/usr/local/lib/python3.8/logging/__init__.py", line 228, in _releaseLock web_1 | _lock.release() web_1 | RuntimeError: cannot release un-acquired lock Here is my uwsgi .ini file: [uwsgi] strict = true ; only explicitly understood configration allowed module = myapp.wsgi need-app = true ; don't start if can't find or load django app ### PROCESS SETTINGS ############### master = true ; gracefully re-spawn and pre-fork workers, consolidate logs, etc enable-threads = true processes = 10 ; maximum number of worker processes threads = 2 thunder-lock = true socket = 0.0.0.0:8000 ; too complicated for me to get a unix socket to work with docker, this is fine. #socket = /tmp/myapp.sock vacuum = true ; on exit, clean up any temporary files or UNIX sockets it created, such … -
TypeError: createTask() got an unexpected keyword argument 'prefix'
I'm currently working on some presence project. Actually i did asking other question about this project before (but my coworkers suggest me to change some of the structure) I think this one is promising. But unfortunately, we get some error like TypeError: createTask() got an unexpected keyword argument 'prefix' Here's my app.py problematic programs: @app.route("/database", methods=['GET', 'POST']) def database(): cform = createTask(prefix='cform') dform = deleteTask(prefix='dform') uform = updateTask(prefix='uform') reset = resetTask(prefix='reset') if not session.get('email'): return redirect(url_for('login')) elif request.method == 'POST': if cform.validate_on_submit() and cform.create.data: return createTask(cform) if dform.validate_on_submit() and dform.delete.data: return deleteTask(dform) if uform.validate_on_submit() and uform.update.data: return updateTask(uform) if reset.validate_on_submit() and reset.reset.data: return resetTask(reset) # read all data docs = db.tasks.find() data = [] for i in docs: data.append(i) return render_template('database.html', cform = cform, dform = dform, uform = uform, data = data, reset = reset) here's my database.html <html> <head> <title>Simple Task Manager</title> <style> .newspaper { -webkit-column-count: 2; /* Chrome, Safari, Opera */ -moz-column-count: 2; /* Firefox */ column-count: 2; } .head { text-align: center; } </style> </head> <body> <div class="head"> <h1>SIMPLE TASK MANAGER</h1> <h2>using MongoDB</h2> </div> <div class="newspaper"> <form method="POST"> {{ cform.hidden_tag() }} <fieldset> <legend>Create Task</legend> {{ cform.nama.label }}<br> {{ cform.nama }}<br> {{ cform.tanggal.label }}<br> {{ cform.tanggal }}<br> … -
How to get foreign key id in serializer?
How can I get status_name and status id in Course serializer? Updated with status My models: class Course(models.Model): name = models.CharField(max_length=255) class Status(models.Model): COURSE_STATUS = ( ('DONE', 'Done'), ('IN PROGRESS', 'In progress'),) course_status = models.CharField(max_length=9, choices=COURSE_STATUS, default='DONE' ) course = models.ForeignKey(TrainingCourse, on_delete=models.CASCADE, related_name="courses") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="students") class Meta: verbose_name_plural = 'Statuses' verbose_name = 'Status' unique_together = ('user', 'course') My serializer: class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ['name'] -
Django rest-frameowrk required = False for nested serializer not working
Struggling since 2-3 hours now. Don't understand why I am not able to save VisVisitParametersSerializer. It gives an error This field may not be null. for parameter_values when I don't pass data for parameter_values. I have gone through the similar kind of issues disscussed here but that does not solve my problem. can someone help me on this? However, when trying to use this serializer and not supplying the details, I receive the following: Serializers: class VisVisitParametersSerializer(serializers.ModelSerializer): parameter_values = VisVisitParameterValuesSerializer(many=True, required=False, allow_null=True, ) class Meta: model = VisVisitParameters fields = '__all__' def create(self, validated_data): parameter_values = validated_data.pop('parameter_values') d = VisVisitParameters.objects.create(**validated_data) vparameter_id = VisVisitParameters.objects.latest('vparameter_id') for parameter_value in parameter_values: VisVisitParameterValues.objects.create(vparameter=vparameter_id, **parameter_value) return vparameter_id Models class VisVisitParameters(models.Model): vparameter_id = models.AutoField(primary_key=True) parameter_name = models.CharField(max_length=300, blank=True, null=True) parameter_description = models.TextField(blank=True, null=True) value_type = models.CharField(choices=value_type_text, max_length=8, blank=True, null=True) class VisVisitParameterValues(models.Model): vpvalue_id = models.AutoField(primary_key=True) vparameter = models.ForeignKey('VisVisitParameters', models.DO_NOTHING, blank=False, null=False) parameter_value = models.CharField(max_length=100) -
Better way of choosing foreign key option in django admin? (without the traditional dropdown and a method which allows filtering)
Is there a better way of selecting foreign key of a model in django admin? At the moment, the selection is the traditional dropdown, however, it is not scalable. Is there a feature which enables, perhaps a pop-up windows, which allows filtering the foreign key options (by its own foreign key) and choosing? -
Trigger Django Signal from Shell
I have configured a signal to run on post_save and its working fine in Django admin and API. But when I try to update the model using mymodel.save() using django shell it does not get triggered. Is there a workaround as I have to manually update the model and call the save method in some cases. -
Unable to load Static files into my Index.html in Django
I am new to Django and I am having a challenge in importing static files into my main HTML document. Can anybody help? Below is the approach I am following My project structure looks like below. Hi2 is the project settings.py looks like below. I did all the Important settings related to Static Files # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFIELS_DIRS=[ STATIC_DIR, ] Finally imported CSS into my index.html in the below way. In the 3rd line Used {% load static %} and in 14th and 17th lines used "{% static "file location" %}". But it's not all reflecting when viewd Index.html page. 1) <!DOCTYPE html> 2) <html lang="en"> 3) {% load static %} 4) <head> 5) 6) <meta charset="utf-8"> 7) <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 8) <meta name="description" content=""> 9) <meta name="author" content=""> 10) 11) <title>Home</title> 12) 13) <!-- Bootstrap core CSS --> 14) <link href="{% static "myapp/vendor/bootstrap/css/bootstrap.min.css" %}" rel="stylesheet"> 15) 16) <!-- Custom styles for this template --> 17) <link href="{% static "myapp/css/simple-sidebar.css" %}" rel="stylesheet"> 18) 19) </head> Any help is highly appreciated Thanks … -
Why django model save function does not respond?
I am trying to create a blog post model and i added a schedule filed on Django model that i can schedule my post by date and time if schedule time == now then post should be verified and display to dashboard so for this i used def save function but save function does not respond when i tried to schedule a blog post from admin panel it did not change verified = True here is code what i did so far. class Blog(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post") title = models.CharField(_("Title of blog post"), max_length=250, null=True, blank=True) header = models.CharField( _("Blog title eg. TIPS, "), max_length=250, null=True, blank=True) slug = models.SlugField(_("Slug of the title"), max_length=250, unique_for_date='publish', null=True, blank=True) photo = models.ImageField(_("Blog post main image"), default="img.png", null=True, blank=True, upload_to='users/avatar') read_time = models.TimeField( _("Blog post read time"), null=True, blank=True) category = models.ForeignKey(Category, verbose_name=_( "Blog category list"), on_delete=models.CASCADE, null=True, blank=True) publish = models.DateField() tags = TaggableManager(blank=True) description = HTMLField() views = models.IntegerField(default="0") # <- here verified = models.BooleanField( _("Approved post before push on production"), default=False) schedule = models.DateTimeField( _("Schedule post by date and time"), auto_now=False, auto_now_add=False, null=True, blank=True) class Meta: verbose_name = _('blog') verbose_name_plural = _('blogs') def __str__(self): return self.title def … -
While building wheel for pdftotext, command 'gcc' failed with exit status 1
I am using Python 3.7.0, Django 3.0.4, and trying to host in Heroku. I am using windows OS and the most solution I found is on Linux. Every time I tried to push into the master of Heroku, it occurs the following error. Could anyone please help me out? ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-vu13x6kn/pdftotext/setup.py'"'"'; __file__='"'"'/tmp/pip-install-vu13x6kn/pdftotext/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-quoxq88r remote: cwd: /tmp/pip-install-vu13x6kn/pdftotext/ remote: Complete output (14 lines): remote: /app/.heroku/python/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' remote: warnings.warn(msg) remote: running bdist_wheel remote: running build remote: running build_ext remote: building 'pdftotext' extension remote: creating build remote: creating build/temp.linux-x86_64-3.6 remote: gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPOPPLER_CPP_AT_LEAST_0_30_0=0 -I/app/.heroku/python/include/python3.6m -c pdftotext.cpp -o build/temp.linux-x86_64-3.6/pdftotext.o -Wall remote: pdftotext.cpp:3:10: fatal error: poppler/cpp/poppler-document.h: No such file or directory remote: #include <poppler/cpp/poppler-document.h> remote: ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ remote: compilation terminated. remote: error: command 'gcc' failed with exit status 1 remote: ---------------------------------------- remote: ERROR: Failed building wheel for pdftotext -
python open function path
Could you please help me to understand how to set the path from where the file needs to be saved. def service_area_by_region_top_category_count(self, services_in_service_area_by_region, region_name, limit): print('#### ' + region_name + ':') with open("how to give the path here?/location.txt", "a") as file_prime: file_prime.write(str('#### ' + region_name + ':')+ '\n') region_queryset = services_in_service_area_by_region[region_name] with open("how to give the path here?/location.txt", "a") as file_prime: for category in Category.objects.all().annotate( service_count=Count(Case( When(services__in=region_queryset, then=1), output_field=IntegerField(), )) ).order_by('-service_count')[:limit]: print(" - " + category.name + ": " + str(category.service_count)) file_prime.write(str(" - " + category.name + ": " + str(category.service_count))+ '\n') Thank you for the help. -
How to implement ldap authentication(without admin credentials) in django
My setup: Django-3.0, Python-3.8, django_auth_ldap I have LDAP Server (Active Directory Server) in my organization. I am building a Django Application which serves some operations for all the users. I know Django has built-in User Authentication mechanism, But it authenticates if users are present in User Model Database. But my requirement is. All user entries are in LDAP Server(Active Directory). Using proper user credentials LDAP server authenticates me. I Created a Login Page in Django 'accounts' app, 1. whenever I enter username and password from Login Page, it should Authenticate using My Organization LDAP Server. 2. After Login I have to hold the session for the logged in user for 5 active minutes. (Django auth session) I saw django_auth_ldap package gives some insight for my purpose. I have these contents in settings.py. import ldap ##Ldap settings AUTH_LDAP_SERVER_URI = "ldap://myldapserver.com" AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS : 0} AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s, OU=USERS,dc=myldapserver, dc=com" AUTH_LDAP_START_TLS = True #Register authentication backend AUTHENTICATION_BACKENDS = [ "django_auth_ldap.backend.LDAPBackend", ] Calling authenticate in views.py. from django_auth_ldap.backend import LDAPBackend def accounts_login(request): username = "" password = "" if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') auth = LDAPBackend() user = auth.authenticate(request, username=username, password=password) if user is not None: login(request, … -
How to parse this Postgresql query into Django
I have this Postgresql query: select a.code from accounts a where a.code like '0077-7575%' or '0077-7575' like a.code||'%' At django I am trying to do this: q = Accounts.objects.filter(Q(code__startswith='0077-7575') | Q('0077-7575'__startswith=code)) But, of course, it doesn't work... How can I solve this? -
Checkout Not Working in Django, Even With Test Card Details
I've been following along with a tutorial for my project and I've created a checkout page, with the relevant views, models etc being created as well. The issue I'm currently having is that my website won't accept the test card details I'm putting in and it keeps throwing the error "We were unable to take a payment with that card!". Below are the test card details I'm using. Below is the checkout view that is being used. The error message I'm getting is the error message shown in the second from bottom 'else' statement. def checkout(request): if request.method=="POST": order_form = OrderForm(request.POST) payment_form = MakePaymentForm(request.POST) if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() order.save() cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price order_line_item = OrderLineItem( order = order, product = product, quantity = quantity ) order_line_item.save() try: customer = stripe.Charge.create( amount = int(total * 100), currency = "GBP", description = request.user.email, card = payment_form.cleaned_data['stripe_id'], ) except stripe.error.CardError: messages.error(request, "Your card was declined!") if customer.paid: messages.error(request, "You have successfully paid") request.session['cart'] = {} return redirect(reverse('products')) else: messages.error(request, "Unable to take payment") else: print(payment_form.errors) messages.error(request, "We were unable … -
How to get the total count of followers filter by user in Django?
I have a ManyToManyfield in Django and im trying to get the total count of users that are following a specific user. Anyone know how to make this? I've tried this code 'focount' context in views.py but is not working. Thanks! views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name='posts' paginate_by = 15 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username')) context['focount'] = Friend.objects.filter(current_user=self.request.user).count() return context Models.py class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner', null=True) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create(current_user=current_user) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create(current_user=current_user) friend.users.remove(new_friend) user_posts.html <div class="followers-col-st"><span class="follower-color">{{ focount }}&nbsp;</span> -
Django running migrations after cloning project is failing
I just cloned my project from a git repository. After installing all dependencies and a virtual environment I proceeded to set up the database by running migrations as follow: python3.6 manage.py makemigrations python3.6 manage.py makemigrations api python3.6 manage.py migrate but the last command is failing: python3.6 manage.py migrate Operations to perform: Apply all migrations: account, admin, api, auth, authtoken, contenttypes, sessions, sites, socialaccount Running migrations: Applying account.0001_initial...Traceback (most recent call last): File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 394, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: users_user The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line …