Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Will this QuerySet hit database twice or once?
organizations = Organization.objects().all() for organization in organizations: pass ids = organizations.values_list("id", flat=True) So I assign the QuerySet to a variable then loop over all instances in the QuerySet. Then I call values_list on the same variable. Will values_list cause another database access or will the instances fetched while iterating over them be reused to create the list? -
how to see data of user specified through django-table2?
Hello i want to make a table where one can see only his created rows and not others so i have specified a user for everyrow previously i used it like this - def see(request): as=A.objects.filter(user=request.user) return render(request,'m/see.html',{'as':as}) this was working perfectly fine later i rendered a table through Django table 2 my tables .py is class ATable(tables.Table): class Meta: model = A exclude = ('aid',) per_page = 2 i want to make it user specific so that i can only see data entered from myuserid not all my filter.py code is class AFilter(df.FilterSet): class Meta: model = A exclude = ('aid',) kindly help what and where should i write to specify the user -
Performance issue with Django and Postgres on a single update
I have an intermittent performance issue with Django and Postgres when updating a single line in a small "< 1m" rows table. The APM reports the issue on the update line, which is: Model.objects.filter(id=model_id).update(field=True) The error is raised because the execution takes more than 5s. This code runs in a celery task which receives the id of the model as the argument and executes normally most of the time. I know it's a very open question but any idea or help on what might be happening is appreciated. I'm running out Python 3.7, Django 2.0.13, and Postgres 9.5. -
How to show Data In database (SQL Server) On Django Admin
I have a project working with sqlite3 (default database) and I am trying to use Microsoft SQL Server instead. I need to do get data from my SQL Server database to Django Admin pages. -
Keep selected options after form submit in Django
I have a ModelForm for filter datas. I would like to keep selected options after form submit.There is any Django's solution for this problem? I did find any good solution yet. My model form: class ELearningFilterForm(forms.ModelForm): class Meta: model = ELearning fields = ('e_learning_type', 'e_learning_name', 'specializations') widgets = { 'specializations': forms.CheckboxSelectMultiple(), 'e_learning_type': forms.RadioSelect() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['e_learning_name'].required = False -
Computional complexity of reversed Foreign Key reference [closed]
I got such models in Django: class Artist(models.Model): name = models.CharField(max_length=128) class Sons(models.Model): title = models.CharField(max_length=128) artist = models.ForeignKey(Artist, on_delete=models.DO_NOTHING) Let's say there are 1000 songs in total, while Artist1 has just 10 songs. When I do basic ORM query like Artist.objects.first().songs.all(), does it need to check every of 1000 songs if it is related to the Artist1 or it "knows" which 10 to get? In other words, does the cost of retrieving those 10 songs increase as the next songs get created? -
How to save an image to a customized filepath in django admin?
I am trying to upload images to specific folders I select. the model code is as below: class PhotosTags(models.Model): Tag_name = models.CharField('Tag Name', max_length=100, default='NA', unique=True) Description = models.TextField('Tag Description', max_length=200, blank=True) class Meta: verbose_name = 'Tags' verbose_name_plural = verbose_name ordering = ['Date_created'] def __str__(self): return str(self.Tag_name) class Photos(models.Model): Name = models.TextField('Photo Name', max_length=200, blank=True) Tag = models.ForeignKey(PhotosTags, on_delete=models.CASCADE, default=None) filepath = 'Gallery' Photo = models.ImageField(upload_to=filepath, blank=False) class Meta: verbose_name = 'Photos' verbose_name_plural = verbose_name ordering = ['Date_uploaded'] pre_save.connect(upload_photo, sender=Photos) Here each tag has its own folder. The function I want to realize is, when I upload an image, I can select a specific tag (through selection of "Tag") and then this image can be uploaded to that folder. I tried use: signals to change the filepath but failed. The code i wrote is: def upload_photo(sender, instance, **kwargs): tardir = instance.Tag.Tag_name instance.filepath = 'Gallery'+'/'+tardir -
Package and deploy a Django app on local server
I am creating a web app using Django. I want to be able to package it into a setup file that can be installed on a client's computer and run on a local server on one computer or maybe a company's server which will serve the app to multiple pcs. I do not want to serve the app directly via internet as the data it will use is highly confidential. The client should not have access to the source code. The app will use multiple python modules other than Django. I am relatively new to programming so please keep it simple as far as possible. -
while adding image to database in django 3.1 showing this error
I am trying to add images to database it shows this error message. STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep)+['static'])) AttributeError: 'WindowsPath' object has no attribute 'split' Settings.py STATIC_URL = '/static/' STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep)+['static'])) MEDIA_ROOT = os.path.join(BASE_DIR,'images') MEDIA_URL = '/images' -
How to just listen to specific ip addresses for calling specific views
I was wondering if there is a way to listen to ip addresses and judge thereby if a view is allowed to be displayed or not. If so, could you recommend me a good approach for this. I'm gonna give an example in order to get better understood. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path('accounts/', include('accounts.urls')), ] As to this example, when a certain url pattern is matched, i want for django to check if the requesting pc ip address lies in 'allowed_ips_list'. Im aware of this can be attained inside views but, i was thinking that if i am able to optimize this process it would be better.. than calling a view and checking consecutively. As always, thank you for your attention. -
How can i show products by price range in same page by Django and js
I want to show my products in-between two range of prices. I am making an eCommerce site and there is a price system is like this: price range image and the html code is here: <!-- Start Range --> <div class="htc-grid-range"> <h4 class="section-title-4">FILTER BY PRICE</h4> <div class="content-shopby"> <div class="price_filter s-filter clear"> <form action="#" method="GET"> <div id="slider-range"></div> <div class="slider__range--output"> <div class="price__output--wrap"> <div class="price--output"> <span>Price :</span><input type="text" id="amount" readonly> </div> <div class="price--filter"> <a href="#">Filter</a> </div> </div> </div> </form> </div> </div> </div> <!-- End Range --> this is the js file: $("#slider-range").slider({ range: true, min: 10, max: 500, values: [110, 400], slide: function(event, ui) { $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]); } }); $("#amount").val("$" + $("#slider-range").slider("values", 0) + " - $" + $("#slider-range").slider("values", 1)); How can I solve this problem? I want to show products by the range of price but there is no min, max range in my HTML. I need the exact solution of models.py and view.py files for this HTML -
How to get year-month costs summary for certain category in DetailView, Django?
I have a table with expenses categories and when I click on the certain category it redirects me to this DetailView page. Then I want to show the year-month costs summary for chosen category to look similiar to this what I already got (summary per year-month but not for certain category). How can I achieve that? This is what I got for now and got stucked: def category_summary(): summary_by_year_month = Expense.objects.annotate( month=TruncMonth('date')).values('date').annotate( amount=Sum('amount')).order_by() return summary_by_year_month MODELS.PY class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' The most confusing part about this problem for me is how can I retrieve this information only for chosen category and show it to user in DetailView? Thank you in advance for any help. -
How to modify Django default language codes and names?
I am building a dictionary application for multiple languages using Django. Being a dictionary, I would like it to distinguish, say, between American English, British English, and Australian English. The LANGUAGES list in django.conf.global_settings.py has the following variations of the English language by default: LANGUAGES = [ ... ('en', gettext_noop('English')), ('en-au', gettext_noop('Australian English')), ('en-gb', gettext_noop('British English')), ... I would like to make American English more explicit both in terms of language code and language name. I tried to modify the django.conf.global_settings.py file OR to override the LANGUAGES list in my settings.py file as below but did not succeed. LANGUAGES = [ ... ('en-us', gettext_noop('American English')), ('en-au', gettext_noop('Australian English')), ('en-gb', gettext_noop('British English')), ... The language switcher that I am using, which is not displaying the desired changes, is the one I found on the official Django documentation. <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language" class="custom-select custom-select-sm bg-dark border-dark text-light"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> … -
How to call custom methods in DetailView / ListView in django?
I am builgind a eCommerce Website and thinking a custom method to check if a Product purchased by the user who's logging in, then I came up the "check_bough" method in ProductDetail View with Prodcut model and ProdcutPurchase model Now I have below qustions need your help: Which method should I override to make it call automatically? I thought of thinking on override the get_context_data_method. If check_done returns true then I would make a context['bought'] = 'some str' and render it on html. However, I think there must be better way... How should I modify the ProdcutList View to make it work as well? Finally, what will you guys suggest to show it in the html file? I just really want to know how will you guys will do about this problem. Even adding a attribute like 'bought by' in Prodcut model would be good or not? Do really need your help!! Thank you so much! Views.py class ProductList(generic.ListView): model = Product def get_context_data(self, *args, **kwargs): context = super(ProductList,self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj return context class ProductDetail(ObjectViewedMixin,generic.DetailView): model = Product def get_context_data(self, *args, **kwargs): context = super(ProductDetail,self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj return … -
How to list Django switches?
In my Django when you execute python -m django it lists all subcommands. But how do you list all switches like --version and others? -
Unable to override both contrib.admin.AdminSite and django.contrib.auth.admin.UserAdmin simultaneously
I'm trying to both override the default AdminSite class, and the UserAdmin. I'm trying to combine the examples from two different sections of the documentation: Overriding the default admin site Extending the existing User model Originally I had just the overriden AdminSite class, but then the problem arose when I tried to also override UserAdmin. Both of these work independently. I can either override AdminSite and get a custom header, or UserAdmin and get my inline showing. For whatever reason, I run into an import error: ImportError: Module "core.admin" does not define a "CoreCustomAdmin" attribute/class. It looks like a sort of circular dependency, but that's just a guess, as I cannot figure out where/how it's happening. Stack trace: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 20, in import_string return getattr(module, class_name) AttributeError: module 'core.admin' has no attribute 'CoreCustomAdmin' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 44, in autodiscover_modules if register_to: File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/utils/functional.py", line 240, in inner self._setup() File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 540, in _setup AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
Django. How to query an array within a JsonField record?
Django. How to query an array within a JsonField record? I have a line that contains a JsonField field and inside this jsonfield contains another array field. How do I query the data and return the line within this array? Json in database site paste.ofcode.org/5v3GBex9sWVFBWMWjgbn3Q produto = Produto.objects.filter(pk=pk, labolatorio__historico__items__produto__contains='656aa2b9-9f5e-483b-8182-510bde827d5f').first() I need the result of the index in which the id was compatible In this case I need this return { "ee": { "ee": 0.1, "values": 0.1 }, "insetos": false, "produto": "656aa2b9-9f5e-483b-8182-510bde827d5f", } -
I keep getting the No module named 'django_heroku'
I'm trying to deploy an app on heroku but i keep getting this. Not the first time i'm facing this problem but i'm not able to get around it this time. Anyone knows what might cause this error? knowing that django-module is installed and the requirements.txt is up to date. -----> Python app detected -----> Installing python-3.8.5 -----> Installing pip 9.0.2, setuptools 47.1.1 and wheel 0.34.2 -----> Installing dependencies with Pipenv 2018.5.18… Installing dependencies from Pipfile.lock (f9b65c)… -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 224, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 231, in fetch_command settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load … -
Why am i getting Uncaught SyntaxError: unexpected token: identifier
for (post of posts){ //Posts are returned from a python django function let readMore = ''; let postDesc = post.fields.description if (post.fields.description.length > 227) { readMore = `<p class="btn btn-link" onclick="this.innerHTML = ${postDesc}"> Read more</p>`; }; output += ` <p class="card-text" style="white-space: pre-line;"> ${post.fields.description.substring(0, 227)} ${readMore} </p> ` }; } But when i click the read more button: Uncaught SyntaxError: unexpected token: identifierlocalhost:8000:1:22 I tried to remove the onclick and replace it with this at the end: $('#mainPosts').append(output) function showMore() { $('.readMore').click(function (e) { e.preventDefault(); $(this).parent().html(`<br> ${post.fields.description}`) }) } let g = document.createElement('script'); let s = document.getElementsByTagName('script')[0] g.text = showMore(); s.parentNode.insertBefore(g, s) But the problem is it's not replacing the substring current post description with the full one, it's replacing it with the very last post full description in the list! -
How to have a list of Fields in django models?
I have a models like this: from django.db import models class Article (models.Model): author = models.ForeignKey('Users.User') title = models.CharField() text = models.TextField() stars = [ models.IntegerField(), # 0 stars models.IntegerField(), # 1 stars models.IntegerField(), # 2 stars models.IntegerField(), # 3 stars models.IntegerField(), # 4 stars models.IntegerField(), # 5 stars ] but the problem is it the stars Fields won't be recognized in 000x_initials.py. What I have to do? I want to use it like this: if request.method == 'POST': post_data = request.post star = int(post_data['star']) article.stars[star] += 1 article.save() -
Unable to start django site
I have been trying to run my django application/site by using python manage.py runserver But the command line just does not show any output. I have selected the python env as the interpreter already but still, nothing happens -
Upload Document in Django Rest Framework Dynamic Form
In my Djago-React Application I am creating a form which has dynamic fields as well as an option to upload the document For that I am using multipart/form-data and its working fine when I am using it only to upload the document but as soon as I enter the data in dynamic fields the serializer stops handling the data. Example data: Form Data: transaction_no: 2341 document: (binary) items[0][product]: 5 items[0][quantity]: 1 items[0][fault]: Repairable items[1][product]: 4 items[1][quantity]: 2 items[1][fault]: Return allotment: 122 Response: {"items":[{"product":["This field is required."]},{"product":["This field is required."]}]} Serializer: class DeliveredItemsSerializer(serializers.ModelSerializer): class Meta: model = DeliveredItems fields = "__all__" class DeliveredSerializer(serializers.ModelSerializer): items = DeliveredItemsSerializer(many=True,required=False) class Meta: model = Delivered fields = "__all__" def create(self, validated_data): items_objects = validated_data.pop('items', None) prdcts = [] try: for item in items_objects: i = DeliveredItems.objects.create(**item) prdcts.append(i) instance = Delivered.objects.create(**validated_data) print("prdcts", prdcts) instance.items.set(prdcts) return instance except: instance = Delivered.objects.create(**validated_data) return instance def update(self, instance, validated_data): items_objects = validated_data.pop('items',None) prdcts = [] try: for item in items_objects: print("item", item) fk_instance, created = DeliveredItems.objects.update_or_create(pk=item.get('id'), defaults=item) prdcts.append(fk_instance.pk) instance.items.set(prdcts) instance = super(DeliveredSerializer, self).update(instance, validated_data) return instance except: instance = super(DeliveredSerializer, self).update(instance, validated_data) return instance Models: class DeliveredItems(models.Model): choices = (('Repairable', 'Repairable'),('Return', 'Return'), ('Damage', 'Damage'), ('Swap Return', 'Swap Return')) product … -
is serializer necessary in Django RestFramework when operating with external db
I have requirement where in, I am suppose to build REST API, Database that i have to use is MongoDB and is not a part of the current Django project, it is managed and handled by some other team. for current Django project, I use MySQL. below is how i write API's with current django project with MySQL views.py class UserViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) serilaizers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' but for MongoDB new requirement, i use PyMongo to interact with MongoDB views.py import pymongo class EmpViewSet(viewsets.ViewSet): def list(self, request): myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["external_database"] mycol = mydb["employee"] result = mycol.find_one({'emp_id': 123}) return Response({"result": result}, status=status.HTTP_200_OK) it is working fine with above code(it is not the exact code, similar implemention). i need to do all CRUD operation on MongoDB. I am unaware that serialzers is needed for this or not? if needed then, how will i write the serializer for it, since the result from the mongo query may give dynamic schema. any help will be greatly appreciated ! Thanks in advance ! -
Separate Django Restful API into two servers
I am developing an API server which is written in Django framework, and using Nginx and uWSGI to implement the web server. There are several APIs contain in this project, some of them are related to billing service, which are relatively important that we are thinking about to separate these APIs to run on another server. The two API servers are going to use the same files, all the models and database are the same. The following is my nginx.conf: user nginx; worker_processes 2; worker_rlimit_nofile 8192; events { worker_connections 3000; } http { upstream myapp { server unix://tmp/myapp.sock; } server { listen 80; location / { include uwsgi_params; uwsgi_pass myapp; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; } } } I had found several solutions that adding another server block inside of the nginx.conf, and also provide a uwsgi.ini config file for it. But I still don't know how to implement it exactly. I am really new to the Nginx, and have pretty blur concept about it now. Appreciate for any help! -
Unable to bind data in tables with one view function
def index(request): indexdata = Customer.objects.all() return render(request, 'index.html',{ "Customer":indexdata }) indexdata2 = home.objects.all() return render(request, 'index.html',{ "home":indexdata2 })