Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upgrading to pip version 19.3.1
doesn't work I want to upgrade pip version from 19.2.3 to 19.3.1 but couldn't able to do that. I had tried the command so many times but that doesn't resolve the problem -
Django. Sanity and understandable one-to-one relationships
I am wondering how to make the one-to-one relations in Django a bit more understandable and clear for the new developers. Let's take a look at the basic example of the Django docs. from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return "%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) def __str__(self): return "%s the restaurant" % self.place.name class Waiter(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return "%s the waiter at %s" % (self.name, self.restaurant) What follows are examples of operations that can be performed using the Python API facilities. Create a couple of Places: >>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton') >>> p1.save() >>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland') >>> p2.save() Create a Restaurant. Pass the ID of the “parent” object as this object’s ID: >>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False) >>> r.save() A Restaurant can access its place: >>> r.place <Place: Demon Dogs the place> A Place can access its restaurant, if available: >>> p1.restaurant <Restaurant: Demon Dogs the restaurant> The problem that I don't understand how to let the First model to know … -
Is it possible to populate models with fixtures in AppConfig's ready() method?
I'm trying populate model from fixtures after starting Django. I found out, that custom methods can be called in AppConfig's ready() method. So, when I'm trying to do next: class ApplicationConfig(AppConfig): name = 'application' def ready(self): from django.core.management import call_command call_command('loaddata', 'application/fixtures/some_info.json') I got error message: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/app/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/venv/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn\'t reentrant Is there any other ways to prepopulate model on start? Or, how to fix my problem? -
django form multiple choice field convert to dropdown list
i want to convert my multiple choice field into a dropdown list which is having list of all users. to get this form i'm using django form class UserData(forms.Form): users = forms.ModelMultipleChoiceField(queryset = User.objects.all(), widgetforms.CheckboxSelectMultiple) start_date =forms.DateField(initial=datetime.date.today) end_date = forms.DateField(initial=datetime.date.today) in output html page we get form code like this <form method="post" action="application"> <input type="hidden" name="csrfmiddlewaretoken" value="kupqwrJmkQl9cRfRbuEhUuXJZCvzfkVeggYB6"> <div class="usage-form"> <p><label>Users:</label> </p> <ul id="id_users"><li><label for="id_users_0"><input type="checkbox" name="users" value="1" id="id_users_0">mohit</label> </li> <li><label for="id_users_1"><input type="checkbox" name="users" value="2" id="id_users_1"> krishna</label> </li> </ul> <button type="submit" name="userlist_sub" class="btn-light btn">Submit</button> </div> </form> is there any way in jquery or js to convert it in a dropdown list ? because as number of users increases list of checkbox won't look good. right now its list of only two users. -
Adding react build files to a Git repository
I am trying to add the build files which are created by npm run build in a React App, to a Git repository. The files generated by npm run build is getting directly used by my backend server on Django. And my backend(in Django) and the frontend(in React) are two different Git repositories. Here is the problem I am facing. Every time I run npm run build it creates new files with different hashes. If I keep on adding all the files, the size of my git repository will increase. I tried removing older files completely from git by running git filter-branch --tree-filter 'rm -rf build/static' HEAD. But since this rewrites the history, I'll have to use git push with --force every time, which doesn't feel right. I can avoid adding static files all together by creating the build directly on the server. This will be helpful, but everyone working on the back end will have to build the static files locally, which means they'll have to install node and react, which might be cumbersome for the back end developers. Is there a better way of doing this? How should I solve this? -
Elasticsearch + Django in Openshift online
I have a website written in python 3 and django which records items of the django DB in an elasticsearch index running on my local machine, using django-elasticsearch-dsl. I have pushed my application to openshift online, and it works well (using a public url), but naturally I can't use the same elasticsearch index. How can I use the django-elasticsearch-dsl script when my app is running in Openshift? Thanks, -
Image Display Issue With Chrome Version on Website
I am working on one of the website which is developed in Django where I am displaying image with many other content in Tabular form.Today, I updated the Chrome version to 79 so the image is not displaying on that particular page where the image is inside the table. On Firefox it is working properly and also on the old version of chrome it is working properly. But in latest version i am facing Problem.. -
how to get error logs from fargate using Django, docker
I deployed django web project using Nginx to aws ECS fargate using Jenkins and Docker. The problem is, CloudWatch log shows there is no error, but when I try to send ping or call api, it shows 503 or 502. It seems like CloudWatch log does not work when response is 500. The only way I have in mind is make docker file allow ssh, and open port 22 of fargate, and ssh. However, using ssh to production and docker image sounds strange to me. I want to know where I can find error log. -
Django admin always reset field value changes in docker container
I am migrating and upgrading my mysql 5.5.X, python 2.7, django 1.11 web app on a ubuntu 14.04 machine to dockerized apps with python 3.7 on a ubuntu 18.04 machine. Everything seems working fine. However, when I change the field value in django admin, the changes always reset to original (10) after refreshing with Ctrl + R. For example, there is a model field called search quota. The original value is 10. I change it to 15 or others in django admin. After that, I keep refreshing and the value will fall back to 10. Also, when I send several ajax requests to a python controller to deduct its value, it will restore to the original one. Why the changes are not persistent and how can I fix it? Is it about my docker-compose config not correct? When I checked the logs, there are no error messages from the containers. Though I can see some warnings in db container. version: '3' services: db: image: mysql:5.5.62 container_name: db volumes: - dbdata:/var/lib/mysql expose: - '3306' restart: always environment: MYSQL_DATABASE: 'bbbb' MYSQL_USER: 'aaaa' MYSQL_PASSWORD: 'yyyy' MYSQL_ROOT_PASSWORD: 'xxxx' web: build: . command: > sh -c "exec gunicorn spo.wsgi:application --workers=2 --threads=4 --worker-class=gthread -b 0.0.0.0:8001" # … -
How do I create individual pages for a dataset
I want to create individual pages for each headline gotten,but I have no clue how. https://tutorialspoint.dev/language/python/fetching-top-news-using-news-api -
Django Caching - Template not rendering required data because of caching
I'm building a platform that allows users to login via GitHub. After authentication, users will have access to repositories and corresponding issues. I am using requests to get data from GitHub. I decided to do a per-view cache for the view that gets the user's repositories so that the requests won't be made multiple times. Caching is handled by Memcached. Here's the view: def repositories(request, username=None): access_token = get_access_token(request) payload = { 'access_token': access_token, 'sort': 'updated', } repos_url = 'https://api.github.com/user/repos' request_repos = requests.get(repos_url, params=payload) if request_repos.status_code == requests.codes.ok: repositories = request_repos.json() for repository in repositories: repository_name = repository['name'] request.session[f'{repository_name}_issues_url'] = repository['issues_url'] return render(request, 'core/repositories.html', {'repositories': repositories}) I specified the per-view caching in URLconf such that it caches for 15 minutes: urlpatterns = [ path('@<str:username>/repositories/', cache_page(60 * 15)(repositories), name='repositories'), ] The problem is when the page is cached and a new repository is added on GitHub, the just added repository won't be added when the template is returned - the cached page is returned which doesn't include the new repository. How do I solve this problem? What can I do? Thanks! -
Removing cached Query from Redis using django-cacheops
I am using django-cacheops to cache a Query. And updating some in the same instance with some different API call now I want to remove this cached Query from Redis. This is API-1 users = User.objects.cache().get(user_id = user_id) Now I am updating my user with API-2 user = request.user if user.is_sms_read: user.is_sms_read = False else: user.is_sms_read = True user.save() Now I am fetching the data with same API-1 and it is giving me the data cached data I want if I call the API-2 it should clear the cache and fetch new data. -
Trying to render data from database in a html table using Django framework
I have created a GPU database which I want to render in HTML format using Django MVT. This is "urls.py" script inside the 'graphicsCard' ['graphicsCard' is the app name] from django.urls import path from . import views urlpatterns = [ path('products', views.productViews, name='products') ] views.py of graphicsCard from django.shortcuts import render from .models import Products # Create your views here. def productViews(request): allproduct = Products.objects.all() context = { 'allproduct': allproduct } return render(request, 'Products.html', context) html template called as "products.html" {% extends 'homepage.html' %} <!-- {% load %} --> {% block content %} <div class="row"> <div class="col-2 bg-info"> Menu </div> <table class="col-10 table table-dark py-0 my-table"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> {% for x in allproduct %} <tr> <td>{% x.name %}</td> <td>First</td> <td>Last</td> <td>Handle</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} when I run python manage.py shell and type product = Products.objects.all() product[1].name it sends the data from the database but I cannot figure out this error called "Error during template rendering" followed by "Invalid block tag on line 21: 'x.name', expected 'empty' or 'endfor'. Did you forget to register or load this tag?" -
Django: Understanding QuerySet API
I'm a newbie in Django and I have some questions about making queries by QuerySet API. For instance, I have User, his Orders, and its Statuses class User(model.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) is_active = models.BooleanField() class OrderStatus(model.Model): name = models.CharField(max_length=100) class Order(model.Model): number = models.CharField(max_length=10) amount = models.DecimalField(max_digits=19, decimal_places=2) user = models.ForeignKey(User, related_name="orders") order_status = models.ForeignKey(OrderStatus) creation_datetime = models.DateTimeField(auto_now_add=True) # Some filtering field filtering_field = models.IntegerField() I combined all of my questions to this one query: Get active users with some additional data for each user: 'Amount' of the Orders filtered by 'filtering_field' and aggregated by Min and Max 'Number' and 'Amount' of the first Order filtered by 'filtering_field' Count of the Orders filtered by 'filtering_field', aggregated by Count and grouped by 'Order Status'. This grouping means that data from query #1 and #2 can be duplicated and it's ok. I could make this query in T-SQL by 3 separated subquery with own grouping, filtering, ordering: SELECT u.id, u.first_name, u.last_name, ts.min_amount, ts.max_amount, first_order.number as first_order_number, first_order.total_sum as first_order_total_sum, cnt.order_status_id, cnt.cnt FROM [User] u -- 1. 'Amount' of the Orders filtered by 'filtering_field' and aggregated by Min and Max LEFT OUTER JOIN ( SELECT [user_id], MIN(amount) min_amount, MAX(amount) max_amount … -
How to store the view output in memcache in django. When I am storing the data in cache it storing None
This is My View code, on POST request, I will pass some start_date and end_date to CumulativeMain method, after some calculation it returns the dataframe. This dataframe, I want to store into the cache. But it is storing the None values. if request.method == 'POST': cache_key = 'portfolio_returns' # this key stores prtfolio returns data cache_time = 86400 # time in seconds for cache to be valid cumulative_return = cache.get(cache_key) if not cumulative_return: cumulative_return= CumulativeMain(start_date,current_date) #it returns dataframe cache.set(cache_key, cumulative_return, cache_time) print(cache.get(cache_key)) # printing None instead of data -
What are you supposed to do with the original field that you translate with django-modeltranslation?
I specify in settings.py the languages the fields of the models should be available in: gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('zh-cn', gettext('Simplified Chinese')), ('zh-tw', gettext('Traditional Chinese')), ) But when I apply the migrations, this will mean that apart from the original field, it will create these additional three fields. If the original field was "name", I will now have "name", "name_en", "name_zh_cn", and "name_zh_tw". What is one supposed to do with the original field? Ignore it? Delete it? Should I just not put English in LANGUAGES and treat the original one as the English translation? -
django - specific query or calculation for this relationships
I have Influencer and InfluencerList classes in my model (many-to-many relationship). InfluencerList model has also many-to-one relationship with User model. I have this query which looks in logged in users InfluencerList's and calculates the Influencer's in each list, it works fine. context['influencer_lists'] = logged_in_user.lists.annotate(influencer_count=Count('influencers')) I also want to pass the amount of total followers (a field in Influencer class) in each InfluencerList. I think i must use something like that but i don't know where to assign the query results as there are many lists: q = userList.influencers.annotate(total_followers=Sum('follower_count')) #maybe combined with for userList in logged_in_user.lists.all() What is the clearest and best way to do it? models.py: class Influencer(models.Model): fullname = models.CharField('Full Name', max_length = 40, blank=True, null=True) follower_count = models.IntegerField('Follower Count', default=None, blank=True, null=True) class InfluencerList(models.Model): name = models.CharField('Name:', max_length=20, blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') influencers = models.ManyToManyField('Influencer', related_name='lists') views.py: class InfluencerListsView(LoginRequiredMixin, ListView): #model = InfluencerList template_name = "app1/influencer_lists.html" #context_object_name = "influencer_lists" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) logged_in_user = self.request.user context['influencer_lists'] = logged_in_user.lists.annotate(influencer_count=Count('influencers')) lists = logged_in_user.lists.all() for userList in lists: # this line shows the same follower count for each list ofc. context["myKey"] = userList.influencers.aggregate(total_followers=Sum('follower_count')) return context -
Running startproject on django-admin runs, but no directories are being made
I'm trying to follow the tutorial on the Django website, so I tried to make a project using django-admin startproject mysite. The command runs without error, but when I open the directory the project it's supposed to be stored in, the directory is completely empty. Running the command again gives me the following: CommandError: 'G:\PROGRAMS\django-tutorial\mysite' already exists. I read on some other posts where it might be related to having multiple installs and the commands running and conflicting, so I removed all the references to my other Python versions (except 3.8). It still doesn't seem to do anything. I made a different folder to see if it's just some weird folder conflict (There used to be another django project in the same folder before I deleted it; I wanted to start the tutorial again). However, still no files are being created. I'm pretty stumped by this. Does it have anything to do with my Python installs or a previous Django installation (I tried running pip uninstall django twice, but it only ran once on my current Django installation). I'm using Django 3.0.1 currently, on Windows 10. Thanks -
Hawthorn to Ironwood Migration (Open edX)
I am trying to execute database migration from hawthorn.master to ironwood.master, during MySQL migration, getting the error like this: File “./manage.py”, line 123, in execute_from_command_line([sys.argv[0]] + django_args) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/init.py”, line 364, in execute_from_command_line utility.execute() File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/init.py”, line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py”, line 283, in run_from_argv self.execute(*args, **cmd_options) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py”, line 330, in execute output = self.handle(*args, **options) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py”, line 204, in handle fake_initial=fake_initial, File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/migrations/executor.py”, line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/migrations/executor.py”, line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/migrations/executor.py”, line 250, in apply_migration self.recorder.record_applied(migration.app_label, migration.name) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/migrations/recorder.py”, line 73, in record_applied self.migration_qs.create(app=app, name=name) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/query.py”, line 394, in create obj.save(force_insert=True, using=self.db) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/base.py”, line 808, in save force_update=force_update, update_fields=update_fields) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/base.py”, line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/base.py”, line 924, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/base.py”, line 963, in _do_insert using=using, raw=raw) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/manager.py”, line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/query.py”, line 1079, in _insert return query.get_compiler(using=using).execute_sql(return_id) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py”, line 1112, in execute_sql cursor.execute(sql, params) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/backends/utils.py”, line 64, in execute return self.cursor.execute(sql, params) File “/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/utils.py”, line 94, in exit six.reraise(dj_exc_type, … -
django.core.exceptions.ImproperlyConfigured. SOS from django beginner
I am kind of novice in django and I need your help!!! my console says "django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import." But I don't know why... this is my "boardapp/urls.py" ''' from django.urls import path from .views import * urlpattern = [ path('', main_page, name='main') ] ''' and this is my "awsdjangoproj/urls.py" ''' from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('boardapp/', include("boardapp.urls")) ] ''' Do you guys have any idea how to fix this tiny problem^^;;; -
Best Profanity filters for using in Python Django project [closed]
I have a requirement where I need to use the profanity check for the list of forms. If the profanity is detected then it should stop further actions. Currently I am using "profanity_check" package for profanity detection, however getting the below warning from python in cmd. Please suggest. FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+ Is the "profanity_check" package suggested, what are alternative solutions? Thank you. -
No Reverse Match when applying django_restframework_api_key in django admin page
I am trying out the django_restframework_api_key library. I am trying out the example in the API Key models in the user guide with a little bit of tweaking. Issue: When trying to save the api key in the Django Admin Page, I get a No Reverse Match Error. Here's the page where I hit save and then get an error: ScreenShot Error: Here's the error, I get: Internal Server Error: /admin/clients/clientapikey/add/ raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'clients_clientapikey_change' with arguments '('',)' not found. 1 pattern(s) tried: ['admin\\/clients\\/clientapikey\\/(?P<object_id>.+)\\/change\\/$'] Project name: api_key_project App Name: clients Django Version: 3.0.1 Python Version: 3.6.9 The clients/model.py file: from django.db import models from rest_framework_api_key.models import AbstractAPIKey # Create your models here. class Client(models.Model): name = models.CharField(max_length=200) active = models.BooleanField(default=True) def __str__(self): return self.name class ClientAPIKey(AbstractAPIKey): client = models.ForeignKey( Client, on_delete=models.CASCADE, related_name="api_keys", ) The clients/admin.py file: from django.contrib import admin from .models import Client, ClientAPIKey admin.site.register(Client) admin.site.register(ClientAPIKey) Installed app section of api_key_project: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'clients', 'rest_framework', 'rest_framework_api_key', ] The original AbstractAPIKey model of the library can be found here Any ideas where I am going wrong? Should I add something to my app urls.py ? -
create or update order after addtocart drf
I am trying to create or update order after addtocart: serializers.py: class AddtocartSerializers(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['image_number','title','image_size','file_type','price'] class CartSerializers(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all()) items = AddtocartSerializers(many=True) ordered_date = serializers.DateTimeField() class Meta: model = Order fields = ['user','items','ordered_date'] views.py: class AddtocartView(generics.CreateAPIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset=OrderItem serializer_class = AddtocartSerializers class CartView(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset=Order.objects.all() serializer_class = CartSerializers current cart api getting all the user and item but i want to create or update order after addtocart and on cart page it should get all the item belong to that user and addup the price -
How to request data from an open source website such as Reddit or Github and display on the Local Django Website?
I am quite a newbie to Django and I am trying to understand how API calls and requests work in Django. I have a simple Django website that has User login and authentication system. I want a user to save the top ten reddit posts and display them on their respective login system. I have seen the request method in Python and some web-crawling methods. I am unable to figure out a way to request data from Reddit . Here is the code I have written so far : https://github.com/darthvedder17/Django-Website-Reddit -
How to use django-request module to log all the user activities in a table?
I'm using Django 1.8 version. Need to know how to use django-request or any other module to capture the all the user activities in a website.