Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use Ckeditor in template (Html) in django?
I want to show the content that have written in the RichTextField from admin site. and i want them to show in the front end also but my code isn't working. Please help me with this. The code that i have written is not showing the content i have written in that field. help me with it..! I have setup Urls, views and other things also...! models.py from django.db import models from ckeditor.fields import RichTextField class Test(models.Model): content = RichTextField(blank=True,null=True) base.html #where I want to show that content in Homepage <!DOCTYPE html> <html> <head> <title>Base</title> </head> <body> {{test.content|safe}} </body> </html> -
django admin site customization change_list.html
Is it possible to change the viewi of change_list in Django admin site? just like on the picture this is my model.py class gradingPeriod(models.Model): Grade_Scales_Setting= models.ForeignKey(gradeScalesSetting, related_name='+', on_delete=models.CASCADE,null=True) Description = models.CharField(max_length=500,blank=True) Display_Sequence = models.IntegerField() Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) StartDate=models.DateField(null=True,blank=True) EndDate=models.DateField(null=True,blank=True) class gradingPeriodsSetting(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) NumberOfGradingPeriods = models.IntegerField(blank=True, null=True) class gradingPeriodsSummary(models.Model): Grading_Periods_Setting= models.ForeignKey(gradingPeriodsSetting, related_name='+', on_delete=models.CASCADE,null=True) Description = models.CharField(max_length=500,blank=True) Display_Sequence = models.IntegerField() Start_Grading_Period= models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,null=True) End_Grading_Period= models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,null=True) I don't know how to code it on the admin.py what I desire design in my change_list -
Migrate a model file with a deep hierarchy. django
This is my folder structure. And model is written in account.py. from .. class User(AbstractBaseUser, PermissionsMixin): ... After that, when makemigration is performed, accounts.py is not recognized. But the model of test.py was recognized. How can I recognize accounts.py? models/init.py from .commons import __init__ from . import test models/commons/init.py from . import accounts -
VS Code > Preferences > User Settings > Extensions > Python > Linting > Flake8 Args Added Item stopped working
Please don't treat this as an "asked and answered" question. I sincerely have been clobbering to try to figure out why this has stopped working, if it's a VS Code problem, or a Flake8 one, or if I'm just crazy and should find another way around this. Looking for a way to stop the Flake8 linter's "file is too long" and "not used" warnings, I found a solution listed as one of the hottest on StackFlow. I copied and pasted it exactly and it worked! Great, but while following Django Project tutorial on this code in admin.py file: from django.contrib import admin from .models import Choice, Question class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) suddenly, (the setting had been working fine for days), I got this Problem warning: line too long(80 > 79 characters) flake8(E501) (13,80) I know I may be too picky on this but it is really annoying. I've also read that I can break the line up using a backslash without breaking the continuity of the code, but I also tried that and got a message … -
Django Import Export Validation
I am trying to show the validation errors on the upload page. This is what I have : import.html <form class="importform" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> {{ form.errors }} </form> views.py def upload(request): if request.method == 'POST': chart_resource = ChartResource() dataset = Dataset() new_chart_data = request.FILES['myfile'] imported_data = dataset.load(new_chart_data.read()) result = chart_resource.import_data(dataset, dry_run=True) if not result.has_errors(): chart_resource.import_data(dataset, dry_run=False) else: print(errors) return render(request,'import.html') class WOForm(forms.ModelForm): class Meta: model = Workorder fields = ('series', 'start','end') def clean_label(self): return self.cleaned_data['series'].upper() def clean_price(self): return self.cleaned_data['start'].int() def clean_ctype(self): return self.cleaned_data['end'].lower() Also I need to translate the log to something that is understandable for normal users. Thank you for any help -
Using external database for user logins in Django
I have a Django application where, in development, I was using the default database (sqlite3, I believe) to store user login info. I had a line in my Dockerfile (which would spin up my app) that would add a user and it would automatically just be stored in the default database. Now that it's moving to production, it would be a colossal pain to add each user one at a time every time we need to update. From what I read in the documentation, it looked like I just needed to modify my settings.py from DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } to DATABASES = { 'default': { 'NAME': 'name_of_user_table', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'username', 'PASSWORD': 'password' } } I don't use the login info anywhere else in my code, and I can't find any reference to the database aside from in settings.py. Have I done enough to ensure that it can be connected to the external postgreSQL database of user logins, or is there more I need to do? This is my first Django application and I'm still learning how all of this stuff works. -
How to use django-filter on JSONField
django-filter works good on all the default fields of Model, but problem comes when we want to work it on postgres fields such as JSONField I have the following model: from django.contrib.postgres.fields import JSONField,ArrayField class MyModel(models.Model): j_field = JSONField(blank=True,null=True,default=dict) j_field has data in the following structure: [{"name":"john","work":"developer"},{"name":"cena","work":"teacher"}] How do I filter the results based on name or work from j_field using django-filter? import django_filters class MyModelFilter(django_filters.FilterSet) class Meta: model = MyModel ... ... what's next? -
Unable to access Django site from browser though there are url patterns
I'm trying to setup a Django site. I was able to add path in urls.py file. I was able to run the project using python manage.py runserver and see it running in console. But when I hit the url 127.0.0.1:8000 in the browser, it's giving me 404 error. I tried adding "*" to ALLOWED_HOSTS. But no use. When I tried adding "*.*", it's throwing error: DisallowedHost at / Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS. I'm getting the same error even after adding ["127.0.0.1", "localhost"]. I don't have any issue with firewall too. Is there anything that I'm missing that's causing this issue? -
By Django, how do I put datas which are from different html pages in one model?
I am a django baby. I am making movie reservation web site. I want to put datas which are from different html pages in one model. For example, in select_movie.html I want to get movie name(Avengers), in select_date I want to get date(2019-04-24) my client wants to see a movie, in select_time.html I want to get time(13:00) my client wants to see a movie, and in select_seat.html I want to get seat(A07) my client chooses. Like this. id / user_name / movie_name / data / time / seats 1 / koozzi / Avengers /2019-04-24 / 13:00 / A07 2 / koozzi2 / Avengers /2019-04-24 / 13:00 / A06 Could you please tell me which skill do I have to use?? I want to use "only" django and HTML! -
Monitor php changes in Django database
I have Django SQL database that is changed by php program. Is there a way to monitor this changes from Django? If not then what are the possibilities? -
How can to insert one html code from one field into another and to render it?
Hello I have model with content and additional fields. Example of content field: <div> <p>text</p> </div> Example of additional field: <p> <span> some text</span> <p> Also I render content on the page: detail_base.html {% include object.content_template with object_content=object.html_content %} entry_detail.html {{ block.super }} base_entry_detail.html {{ object_content|safe }} How can I paste code from additional field to code from content field. I need to get, for example: <div> <p>text</p> <p> <span> some text</span> <p> </div> I can to change only entry_detail.html and detail_base.html and code in the field. Thanx. -
What's the best way to get popular posts with Django?
What is here is more for discussion than code questions. I want to know how you guys do to get the popular posts. For example, once I did the following: I added a related template, and that template contained only one field, which is the post preview date, and every time a request was made, it was incremented, so I did some work to get the posts that only filter views from the last 7 days, and then I would rank the posts based on which one had the most related instances, ie, with the most views in the last week. But I don't know if this is the best way. How would you do that? -
Django, How to move from s3 to CDN?
Our media image files are stored under http://s3.ap-northeast-2.amazonaws.com/{bucket_nmae}/media/ I want to change the url to http://static.example.com/media/ and serve them through cloudflare / cloudfront if possible I've seen tutorials which describe the steps for using s3 as your endpoint or CDN as your endpoint. (https://ruddra.com/posts/aws-boto3-useful-functions/) But I haven't found one that describes the steps to move from s3 to CDN . -
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.