Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i find out how to get the right pk?
I'm new to programming and I'm practicing on making a poll app. But im stuck trying to get the percentage of each choice voted, like so: Models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Views.py: class IndexView(ListView): template_name = 'posts/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] class DetailView(DetailView): model = Question template_name = 'posts/detail.html' class ResultsView(DetailView): model = Question template_name = 'posts/results.html' def get_context_data(self, *args, **kwargs): context = super(ResultsView, self).get_context_data(*args, **kwargs) q = Question.objects.get(pk=self.kwargs['pk']) total = q.choice_set.aggregate(Sum('votes')) percentage = q.choice_set.get( pk=self.kwargs.get('pk')).votes/total['votes__sum'] context['total'] = total['votes__sum'] context['percentage'] = percentage return context def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'posts/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # … -
Why won't this post request submit a file in Django Tests
I have a test that looks like this: with open('/path/testing_file.txt') as fp: file = fp form = { 'data1': 'text', 'data2': 'text2', 'file': open('/path/testing_file.txt'), } response = self.client.post('/link', form, follow=True) '/link' is connected to a view which prints the POST data: print(request.POST) In my actual site I submit files with an AJAX request, and it works well. However, when attempting to execute this unit test, the file is not submitted. The print statement prints this: <QueryDict: {'data1': ['text'], 'data2': ['text2']}> I tested the output with print(request.body) as well, and the output is messy, but is clear that the file data is getting sent to the request object, as I can see the content of file in the output. However, since my code works by accessing the file through request.POST['file'] already, I don't want to modify the view code to accommodate a test. So why isn't this working, and how can I properly post a file in django tests? -
How can I get the date of the created field in the format I want?
current is this created = models.DateTimeField(auto_now=True) July 13, 2020, 8:06 a.m. and I want to change date format July 13, 2020, 8:06 a.m. => 2020년6월 13일 is this possible? if you know how to change thanks for let me know ! -
I have extended my Django model from AbstractUser, how do I query the extended model to get date_joined of the user?
I have created a model class which extends from AbstractUser to handle token authentication, how do I get date_joined property of the modal's object when querying it in django rest framework views.py? Models.py: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from .managers import CustomUserManager # Create your models here. class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() date_of_birth = models.DateField(blank=True, null=True) def __str__(self): return self.email class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) def __str__(self): return self.title @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Here is my Managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password,**extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, … -
Keep previous get parameter in url and paginate using query from elasticsearch-dsl
I want to paginate some results I got using elasticsearch-dsl(version 7.8.0), exactly like how stack overflow does with the number of questions per page on its questions list(see https://stackoverflow.com/questions. So, I expect the user to enter the number of "posts" per page he wants. documents.py: from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from polls.models import Choice @registry.register_document class ChoiceDocument(Document): class Index: name = 'choices' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } class Django: model = Choice fields = ['choice_text'] from django.utils.functional import LazyObject class SearchResults(LazyObject): def __init__(self, search_object): self._wrapped = search_object def __len__(self): return self._wrapped.count() def __getitem__(self, index): search_results = self._wrapped[index] if isinstance(index, slice): search_results = list(search_results) return search_results views.py: from django.shortcuts import render from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # search is the name of my app from search.documents import ChoiceDocument, SearchResults def search_choice(request): paginate_by = request.GET.get("paginate_by", 2) or 2 all_choices = ChoiceDocuments.search() q = request.GET.get("q", None) choices = ChoiceDocument.search().query("match", choice_text=q) if q else '' paginator = Paginator(SearchResults(choices), paginate_by) if choices else Paginator(SearchResults(all_choices), paginate_by) page_number = request.GET.get("page") try: page = paginator.page(page_number) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) page_obj = paginator.get_page(page_number) return render(request, 'search/search.html', {'choices': choices, 'page_obj': page_obj} search.html template: {% load template_tags %} … -
The loop part in the template is not being displayed
template code <html> <head> <meta charset="utf-8"> <title>Customer Page</title> </head> <body> <h1>Dear user, please check if the the email list is correct</h1> <ul> {% for customer in customer_list.objects.all %} <li>{{customer.Country}}</li> {% endfor %} </ul> </body> </html> view code from practice.models import Customer class CustomersView(ListView): template_name = "practice/customer_list.html" context_object_name = "customer_list" def get_queryset(self): return Customer.objects.all() However, in the code above, pylint underlined Customer and stated "Class 'Customer' has no 'objects' member" The browser only shows thisDear user, please check if the the email list is correct and not the loop part. I checked the QuerySet, it is not empty. In [1]: from practice.models import Customer In [2]: Customer.objects.all() Out[2]: <QuerySet [<Customer: Customer object (1)>, <Customer: Customer object (2)>]> What might be the possible causes? -
AttributeError: module 'concurrent.futures' has no attribute 'FIRST_COMPLETED'
I need your help! I make a simple blog on Django 3, I start the server and a bug of mistake : AttributeError: module 'concurrent.futures' has no attribute 'FIRST_COMPLETED' py .\manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 21, in setup set_script_prefix( File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\base.py", line 105, in set_script_prefix _prefixes.value = prefix File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\asgiref\local.py", line 113, in __setattr__ storage = self._get_storage() File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\asgiref\local.py", line 83, in _get_storage context_obj = self._get_context_id() File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\asgiref\local.py", line 51, in _get_context_id from .sync import AsyncToSync, SyncToAsync File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\asgiref\sync.py", line 1, in <module> import asyncio File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\asyncio\__init__.py", line 8, in <module> from .base_events import * File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 45, in <module> from . import staggered File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\asyncio\staggered.py", line 11, in <module> from . import tasks File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\asyncio\tasks.py", line 389, in <module> FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED AttributeError: module 'concurrent.futures' has no attribute 'FIRST_COMPLETED' -
How to test successful token claim with jwt
I'm using django rest simple jwt and I wanted to test a simple login and check the response data for the token and other custom data. So I tried with the APITestCase to create an user and then try a login with the same credentials. The results is a 401 instead a 200 with a token in response data. Here is my test case simplified: from rest_framework.test import APITestCase from django.contrib.auth import get_user_model # Create your tests here. User = get_user_model() class UserAuthTestCase(APITestCase): username = "someuser" password = "1234pass" def setUp(self): self.user = User.objects.create( username=self.username, password=self.password ) def test_successful_login_gives_200(self): response = self.client.post( '/auth/token/', { 'username': self.username, 'password': self.password }, format='json' ) self.assertEqual(response.status_code, 200) The the rest framework configuration is set to use the simplejwt authentication only. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } -
I'm getting a KeyError while trying to redirect to homepage in Django framework
From my views.py, in this class given below class Home(TemplateView): model_name = AccountInfo template_name = "BudgetApp/Home.html" def get(self, request, *args, **kwargs): user = request.session["username"] context={} context["user"] = user return render(request,self.template_name,context) Apparently, I'm getting a key error:'username'. Could you please help me out on this? This is probably the main reason why it doesn't redirect to the homepage after login for me. -
Multiple POST to One Endpoint Django
I have an endpoint /homepage in my django app that renders an HTML page. This page has several forms that each make a POST request to the /homepage endpoint. How can I decipher which POST request is being sent to the /homepage endpoint? Or, is it better to make and endpoint like /api that has sub-endpoints for each of the POST requests in the page? Thanks!! -
Djano first project search issue
This is the part of the project I'm stuck on: Search: Allow the user to type a query into the search box in the sidebar to search for an encyclopedia entry. If the query matches the name of an encyclopedia entry, the user should be redirected to that entry’s page. If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were Py, then Python should appear in the search results. Clicking on any of the entry names on the search results page should take the user to that entry’s page. my code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.wiki, name="wiki"), path("search", views.search, name="search"), ] util.py import re from django.core.files.base import ContentFile from django.core.files.storage import default_storage def list_entries(): """ Returns a list of all names of encyclopedia entries. """ _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. … -
Having to run main.py file from manage.py shell django
Running main.py file from manage.py shell django I need some help understanding this. So i have a main.py file that i want to access a file from a database table and do some wizard with numbers in the file. I access this by: import pandas as pd import matplotlib.pyplot as plt from .models import UploadedFile if UploadedFile.objects.filter(the_file='hello.csv').exists(): df = pd.read_csv(UploadedFile.objects.get(the_file='hello.csv').the_file, index_col='Date', parse_dates=True) Thats fine and makes sense. But what i dont understand is when i run this file using: python3 main.py run i get an error. the error says: File "main.py", line 3, in <module> from .models import UploadedFile ImportError: attempted relative import with no known parent package So what i have to do to get my numbers crunched from the file is to go into my python3 manage.py shell and then do from charts app import main. If i do this the code runs as soon as i do that. why is this. i dont understand this. it is a annoying because in pycharm i can't just select the main button and click run. -
Django application deployment on Heliohost.org problems
I've got an account at heliohost.org (Johnny Server) and I'm desperately trying to deploy a most simple Django application without any success. It's actually a very simple test application to check everything works fine, but it doesn't. There are several error logs: https://pastebin.com/xJBB50dF And these are the most important files' contents: .htaccess: RewriteEngine On RewriteBase / RewriteRule ^(media/.*)$ - [L] RewriteRule ^(admin_media/.*)$ - [L] RewriteRule ^(dispatch\.wsgi/.*)$ - [L] RewriteRule ^(.*)$ /InformeSO/dispatch.wsgi/$1 [QSA,PT,L] dispatch.wsgi: import os, sys # edit your username below sys.path.append("/home/alber80/public_html") from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'InformeSO.settings' application = get_wsgi_application() settings.py: """ Django settings for InformeSO project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'nf7w+ajbhz=s_#2y&72&*$v)x#1q2pccrv6t!!*@5l7tx7#$#t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_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 jinja if-elif statement breaks with ==
So on my front-end, I want to show some HTML only if the user belongs to one of 2 groups: 'admins' or 'clerks'. There are 3 groups of users: 'admins', 'clerks', and 'sellers'. Here is my front-end code: {% if user.groups.all.0 == "admins" %} <h1>Some HTML</h1> {% elif user.groups.all.0 == "clerks" %} <h1>Some HTML</h1> {% endif %} When I run this code, the HTML shows for the admins. But that of the clerks does not show. I have tried printing out the group to be sure that the spelling and the casing were the same, and they were the same. And Django does not throw an error. It only works if I rewrite the code as follows: {% if user.groups.all.0 == "admins" %} <h1>Some HTML</h1> {% elif user.groups.all.0 != "sellers" %} <h1>Some HTML</h1> {% endif %} But I feel like this is not good design. Please am I missing something? Thank you all in advance -
'str' object has no attribute 'field' using widget_tweaks
This question has been up tons of times, but are all narrowed down to exactly their specific issue. I hope that this question can clarify the problem more, so it will become more generally useful, than just narrowed to my issue. I get the error 'str' object has no attribute 'field' And I got following code template.html {% load widget_tweaks %} <form action="." method="POST"> {% render_field form.co_nip_number name="co_nip_number" class="form-control" type="number" required="" %} </form> forms.py from django import forms from .models import BusinessContact class BusinessContactForm(forms.Form): class Meta: model = BusinessContact fields = 'co_nip_number' models.py from django.db import models class BusinessContact(models.Model): co_nip_number = models.CharField(max_length=10) urls.py from django.urls import path from . import views app_name = 'dashboard' urlpatterns = [ path('new-client/', views.NewClient.as_view(), name='new-client'), ] views.py from django.views.generic import FormView from django.http import HttpResponse from .forms import BusinessContactForm class NewClient(FormView): template_name = 'dashboard/new-client.html' form_class = BusinessContactForm def form_valid(self, form): form.save() return HttpResponse('You managed') What does this error mean? How do we solve it? Thank you for your time -
Django - Docker python: can't open file 'manage.py': [Errno 2] No such file or directory
I am using Docker first time in my life and with various tutorials I got to this stage here. All steps are finishing correctly, but after last step succeeds I receive this error: Successfully built 66717d9cdec1 Successfully tagged movie_universe_app:latest Recreating movie_universe_app_1 ... done Attaching to movie_universe_app_1 app_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory movie_universe_app_1 exited with code 2 And I don't know how to fix it. Here are my files: Dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /movie_universe COPY ./movie_universe /movie_universe WORKDIR /movie_universe COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/ RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] docker-compose.yml version: "3.7" services: app: build: context: . ports: - "8888:8888" volumes: - ./movie_universe:/movie_universe command: sh -c "python manage.py runserver 0.0.0.0:8888" environment: - DEBUG=1 entrypoint.sh: #!/bin/sh set -e python manage.py collectstatic --noinput uwsgi --socket :8888 --master --enable-threads --module app.wsgi I tried to delete "volumes:" from docker-compose.yml but it is still not working. Can please someone … -
ModuleNotFoundError: : No module named 'main.apps.mainconfigdjango'; 'main.apps' is not a package
This error occurred when I tried to run "python3 manage.py makemigrations". I'm really not sure what happens but I went into mysite/mysite/settings.py and added main.apps.MainConfig to the Installed Apps list. I am a beginner to python and the django framework and i would appreciate feedback from more experienced Python and Django developers. -
bokeh hbar_stack not rendering properly when using datetimes
i'm trying to plot a hbar_stack with datetimes in x axis with no luck. i've done normal hbar plots with datetimes before with no problems so it's has to be something with the hbar_stack. Here is the code with some static data: start_date = datetime.datetime(2020, 7, 10, 10, 26, 15, 240666) end_date = datetime.datetime(2020, 7, 10, 13, 27, 33, 741238) tasks = ['task 1', 'task 2', 'task 3', 'task 4'] status = ['status_1', 'status_2', 'status_3', 'status_4'] exports = {'tasks': tasks, 'status_1': [datetime.datetime(2020, 7, 10, 13, 26, 59, 531234), datetime.datetime(2020, 7, 10, 13, 25, 16, 666837), datetime.datetime(2020, 7, 10, 10, 37, 16, 368927), datetime.datetime(2020, 7, 10, 10, 26, 15, 240666)], 'status_2': [None, datetime.datetime(2020, 7, 10, 13, 27, 33, 741238), datetime.datetime(2020, 7, 10, 11, 37, 7, 629667), datetime.datetime(2020, 7, 10, 10, 27, 5, 540767)], 'status_3': [None, None, None, datetime.datetime(2020, 7, 10, 10, 54, 17, 738024)], 'status_4': [None, None, None, datetime.datetime(2020, 7, 10, 11, 2, 15, 196620)]} p = figure(y_range=tasks, x_range=[start_date, end_date], x_axis_type='datetime', title="Tasks timeline", tools=["hover,pan,reset,save,wheel_zoom"], tooltips=None) p.xaxis.formatter = DatetimeTickFormatter( days=["%m-%d-%Y"], months=["%m-%d-%Y"], years=["%m-%d-%Y"], ) p.xaxis.major_label_orientation = radians(30) p.hbar_stack(status, y='tasks', height=0.2, color=Spectral[11][:len(status)], source=ColumnDataSource(exports)) As one can see from the data the datetimes are minutes apart but it renders with years of difference. On hovering … -
Installing Anaconda on Amazon Elastic Beanstalk to use in Django application
I have a Django application which it's deployed to Amazon Elastic Beanstalk. I have to install anaconda for installing pythonocc-core package. I have created a .config file in .ebextensions folder and add the anaconda path in my wsgi.py file such as below and I have deployed it successfully. .config file: commands: 00_download_conda: command: 'wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh' test: test ! -d /anaconda 01_install_conda: command: 'bash Anaconda3-2020.02-Linux-x86_64.sh -b -f -p /anaconda' test: test ! -d /anaconda 02_create_home: command: 'mkdir -p /home/wsgi' 03_conda_activate_installation: command: 'source ~/.bashrc' wsgi.py: sys.path.append('/anaconda/lib/python3.7/site-packages') However when I add the 04_conda_install_pythonocc command below to the continuation of this .config file, I got command failed error. 04_conda_install_pythonocc: command: 'conda install -c dlr-sc pythonocc-core=7.4.0' I ssh into the instance for checking. I saw the /anaconda folder has occured. When I checked with the conda --version command, I got the -bash: conda: command not found error. Afterwards, I thought there might be a problem with the PATH and I edited the .config file as follows and I have deployed this .config file successfully. commands: 00_download_conda: command: 'wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh' test: test ! -d /anaconda 01_install_conda: command: 'bash Anaconda3-2020.02-Linux-x86_64.sh -b -f -p /anaconda' test: test ! -d /anaconda 02_create_home: command: 'mkdir -p /home/wsgi' 03_add_path: command: 'export … -
how to connect django to another database system
I have a django website and i want to connect my django website to a set of store local database. how did i can do it and connect between my django database to store database. example : i have django website should connect to local system and get data from local system database and insert it to django database base with in the account of local system . i didn't tried anything until this time i dont't what i should to do to make it happend -
default value of model.UUIDField() doesnt seem to be called in django graphene
I am trying to build an application with django and graphene and I want to set a default value for one of the fields in my model. The mutation is really straight forward. I've passed all the required arguments as objects and the optional ones with **kwargs. Django's docs on **options for models.UUIDField() says that if None type object is sent to the model field, default value will be used. When I try to use my mutation without passing any values/ passing None as a value to the argument, graphql.error.located_error.GraphQLLocatedError: NOT NULL constraint failed: games_game.groupid error is raised. Here is a [pastebin][1]https://dpaste.org/bVhX for Tracebacks, models.py and schema.py to my project. -
Django filters - adjusting box width
With django_filters, I have my filterset, everything works fine it's just the display that I am stuck with (box width). As you can see below, I have changed the "size" attribute of some of the filter options - because the default is too wide. But the "rating" one, which is a NumberInput, doesn't work for some reason. The "size" attribute works for TextInput but not NumberInput. I want to change the size or rather the width of the NumberInput box that will be displayed in the template (see template pictures below). Can anyone help? Thanks in advance! class ReviewFilter(django_filters.FilterSet): comments = CharFilter(field_name='comments', lookup_expr='icontains', label="Comments ", widget=TextInput(attrs= {'size': 15 } )) role_title = CharFilter(field_name='role_title', lookup_expr='icontains', label="Role title ", widget=TextInput(attrs={'size': 15 } )) date_range = DateRangeFilter(field_name="date_created", label=" Posted date ") **rating = CharFilter(field_name="rating", lookup_expr='gte', label="Minimum rating ", widget=NumberInput(attrs={'size': 1 } ))** class Meta: model = Review1 fields = '__all__' exclude = {'recruiter', 'date_created', 'user'} I have this: Screenshot - Look at "Minimum rating" box width But I want this: Screenshot with filter search bar - Look at "Minimum rating" box width -
Collect Static creating a clone of my static files folder Django
I need to refresh a js file in my static files folder, however whenever I run python manage.py collectstatic, a clone of my static files folder is created in a diffrent part of the project, and the js file is still not updated. I tried changing the STATIC_ROOT variable in the settings.py file to the actual location of my static folder, but it doesn't seem to refresh because the collectstatic warning message in the console says its going to be saved in a completely different location. The Structure of my project is resume_V6-test -resume -home -static (actual location) -resume -settings.py -store -staticfiles (clone of the static folder) -users and my settings.py is # Commented out the location it was before I tried fixing the error #STATICFILES_DIRS = [ #os.path.join(BASE_DIR, "static"), #'/resume_V6-test/resume/home/static', #] #STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_ROOT = os.path.join(BASE_DIR, 'home/static') STATIC_URL = '/static/' And the error message is python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: C:\resume_V6-test\resume\staticfiles This will overwrite existing files! Are you sure you want to do this? Thanks -
Django user followers ajax issue
I have built user folloing functionality with Ajax, so a user can follow/unfollow another user. The problem is that when I click "follow" button nothing happens in the frontend. I mean text doesn't change to "Unfollow", as it should be and number of followers does not change too. If reload the page, it is fine - a follower is added. Then if I click "Unfollow" button everything works fine - Ajax request is ok, and in db a follower is deleted. I found out, that the problem happens, because when pushing the "Follow" button and send a Post request, the response code is 500 (Internal Server Error). With "Unfollow" it works fine and the request is 200. I spent a lot of time struggling with this. Any help appriciated. Bellow is the code. The user model and the model for following functionality: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.urls import reverse from django.conf import settings from .managers import CustomUserManager from team.models import Team class Contact(models.Model): user_from = models.ForeignKey('CustomUser', related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey('CustomUser', related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) … -
Django model: sum in def
How to sum fields in model? I have 2 Integer Fields and want to sum them in def, if that possible? class Blank_list(models.Model): expert = models.ForeignKey(Expert, null=True, on_delete=models.SET_NULL, related_name='blank_list') employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL, related_name='blank_list') c8_lvl_aw1 = models.IntegerField('К8: 1', choices=ANSWER_TYPES, default=0, blank=0) c8_lvl_aw1 = models.IntegerField('К8: 2', choices=ANSWER_TYPES, default=0, blank=0) def __str__(self): return "%s произвел оценку следующего сотрудника: %s" % (self.expert, self.employee) #that example what i'm expect def sum_all_fields(self): sum = c8_lvl_aw1 + c8_lvl_aw1 return sum