Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Template rendering performance (I think) how to check if enabling LocMemCache is working?
Ive noticed that randomly some pages take from 2 to 12 seconds to load, I have Debug toolbar installed and I know my queries are all efficient (i.e. no duplicates) and toolbar shows they are all running in milliseconds. One particular page ive decide to focus on is my search page which uses haystack and elastic search. I have a function which queries haystack and I have a timer that runs at the beginning of the server side function and the end and then churns out the query time, this Varys from 0.01 to 0.2 seconds, either way pretty fast (example of view below). but the page can take extremely long to load randomly. ive added template timings panel to DJDT however it doesnt support Django 2.x, but it does still show a timings result which was varying from 2000ms to 10000ms+ Which lead me to research the template rendering where I come across this post (django: guidelines for speeding up template rendering performance). Whilst im not au fait with a lot of the things that are mentioned, I did look into caching. I have added the below to my settings.py file: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': … -
display local images in html template in Django
i want to display images in hmtl template using django i have images in my local : 'home/phuong/dataTestKhiHau/anh/Prob/201910/prob.R.NOV-2019.png' not in static folder in project so in my template <img src="{{ value }}"></img> (value is my images location) but it's not display -
I am trying to get the index value of the list item selected
search.py <div class="container"> <br> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Bank Accounts </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for items in name %} <a class="dropdown-item" href="{% url 'details' %}">{{ items }}</a> {% endfor %} </div> </div> name is a list which varies it can have 2 or 3 or n number of items so i have used a for loop to display all the items in the drop down .now what i am trying to do is get the index of the dropdown item clicked . for example i click the third item of the drop-down i want to pass index of 2 to my views.py so when it redirects to the url "details.html" the data shown on the webpage will be pulled from a list in which i want to pass the index of the item clicked in the drop-down according to the index. -
import error is shown in items.py ,when run the scrapy crawl the project
from applications.news_crawl.models import NewsDetails ImportError: No module named applications.news_crawl.models,the error is found when run scrapy from scrapy_djangoitem import DjangoItem from applications.news_crawl.models import NewsDetails class DuklrNewsCrawlItem(DjangoItem): django_model = NewsDetails -
How do I get duration of an In Memory Video in Python / Django?
So I was successfully using the following code to get the duration of a saved video in Django. def get_video_length(file_path): command = [ 'ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path ] try: output = check_output( command, stderr=STDOUT ).decode() except CalledProcessError as e: output = e.output.decode() return output But now I need to get the duration of an uploaded file before saving it. I have a serializer with a FileField and on validate method I should check the video duration. For instance: class VideoSerializer(serializers.Serializer): video = serializers.FileField(required=True, validators=[validate_media_extension, validate_video_duration]) Then on validate_video_duration I needed to call some method like get_video_length, but I need an alternative to get the duration from the video in memory. The object that I have is an instance of InMemoryUploadedFile (https://docs.djangoproject.com/en/2.2/_modules/django/core/files/uploadedfile/) -
How to share the post with Friends using django?
User - Auth User Model, Friends - Friend model, Sharing of the post data: class share(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='+') sharing = Posts.objects.all() -
Get all action names from ViewSet (drf)
Is it any possibility to get all actions names from ViewSet in DRF? I mean not only standard list, retrieve etc but custom ones too (defined by @action decorator) I've tried to use action_map but it is empty -
Get sphinx running with django: Import errors (autodoc: failed to import module)
I am running a dockerized Cookiecutter django app and I can't get sphinx to work with the project. I set it up and it does create files when I run autodoc but when I run make html it gives me so many errors: WARNING: autodoc: failed to import module 'admin' from module 'building_data'; the following exception was raised: Traceback (most recent call last): File "/Users/micromegas/miniconda3/envs/website/lib/python3.7/site-packages/sphinx/ext/autodoc/importer.py", line 32, in import_module return importlib.import_module(modname) File "/Users/micromegas/miniconda3/envs/website/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/micromegas/myprojectfolder/myproject/building_data/admin.py", line 2, in <module> from .models import Building, BuildingGroup, DemandHeat, DemandCool, TimeSeries File "/Users/micromegas/myprojectfolder/myproject/building_data/models.py", line 6, in <module> from simulation_api.models import Project File "/Users/micromegas/myprojectfolder/myproject/simulation_api/models.py", line 1, in <module> from config.settings.storage_backends import MediaStoragePrivate File "/Users/micromegas/myprojectfolder/myproject/config/settings/storage_backends.py", line 1, in <module> from storages.backends.s3boto3 import S3Boto3Storage File "/Users/micromegas/miniconda3/envs/website/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 40, in <module> class S3Boto3StorageFile(File): File "/Users/micromegas/miniconda3/envs/website/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 58, in S3Boto3StorageFile buffer_size = setting('AWS_S3_FILE_BUFFER_SIZE', 5242880) File "/Users/micromegas/miniconda3/envs/website/lib/python3.7/site-packages/storages/utils.py", line 21, in setting return getattr(settings, name, default) File "/Users/micromegas/miniconda3/envs/website/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in … -
What is the best way to volume existing database to the container?
Need to run project via docker containers. I need to mount existing database to postgres container. Have the next in my docker-compose.yml services: web: build: . env_file: .env command: bash -c "python manage.py collectstatic --no-input && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" depends_on: - redis - postgres restart: always volumes: - static:/static expose: - 8000 environment: - .env links: - postgres - redis redis: image: "redis:alpine" postgres: image: "postgres:10" env_file: - .env volumes: - POSTGRES_DATA:/var/lib/postgresql/data ports: - "5433:5432" expose: - 5433 volumes: POSTGRES_DATA: static: From my .env file POSTGRES_NAME=dbname POSTGRES_USER=dbuser POSTGRES_PASSWORD=dbpassword POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DATA=/var/lib/postgresql/10/main But inside my web container I have next logs File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: database "dbname" does not exist It means that databse mount failed. But I really can not find reason why it happens. -
SQlite DB BRowser - Create users in auth_user table by SQL - how to hash password?
maybe I am wrong doing that but I would like to create data for my Djang app tests and first, I would like to create users using sql script in DB Browser SQLite `INSERT INTO auth_user (date_joined,username,first_name,last_name,email,is_active,is_superuser,is_staff,password) VALUES (DateTime('now'),'Hamilton','Laird','Hamilton','laird.hamilton@surf.com',1,0,0,'mereva2019'); but as password is not encrypted it does not work is there a way to correctly encrypted password? what would be the good way to do that? -
Connect DJONGO rest framework with React
I am having DJANGO models with crud operations API. I want to integrate with the react application. How can I do that? Since we have API for each model and the relations individually. How can we do a workflow? Example - In registration, we have two forms that store in two models and a relation model in DJANGO. We do sync calls in react will make react overweight and more logics in react like rollback etc. Does anyone have a solution to this flow? post(users).then( post(school).then( post(userSchool).then('success') )) // any network issues between in client :( -
How to add an item to cart in ListView
I have a view function to add an item to cart on the item detail page, it works perfectly. def add_to_cart(request, pk): item = get_object_or_404(Item, pk=pk) # follows more code ofc # urls path('add-to-cart/<pk>/', add_to_cart, name='add-to-cart') // template tag to call the function in item detail page <a class="button primary-btn" href="{{ object.get_add_to_cart_url }}">Add to Cart</a> Now I want to make a button to add an item to cart directly from the page listing all items, but since the add_to_cart function requires pk as an args I have to pass it for the function to work properly, so I tried: {% for item in object_list %} // ... extra code... <li><button><a href="{% url 'core:add-to-cart' item.pk %}"><i class="ti-shopping-cart"></i></a></button></li> But It doesn't work. What am I missing? Any help or hint is really appreciated thanks. I'll post any other piece of code you may want to see. -
I've got this error in django : Could not resolve URL for hyperlinked relationship using view name "users-detail"
everybody. I created an app named as credentials. these are my code files: credentials models.py: from django.db import models class Users(models.Model): username = models.CharField(max_length=20, blank=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('username',) class UsersDetails(models.Model): user = models.ForeignKey( Users, related_name='id_user_details', on_delete=models.DO_NOTHING, ) user_title = models.CharField(max_length=30, blank=True) user_first_name = models.CharField(max_length=25, blank=True) user_last_name = models.CharField(max_length=40, blank=True) user_birthdate = models.DateField(blank=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) details_creator = models.ForeignKey( Users, related_name='dtlcreator_user_details', on_delete=models.DO_NOTHING, # default=1 ) class Meta: ordering = ('user_id',) class UsersPasswords(models.Model): user = models.ForeignKey( Users, related_name='id_user_password', on_delete=models.DO_NOTHING) salt = models.CharField(max_length=200, blank=True) pwdhash = models.CharField(max_length=200, blank=True) inserted_timestamp = models.DateTimeField(auto_now_add=True) pwd_creator = models.ForeignKey( Users, related_name='pwdcreator_user_details', on_delete=models.DO_NOTHING) class Meta: ordering = ('user_id',) credentials serializers.py: from rest_framework import serializers from credentials.models import Users from credentials.models import UsersDetails from credentials.models import UsersPasswords class UsersSerializer(serializers.HyperlinkedModelSerializer): details = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='user-details' ) passwords = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='user-passwords' ) class Meta: model = Users fields = ( 'url', 'pk', 'username', 'inserted_timestamp', 'details', 'passwords', ) class UsersDetailsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='user-list') creator = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='user-list') class Meta: model = UsersDetails fields = ( 'url', 'pk', 'user', 'user_title', 'user_first_name', 'user_last_name', 'user_birthdate', 'inserted_timestamp', 'creator' ) class UsersPasswordsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='user-list') creator = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='user-list') class … -
How to autostart PyCharm's Django Server in Debug mode?
I'm trying to star Django Server automatically, when IDE starts. Simple Run command is works fine, but when I try to copy debugger arguments to python interpreter options field - I get the following error: Could not connect to 127.0.0.1: 36771 Traceback (most recent call last): File "/opt/pycharm-2019.2.3/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 449, in start_client s.connect((host, port)) ConnectionRefusedError: [Errno 111] Connection refused Traceback (most recent call last): File "/opt/pycharm-2019.2.3/helpers/pydev/pydevd.py", line 2073, in <module> main() File "/opt/pycharm-2019.2.3/helpers/pydev/pydevd.py", line 1958, in main dispatcher.connect(host, port) File "/opt/pycharm-2019.2.3/helpers/pydev/pydevd.py", line 1775, in connect self.client = start_client(self.host, self.port) File "/opt/pycharm-2019.2.3/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 449, in start_client s.connect((host, port)) ConnectionRefusedError: [Errno 111] Connection refused Process finished with exit code 1 Simple run command: /home/ez/project/venv/bin/python3.7 /home/ez/project/manage.py runserver 8000 Debug command: /home/ez/project/venv/bin/python3.7 /opt/pycharm-2019.2.3/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 36771 --file /home/ez/project/manage.py runserver 8000 What I am doing wroing? How to run debug manually? -
Proper way to upload an image and metadata to aws using django
I am trying to upload images to aws using django. At first I wanted to use s3. It is fairly simple. However images contain metadata, like title and tags. And I want to be able to search using these things. Is s3 suitable for this kind of job. Another recommendation was upload images to s3 and url and metadata to another db. But I don't know how to do that or is it even possible Note: I want to use django admin. -
how to run a mysql service with local image
I want to wget a dump file hosted on another service. So I created a Dockerfile with the command to run wget the dump file. But somehow my mysql server doesnot run and gives an error Here is my Dockerfile: FROM python:2.7-alpine RUN apk update && apk add bash curl && apk add mysql-server COPY ./compose/local/db/dump_sql.sh /dump_sql.sh COPY ./compose/local/db/getmeashop.sql /getmeashop.sql RUN sed -i 's/\r//' /dump_sql.sh RUN chmod +x /dump_sql.sh CMD mysql start \ Here is my dump_sql.sh file: #!/bin/sh echo "stating the wget" wget https://gmas-core-media.s3-ap-southeast-1.amazonaws.com/getmeashop.sql -O ./getmeashop.sql echo "ending the wget" cp ./getmeashop.sql /docker-entrypoint-initdb.d/getmeashop.sql echo "Running it" mysql start And here is the Service: db: image: mysql:5.7.10 environment: MYSQL_DATABASE: gmas_matrix MYSQL_ROOT_PASSWORD: root ports: - '3306:3306' command: /dump_sql.sh build: context: ./ dockerfile: ./compose/local/db/Dockerfile volumes: - my-db:/var/lib/mysql - ./compose/local/db/getmeashop.sql:/docker-entrypoint-initdb.d/getmeashop.sql Thanks in advance. -
django restframework check permission before function
Im checking permission before the POST method in an APIView like this: class ResultDataApi(APIView): ... authentication_classes = (JWTAuthentication,) permission_classes = ([permissions.IsAuthenticated, CheckReadPermission]) def post(self, request): Now I want to check another permission when executing a function inside of the post methode, something like this: in views.py execute_command_function(...) decorating the function @permission_classes(CheckUpdatePermission, ) def execute_command_function(...) also tried it as in the first step, but not working: permission_classes = ([permissions.IsAuthenticated, CheckReadPermission]) cmd_output_data[cmd_key] = execute_command_function(...) -
how do I print the classes and fields from within a models.py?
In the terminal python manage.py shell I am trying to import django.db.models I want to see what classes and fields are within it I also want to determine which directory location models.py is located in How can I do this? -
Djano query object.values() list as parameter
I currently have a query that looks similar to this: Account.objects.filter(id__in=id_list).values("id", "first_name", "last_name") Is there a way to pass a list into the values? (I've tried this, that's why I'm asking) Sort of like: value_list = ["id", "first_name", "last_name"] Account.objects.filter(id__in=id_list).values(value_list) -
Hosted django app on heroku, how would I go about creating images in models
Hi so I have an app where for every model object I create an image and so far I've made it so you manually create the images for multiple objects through an admin action. When I've run it locally it saves to the media folder but now I've deployed it to Heroku, so right now they're created but disappear into the ether. I want the user to be able to print the images so where do they go? -
I want to insert the data of the students in the database.please elaborate to me and how to show the data in the table specially date-of-birth
I have seven fields for entering the data in the database , e.g(Student id,first name, last name,major,phone, gpa and date-of-birth) But the criteria is that i have to create the Date class containing Day,Month,Year as fields and i'm struggling to do this. I also want know to create the different fields in the models file and how the data will entered from the form. How is this work in the views file. Below the html code for fetching data from the user and i use the input fields in the type of text(type="text") But for date i used the(type="Date") The views file,in this file i just entered the data in the simplest manner cause i don't know how to split the day, month and year for entering the data in the string. The Models File Code,in this file i created the two table classes for entering the data. the first class is Date class which will store the data separately for the day, month and year The another table class is Student, firstly which will use the date class with the forgeinkey to store the data in the table along with the other fields. HTML CODE:- <div class="custom-file"> <input type="Date" … -
How to make django-crispy-forms input field to take the entire available width?
I can't manage to make the input widget in the following form to take all the available width in the page. Any ideas? I am using Django 2.2.5, django-crispy-forms 1.7.2 & Bootstrap 4. Since I am already asking, is it possible to make the input field resizable by the user? In the form, I also tried: Field("name", css_class="w-100") forms.py class ProjectsForm(forms.ModelForm): """ Class to create/edit a new profile. """ name = forms.CharField(max_length = 300, required=True) class Meta: model = Projects fields = ['name',] #--- def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field("name", style="width: 1000px;") ) #--- #--- template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New project</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Create</button> </div> </form> </div> {% endblock content %} -
Redirect to the filtered list in Django Admin
Suppose, I have a modelA and modelB, that has ForeignKey relationship with modelA On the any modelA object page in Django Admin, I would like to have a link to the filtered list of modelB instances that have the relationship with that modelA instance. For example: From /admin/my_app/modelA/1/change/ I would like to access /admin/my_app/modelB/?modelA__id__exact=1 -
What`s the problem of "Instance of 'DateTimeField' has no 'year' member" in python django2?
I am learning web develpoment by django. I am coding according to the book django2byexample. I found a problem that the book hasn't include My VScCode printInstance of 'DateTimeField' has no 'year' member Could someone tell me what` the problem?Thank you. Here is the code: def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) -
How we can use Django CRM?
Please someone help me to know what is use of Django CRM? How we can use it.I know this i can search in Google but i want know it from some real time professionals. Can someone please aware me about Github CRM project?.