Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx + Django: ModuleNotFoundError: No module named 'app'
I am trying to run my Django application with Nginx and Gunicorn in Docker In docker compose logs i have the following error: (full log: https://pastebin.com/EXd3Bsii) File "/usr/local/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app django_1 | mod = importlib.import_module(module) django_1 | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module django_1 | return _bootstrap._gcd_import(name[level:], package, level) django_1 | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import ... django_1 | File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked django_1 | ModuleNotFoundError: No module named 'app' How can I solve the problem? Should I specify wsgi configuration? My code wsgi,py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'potok.settings') application = get_wsgi_application() nginx-conf.conf upstream app { server django:8000; } server { listen:80; server_name: localhost; location / { proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect_off; } location /staticfiles/ { alias /var/www/html/staticfiles/; } } docker-compose.yml version: '3.9' services: django: build: . # path to Dockerfile command: sh -c "gunicorn --bind 0.0.0.0:8000 app.wsgi" volumes: - .:/project - static_data:/project/static expose: - 8000 environment: - DATABASE_URL=postgres://postgres:XXXXXXXXX@localhost:5432/lk_potok_2" - DEBUG=1 ... nginx: image: nginx:1.19.8-alpine depends_on: - django ports: - "80:80" volumes: - static_data:/var/www/html/static - ./nginx-conf.d:/etc/nginx/conf.d volumes: pg_data: static_data: -
Twitter Follwers post to database
Im trying to capture daily and record the number of Twitter followers a handle has and add the date and number to the data base. I have a simple function that gets the numbers but I'm not sure how I update the database def get_twitter_followers(request,twitter_handle): today = now().date() consumer_key = "#######################" consumer_secret = "###########################" access_token = "#####################" access_token_secret = "####################" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) user = api.get_user(screen_name=twitter_handle) count = (user.followers_count) return count,today class SocialMedia(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) capture_date = models.DateTimeField(blank=True, null=True) twitter_count = models.IntegerField() def __str__(self): return str(self.project_name) I want to set this up to run on a schedule, but for now, I just want to capture and POST to the database may be just using a button on my app. I'm not sure how to save() to the model? Thanks -
React connection to Django
There is a built React project with the following file structure: structure How can I include it to my django app? -
select all columns from a table where the combination of 3 fields is unique
i'm trying to select all entries in a table with multiple columns where the combination of 3 specific columns are distinct using django ORM with MySql backend. id first_name last_name n_children some_stuff other_stuff date 1 john silver 2 any any 2021-01-01 2 john silver 3 any any 2021-01-01 3 john white 2 some some 2021-01-01 4 john silver 2 some some 2021-01-02 I need to select all rows where the combination of "first_name", "last_name" and "n_children" is unique, prioritizing the most recent entries. In this example, the result should be rows with id [2,3,4]. what i've tried qs = Table.objects.all().order_by('-date').annotate( unique_value=Concat('first_name','last_name','n_children', output_field=TextField()) ).distinct('unique_value') But this does not work because i'm using mysql and i get this error django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database backend Also tried Table.objects.all().order_by('-date').values( 'first_name','last_name','n_children' ).distinct() But this returns only the unique fields, and i need all of them. -
Disable button until on-demand Celery task runs
Continuation question to my previous problem. I have a button in the Django template that triggers a Celery task. I want to disable the button after the button is clicked. It is a resource-heavy task, and definitely clicking multiple times must be prevented. My initial idea was to have two buttons, and conditionally show one or the other, depending on if the task is running or not. I would somehow (not figured out how yet), using AsyncResult(str(task)).status = "SUCCESS" pass the resulting boolean to the template. Then show the disabled button if False, otherwise the original clickable button. template.html {% if importEnabled == True %} <a class="btn btn-primary btn--full" id="id_import_data_btn" href=" {% url "import_data" company.company_id %}">Import Data</a> {% else %} <a class="btn btn-primary btn--full" disabled="True">Importing Data (button disabled)...</a> views.py def trigger_import_data(request, company_id): task = import_data_for_company.delay(company_id) importEnabled = AsyncResult(str(task)).status == "SUCCESS" return HttpResponseRedirect(reverse_lazy("edit-company-profile")) My second idea was to use JS in the template and disable the button after clicking it. Here I could make the button not function (but not disabled) after click, but it also didn't trigger the celery task, which is bad. Then I tried setting the boolean to session storage, so I could determine the button showing in … -
I can't install psycopg2 in my virtual environment
I bought a book Django for professionals and I am currently on 2. chapter PostgreSQL. I have django installed in my virtual environment and my project is in docker as you can see from code below. When I try to install psycopg I get an error: Warning: Python 3.10 was not found on your system... Neither 'pyenv' nor 'asdf' could be found to install Python. You can specify specific versions of Python with: $ pipenv --python path/to/python. I run command: docker-compose exec web pipenv install psycopg2-binary==2.8.5 My Dockerfile is ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ My docker-compose.yml file is version: "3.9" services: web: build: . command: python3 /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 environment: - "POSTGRES_HOST_AUTH_METHOD=trust" -
Django-admin command error Unable to start project
I am trying to start a project in a virtual environment using the django-admin command. The error I get for django-admin startproject [name] [path] is Traceback (most recent call last): File "C:\Program Files\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Program Files\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\%CurrentUser%\Documents\Dev\Django\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\commands\check.py", line 63, in handle self.check( File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\checks\templates.py", line 29, in check_string_if_invalid_is_string for conf in settings.TEMPLATES: File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\conf\__init__.py", line 84, in __getattr__ self._setup(name) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\conf\__init__.py", line 65, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This just started after I had deleted my old project to start again using a comprehensive tutorial. Thanks. -
Django update other user account fields through Model Form (when logged in as admin)
I am building a django project that allows users to singup and then post projects. Apps include a 'users' app and a 'projects' app. I am using @signals so that 'users' create/edit a Profile and the @signals ensure that the underlying django User model is always in synch with the Profile model contained in the 'users' app. I have one Profile for the superuser and this is set up to not only access its own 'user profile' and 'project posts' that it may post, but is also set up to review the projects posted by other users before they can be seen in the public feed of 'project posts'. In the Project model (within the projects app models.py) i have a field called 'is_approved' with a default value of false and 'project posts' are only visible in the public feed after the superadmin has used its template view of a model form to update 'is_approved' from False to True. Each 'project post' includes a Profile field as a foreign key (one-to-many) The above is working very well - as the superuser can be the sessionid authenticated user and yet update the 'project posts' that belong to a different profile. My … -
AttributeError: 'set' object has no attribute 'items' Error (Djngo Rest Api)
The following code has been written but still, the following error will happen: VIEWS PAGE from django.http.response import HttpResponse from django.shortcuts import render from rest_framework import serializers,status from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import AccountSerializer import requests, json # Create your views here. def home(request): return render(request,'register.html') def register(request): return render(request,'register.html') def login(request): return render(request,'login.html') @api_view(['POST']) def registeruser(request): if request.method == "POST": SaveSerialize = AccountSerializer(data=request.data) if SaveSerialize.is_valid(): SaveSerialize.save() return Response(SaveSerialize.data,status=status.HTTP_201_CREATED) return Response(SaveSerialize.data,status=status.HTTP_404_BAD_REQUEST) def insertemp(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') gender = request.POST.get('gender') pass1 = request.POST.get('password1') pass2 = request.POST.get('password2') if pass1 == pass2: password = pass1 address1 = request.POST.get('address1') address2 = request.POST.get('address2') city = request.POST.get('city') branch = request.POST.get('branch') address = f'{address1} {address2} {city} {branch}' data = { 'name':name, 'email':email, 'gender':gender, 'password':password, 'address':address, } headers={'Content-Type: application/json'} read = requests.post('http://127.0.0.1:8000/registeruser', json=data, headers=headers) return render(request,'register.html') else: return render(request,'register.html') This is the serializer page: SERIALIZER PAGE: from rest_framework import serializers from .models import Account class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = "__all__" MODELS PAGE: from django.db import models from django.db.models.base import Model # Create your models here. class Account(models.Model): name=models.CharField(max_length=500) email=models.EmailField(max_length=254) gender=models.CharField(max_length=20) password=models.CharField(max_length=100) address=models.TextField() def __str__(self): return self.name URLS PAGE: from django.contrib import admin … -
Unable to migrate models django
unable to migrate all models or a single app model because every time I'm getting the error which is attached below, I don't know how to overcome it. error: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... the error comes after I did: python manage.py migrate admin zero python manage.py migrate auth zero python manage.py migrate contenttypes zero python manage.py migrate sessions zero -
Unable to login in django admin panel by creating custom user model
I created custom user model and you can login using Email Id. This is for django rest framework. At admin panel it shows the error like Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. but I am entering correct email id and password. is_active and is_staff is set to True. I have created superuser by command: python manage.py createsuperuser is_active,is_staff is True as I have checked in SQLite viewer it is 1 in staff and active field. models.py from django.db import models from django.contrib.auth.models import BaseUserManager,AbstractBaseUser,PermissionsMixin from rest_framework_simplejwt.tokens import RefreshToken class UserManager(BaseUserManager): def create_user(self,email,mobile,password=None): if mobile is None: raise TypeError("Please is enter mobile number") if email is None: raise TypeError("Please is enter Email Address") user = self.model(mobile=mobile,email=self.normalize_email(email)) user.set_password(password) user.is_active = True user.save() return user # superuser or admin def create_superuser(self,mobile,email,password=None): if password is None: raise TypeError("Password should not be none") # how user should be created user = self.create_user(mobile,email,password) user.is_superuser = True user.is_admin = True user.is_active = True user.is_staff = True user.save() return user class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(unique=True,db_index=True) mobile = models.CharField(max_length=10,unique=True,db_index=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' … -
Django Rest Framework: After adding related field with serializer I get Integrity error
I had the following serializer. Django Rest Framework allows me to create, update, delete and get info just with this code. Of course I'm adding the serializer to the viewset but the problem is not there: class MeasurmentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Measurment fields = ('id', 'user_statistic', 'value', 'date_created') I needed to add the detailed info for the field "user_statistic" whenever I GET the data, not just the URL so I added the code in second line and it worked, I got the extra info I needed: class MeasurmentSerializer(serializers.HyperlinkedModelSerializer): user_statistic = UserStatisticSerializer(read_only=True) # New Code Added class Meta: model = Measurment fields = ('id', 'user_statistic', 'value', 'date_created') However the when I POST to the API to create new info into the database it shows the following error: NotNullViolation: null value in column "statistic_id" of relation "cms_userstatistic" violates not-null constraint DETAIL: Failing row contains (55, 6, 0, f, f, null, 2022-01-05, 2022-01-05, null, 67). It seems that serializing a related field prevents DRF to get the related field info whenever it tries to create a new object. How can I add the detailed info for that specific related field without breaking the POST request? I wonder if there is another way … -
Django filter with many to many fields aggregate data
In my frontend, there is an option for the filter, in every filter request, it should show how many items in a particular category. for example, you can check this site, https://www.navingocareer.com/vacatures they show how many items for per category in each filter request, i am going to implement similar feature in my app At first see my codes: this is my models.py class IndustryType(models.Model): name = models.CharField(max_length=200) class Tags(models.Model): name = models.CharField(max_length=200) class Books(models.Model): name = models.CharField(max_length=200) industry = models.ManyToManyField( IndustryType, blank=True, ) tags = models.ManyToManyField( Tags, blank=True, ) and this is my views.py file import django_filters class BookFilterSet(django_filters.FilterSet): industry = django_filters.ModelMultipleChoiceFilter( field_name='industry', queryset=IndustryType.objects.all(), ) tags = django_filters.ModelMultipleChoiceFilter( field_name='tags', queryset=Tags.objects.all(), ) class Meta: model = Books fields = [ 'industry', 'tags' ] class Books(generics.ListAPIView): serializer_class = BookDetailsSerializer filter_backends = [ django_filters.rest_framework.DjangoFilterBackend, ] filter_class = BookFilterSet queryset = Books.objects.all() Currently code is working great based on my expection, now i am trying to implement item count in every request based on it's current query params similar to the given website. Does anyone have idea how i can do it? Like i want to show many items in for per industry with current params, how many items for for tags with … -
Store responses from server per model instance Django
I have a Django server, with an engine backend communicating with the Django backend through GRPC. The Django server has the database and stores users and the users' text documents. When writing in each of these documents the text is sent to a backend engine running NLP models. The backend returns suggestions based on the text and sends them back to the Django backend, which sends them to the client. However the suggestions returned do not belong to any document and are in this case global. This means that they pop up in all documents for all users. I could add a field to the document model in django with these, however since the suggestions are very temporary (They are meant to be fixed) I was wondering if there was any other way to approach this more client sided. The architecture as a whole also feels very clumsy with the Django database in between the client and the actual machine learning engine, however it would be a lot of code to change all of this, do you guys have any suggestions? -
Chunking a django-import-export
I am reading this article about chunking a large database operation. I am also using django-import-export and django-import-export-celery in my admin site and I would like to implement chunking into them. The problem I have is django-import-export already handles the file import, as well as the whole process of importing, in the background. I tried using django-import-export's bulk imports, but one of the caveats is: Bulk operations do not work with many-to-many relationships. so chunking is what we thought was the alternative. Is it possible to perform chunking inside the django-import-export? -
ERROR (EXTERNAL IP): Internal Server Error: /login/
My project works well in development but when in production throws an error. I suspect it is the django cacheops settings that have been applied... Here's the traceback Traceback (most recent call last): File "/workspace/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/workspace/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/workspace/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/workspace/.heroku/python/lib/python3.9/site-packages/sentry_sdk/integrations/django/templates.py", line 73, in rendered_content return real_rendered_content.fget(self) File "/workspace/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/workspace/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/workspace/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 168, in render with context.bind_template(self): File "/workspace/.heroku/python/lib/python3.9/contextlib.py", line 117, in __enter__ return next(self.gen) File "/workspace/.heroku/python/lib/python3.9/site-packages/debug_toolbar/panels/templates/panel.py", line 48, in _request_context_bind_template updates.update(context) DEBUG_TOOLBAR_CONFIG = {'SHOW_TOOLBAR_CALLBACK': 'library.settings.show_toolbar', 'SHOW_TEMPLATE_CONTEXT': True, 'ENABLE_STACKTRACES': True, } CACHEOPS_DEGRADE_ON_FAILURE=True CACHEOPS_ENABLED = True CACHEOPS_REDIS = { 'host': 'localhost', 'port': 6379, #'db': 1, } CACHEOPS_DEFAULTS = {'timeout': 60*60} CACHEOPS = {'libman.*': {'ops':'all'},} CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } SELECT2_CACHE_BACKEND = 'select2' INTERNAL_IPS = [ # ... "127.0.0.1", # ... ] The reason I say it is cacheops is because when I hash this it works CACHEOPS_DEGRADE_ON_FAILURE=True Please help whoever can... -
How to solve "object of type 'Course' has no len()" error that I am getting after using paginator in a view function?
This is my model. I have a many to one relationship. class Course(models.Model): course_name = models.CharField(max_length=100) class Coursegk(models.Model): question = models.CharField(max_length=1000) option_one = models.CharField(max_length=100) option_two = models.CharField(max_length=100) option_three = models.CharField(max_length=100) option_four = models.CharField(max_length=100) answer = models.CharField(max_length=100) courses = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="display") This is my views.py page def showcourses(request): details = Course.objects.all() paginator = Paginator(details, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'index.html', {'data':page_obj}) def displaymcqpage(request, courses_id): displaymcq = Course.objects.get(id=courses_id) paginator = Paginator(displaymcq, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'coursegk.html', {'display':page_obj}) Now paginator is working fine for the index.html page. But when I go to coursegk.html page from index.html page I am getting "object of type 'Course' has no len()" error. How to use paginator for the displaymcqpage function? -
Django create post
I am trying to create a new post to a forum, and it does work, i am also printing if the form is valid, but when i go to check after the post is not posted. In the admin page, the post is there, approved, but missing the tags and category fields. They was added when the post was created, if not i get an error. But I have to manually add them in the admin page to get the post posted to the forum. Here is my Post in models class Post(models.Model): title = models.CharField(max_length=400) slug = models.SlugField(max_length=400, unique=True, blank=True) user = models.ForeignKey(Author, on_delete=models.CASCADE) content = HTMLField() categories = models.ManyToManyField(Category) date = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=True) tags = TaggableManager() comments = models.ManyToManyField(Comment, blank=True) # closed = models.BooleanField(default=False) # state = models.CharField(max_length=40, default="zero") def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title Here is my views.py @login_required def create_post(request): context = {} form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n form is valid") author = Author.objects.get(user=request.user) new_post = form.save(commit=False) new_post.user = author new_post.save() return redirect('forums') context.update({ 'form': form, 'title': 'Create New Post' }) return render(request, 'forums/create_post.html', context) The … -
Seperate folder for django models
I am working on Django project that will utilize different apps to fulfill certain task. Since these apps will be referring to much same data to complete these task I figure it makes since to create a separate folder with the models like this: --Project --App1 --App2 --models ---model1.py ---model2.py Right now I'm having trouble with Django recognizing the models as existing, every time I run a makemigrations Django does not detect that any changes have been made I attempted to put a __init__.py file in the /models folder but this doesn't seem to do anything. -
Django importing of module
I am just going through some Django code: from django.shortcuts import render I have few question regarding this: This render thing how do we know this needs to be imported from django.shortcuts? Can we see render it lies in this folder django.shortcuts,? Where is this located on a drive django.shortcuts ? thank you! -
Understanding AUTHENTICATION_BACKENDS
I am trying to understand how things work when one writes the following in settings.py: AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", "master_password.auth.ModelBackend" ) In particular, the documentation states: If a backend raises a PermissionDenied exception, authentication will immediately fail. Django won’t check the backends that follow. Given this, how can the second and the third backend in the above example get a chance when a user has entered an incorrect password and the first backend has denied him access? More specifically, the third backend pertains to django-master-password, which should let the user in if he used a master password even if it does not match the user's password. So, how will that backend ever get a chance? -
NoReverseMatch at /users/password_reset/
I am trying to set up my Password Reset function for my application but getting errors after i send the reset password to my email. here is the error message: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Below is my urls.py codes: ` urlpatterns = [ path('signup/', views.user_signup, name='signup'), path('login/', views.user_login, name='login'), path('logout/', views.user_logout, name='logout'), path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('user_profile/<int:id>/', views.user_profile, name='user_profile'), ]` -
Squashing migrations speeded up tests - and not just the database setup part
I have been struggling with slow tests - really slow tests. I thought that was probably due to inefficient data setup within my tests. I did some 'before' time measurements and then, for unrelated reasons, squashed all my migrations. Then I ran my tests again. I did not change any of the test code - only the migrations - but the tests are dramatically faster. I had expected some improvement in the database setup number reported with --timing but I had not expected much change in the speed with which the tests themselves run. Can anyone offer an explanation for this? Before Method DB setup DB teardown Running Test Total elapsed MySQL 124.2s 3.6s 794.5s 925.0s MySQL keepdb 1 123.8s 0s 742.5s 869.2s MySQL keepdb 2 4.3s 0s 742.2s 759.1s SQLite run 1 4.9s 0s 886.7s 896.3s SQLite run 2 4.3s 0s 778.1s 785.2s After squashing migration Method DB setup DB teardown Running Test Total elapsed MySQL 107.8s 6.5s 200.0s 319.5s MySQL 109.3s 6.9s 205.3s 326.4s SQLite run 1 34.3s 0s 128.2s 166.9s SQLite run 2 1.5s 0s 124.6s 130.3s -
django_filters issue with gte, lte
I am trying to filter by DateField using django_filters lib. Following the doc I encounter an issue with the "gte" and "lte" lookup_expressions (I tried both). The problem is that it only return results if the date I input in my datepicker is the exact date, which I would suspect would be the expected "iexact" or "exact" lookup_expression results. This is my simplified code, note that I have tried using only one date (removing end_date in both model and filter.py) and the result was the same so I don't believe this is a range issue Model class Replacement(models.Model): start_date = models.DateField( null=True, blank=True) end_date = models.DateField( null=True, blank=True) filter.py #not sure if this DateInput is related to the issue, just a way to attach "date" type so as to get a datepicker on template class DateInput(forms.DateInput): input_type = 'date' class ReplacementFilter(django_filters.FilterSet): start_date = DateFilter(field_name="start_date", lookup_expr='gte') end_date = DateFilter(field_name="end_date", lookup_expr='gte') class Meta: model = Replacement fields = ['start_date', 'end_date'] start_date = django_filters.DateFilter( widget=DateInput(attrs={'type': 'date'})) end_date = django_filters.DateFilter( widget=DateInput(attrs={'type': 'date'})) Views def replacement_list_page(request): replacements = Replacement.objects.all() replacement_filter = ReplacementFilter(request.GET, queryset=replacements) print(replacement_filter) return render(request, "replacements/replacementlist.html", {"replacement": replacements, 'filter': replacement_filter}) Thanks -
How i link myproject folder path to template xyz page in django to download files from buttons
How I link myproject folder path to template xyz page in Django to download files from buttons. After executing my code Django save my files in myproject folder but how do I link my template xyz page buttons to myproject folder path to download my .csv, and .aln files?