Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter by child class type
Lets say we have a class Place with a class Restaurant inheriting from it : from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) If I have a class Tag related to places : class Tag(models.Model): name = models.CharField(max_length=50) tagged = models.ManyToManyField(Place, related_name="tags") For a given tag, how do I get a queryset selecting all Restaurants that have this tag, but not other kind of places ? -
Celery can not find tasks nor settings with Django 2.1.1
I am trying to do Asynchronous task using Celery and RabbitMQ server. I have installed Celery and RabbitMQ on my system. Now when I'm running celery worker -l info, the celery starts working using default configuration settings ignoring my settings and it shows no registered tasks. I am assuming there is something wrong because of my project structure. But its not possible to change it now. Can anyone help me figure out what's the problem here? Tasks are not found and it starts with default settings ignoring my username and password and vhost mentioned in settings file. Project Directory: |--engine | |--app | | |--user | | |--program | | | |--__init__.py | | | |--admin.py | | | |--apps.py | | | |--models.py | | | |--tasks.py | | | |--urls.py | | | |--views.py | | |--course | |--config | | |--settings | | | |--__init.py | | | |--default.py | | | |--development.py | | | |--production.py | | |--__init__.py | | |--celery.py | | |--middleware.py | | |--urls.py | | |--wsgi.py | |--.env | |--manage.py | |--requirements.txt engine/config/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.default') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') … -
approximate count of rows in postgresql django
I have a postgresql database connected to with django. In database there is lots of big tables which I want their row count. Because of large size of tables this takes a lot of time to execute. I founded that the approximate count could be retrieved from pg_class. Is there any way to this in Django and not executing raw query? -
How to send data using ajax in line by line to view
I am working with django project. In html code I use ajax to display data, and from view I want to send data in line by line. For example: def senddata(request): for i in range(10,20): data = { 'is_taken': i } return JsonResponse(data) How can I send every number to html, not all ? In above code, I just receive value is 10 -
Django Filters: Suggest improvements to dynamic filtering logic
I am performing filtration on my dataset based on many kinds of search criterias selected by users on the frontend. Here are a few considerations: All the filter criterias are non-mandatory. The user can select/enter values or leave it blank. The backend has to figure out a way to check NULLs. Dropdowns are multi-select so the filter form data could have multiple lists of ids. (lots of IN queries) There are DATE (from/to) related fields as well which can be left blank. So the code has to handle the following scenarios: Date Range filtration | Date > DDMMYYYY | Date < DDMMYYYY. Here is how the form looks: This is my current approach: class BookingExportFilterBackend(generic_filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): predicate = request.data if all(dt in predicate for dt in ('from_date', 'to_date')): queryset = queryset.filter(date__range=(predicate['from_date'], predicate['to_date'])) if 'from_date' in predicate and 'to_date' not in predicate: queryset = queryset.filter(date__gte=predicate['from_date']) if 'to_date' in predicate and 'from_date' not in predicate: queryset = queryset.filter(date__lte=predicate['to_date']) if 'state' in predicate: queryset = queryset.filter(state__in=predicate['state']) if 'clients' in predicate: queryset = queryset.filter(client__in=predicate['clients']) if 'camera_operators' in predicate: queryset = queryset.filter(camera_operator__uuid__in=predicate['camera_operators']) return queryset I feel that it can be improved, especially the date part. I am using the Q library … -
Dynamik DataTables with Django and Ajax
I refer to the following posts: Reload table data in Django without refreshing the page How to display a table with 10 rows per page? Minimal Example for dynamic HTML pages with Django and AJAX I have little experience with Ajax and Javascript and a bit of Django knowledge. I like an html table to refresh dynamically, that is, every second or so. Moreover, I want the html table to be a javascript DataTable, as that looks really nice (see second link above). The dynamic loading part is working (see first and third link above). However, in my code only the data which are already stored in the database are shown as a nice DataTable. The data loaded afterwards by the setInterval-function is loaded in a plain HTML table. Apparently, the prepend command talks plain html and is not converted to a DataTable. The DataTable does not contain any data that come in from the setInterval function. Any idea how I can change that? Thanks in advance! Here is my index.html code <html> <table id="_appendHere" class="display" width="100%" cellspacing="0"> <thead><tr><th>Name</th></tr></thead> <tbody> {% for a in questions %} <tr><td> {{ a.question_text }} </td></tr> {% endfor %} </tbody> </table> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"> <script … -
Django : Trying to display the object from django admin to a HTML page
I'm trying to display text in a HTML page which i'm saving in django admin interface and whenever i save the data and trying to display the text in html page instead of the text a line space was being printed. [Output][1] attaching the code screenshots here [views file][2][HTML page][3][Models][4][Django Admin Interface][5] [1]: https://i.stack.imgur.com/aWsls.png [2]: https://i.stack.imgur.com/FdKzS.png [3]: https://i.stack.imgur.com/8I10Q.png [4]: https://i.stack.imgur.com/GmKFx.png [5]: https://i.stack.imgur.com/xw8LI.png -
Django: dynamically change caching of pages
I want to cache a page dynamically Generally we have: from django.views.decorators.cache import cache_page @cache_page(60 * 15) def my_view(request): ... or from django.views.decorators.cache import cache_page urlpatterns = [ path('foo/<int:code>/', cache_page(60 * 15)(my_view)), ] But inside the view i want to judge based on some logic, change the cache mechanism (like clear the cache and again start new cache) def my_view(request): if some logic is true: then clear cache_page() execute the view login response = ...... add response to cache_page() return response else: return the old cached page -
Django Rest Framework set a field read_only after record is created
I'm using Django 2.x and Django REST Framework. I have a model with contact as a foreign key class AmountGiven(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField(help_text='Amount given to the contact') given_date = models.DateField(default=timezone.now) created = models.DateTimeField(auto_now=True) and serializer like class AmountGivenSerializer(serializers.ModelSerializer): mode_of_payment = serializers.PrimaryKeyRelatedField(queryset=ModeOfPayment.objects.all()) contact_detail = ContactSerializer(source='contact', read_only=True) contact = serializers.PrimaryKeyRelatedField(queryset=Contact.objects.all()) class Meta: model = AmountGiven depth = 1 fields = ( 'id', 'contact', 'contact_detail', 'amount', 'given_date', 'created' ) contact field is required while creating a new record. But I do not want contact to be modified once it is created. But when I send only amount with PUT method it says { "contact": [ "This field is required." ] } And when I use PATCH method, it works fine but if passing some other value for contact, it is updating contact as well. I want to make contact field not-required while updating existing record. And even if it is passed, use the earlier one instead of setting the new data. -
django-xhmtl2pdf Turkish charachter problem
I am using xhtml2pdf module and i set character encoding UTF-8 for view and HTML but some Turkish character (ğ, ı) is incorrect. I was change HTML font(Code 2000) but problem not solved. How can I fix this please? -
Abstract relationship between abstract entities
I would like to add some abstraction to the following model classes : class Person(models.Model): groups = models.ManyToManyField('Group', through='Membership') acquaintances = models.ManyToManyField('Group', through='Acquaintanceship') class Group(models.Model): members = models.ManyToManyField('Person', through='Membership') partners = models.ManyToManyField('Person', through='Partnership') class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) class Partnership(models.Model): group1 = models.ForeignKey(Group, on_delete=models.CASCADE) group2 = models.ForeignKey(Group, on_delete=models.CASCADE) class Acquaintanceship(models.Model): person1 = models.ForeignKey(Person, on_delete=models.CASCADE) person2 = models.ForeignKey(Person, on_delete=models.CASCADE) I could achieve this by creating abstract classes : class Entity(models.Model): pass class Relation(models.Model): entity1 = models.ForeignKey(Person, on_delete=models.CASCADE) entity2 = models.ForeignKey(Person, on_delete=models.CASCADE) And making Person and Group inherit form Entity and Membership, Partnership and Acquaintanceship inherit from Relation. But how do I "link" the child class properties to the parents one ? Is there a more standard way to achieve this ? -
Django REST Framework - Can not update fields of model by serializer
I want update model's fields with save to DB. I wrote this code. But I can not update model. serializer.is_valid() return value is True. Why I can not? post = Post.objects.get(pk=post_id) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() -
Django Rest Framework - define API from an existing view
I'm writing my django app, and i have a lot of views that already returns a JSONResponse object, for example: def power_on_relay(request): '''View that Power on one of the available relays''' try: relay_id = get_or_raise(request, 'relay_id') GPIO.setmode(GPIO.BOARD) GPIO.setup(relay_id, GPIO.OUT) GPIO.output(relay_id, True) pin_status = GPIO.input(relay_id) return JsonResponse({'success': True, 'message': 'Relay {0} was powered on'.format(relay_id), 'data': None}) except Exception as ex: return JsonResponse({'success': False, 'message': str(ex), 'data': ''}) Now, i need to expose some of these views as "API" and i need to manage the authentication, throttling, etc... So, i was wondering if it's possible using DRF and without writing tons of redundant code. I mean, there is a short way to do that? something like a decorator that doesn't change my web application behaivor? Any suggestions? -
How to convert an URL S3 picture to streaming
I have some pictures stored on an S3 bucket and I want to display them as streaming on my website. I don't know how to do it and if I have to do it in the backend side or frontend. I hear about FFMPEG, I don't know if I can use an url in input. -
switching sqlite to postgresql
recently i have done a small project using defalut db in django sqlite3 but now i want to change it to postgresql. I am trying to do it but i am getting an erro like OperationalError can you help me to do it? I have set up settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } when i do makemigrations it wont do it -
Could I please get help optimizing this postgres query?
I apologize in advance if this is poor StackOverflow etiquette, but I have a very slow query that I found in my logs and I don't know how to optimize it with an index. This is the query and the explain: # explain analyze SELECT "myapp_image"."id", "myapp_image"."deleted", "myapp_image"."title", "myapp_image"."subject_type", "myapp_image"."data_source", "myapp_image"."objects_in_field", "myapp_image"."solar_system_main_subject", "myapp_image"."description", "myapp_image"."link", "myapp_image"."link_to_fits", "myapp_image"."image_file", "myapp_image"."uploaded", "myapp_image"."published", "myapp_image"."updated", "myapp_image"."watermark_text", "myapp_image"."watermark", "myapp_image"."watermark_position", "myapp_image"."watermark_size", "myapp_image"."watermark_opacity", "myapp_image"."user_id", "myapp_image"."plot_is_overlay", "myapp_image"."is_wip", "myapp_image"."size", "myapp_image"."w", "myapp_image"."h", "myapp_image"."animated", "myapp_image"."license", "myapp_image"."is_final", "myapp_image"."allow_comments", "myapp_image"."moderator_decision", "myapp_image"."moderated_when", "myapp_image"."moderated_by_id", "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined", "myapp_userprofile"."id", "myapp_userprofile"."deleted", "myapp_userprofile"."user_id", "myapp_userprofile"."updated", "myapp_userprofile"."real_name", "myapp_userprofile"."website", "myapp_userprofile"."job", "myapp_userprofile"."hobbies", "myapp_userprofile"."timezone", "myapp_userprofile"."about", "myapp_userprofile"."premium_counter", "myapp_userprofile"."company_name", "myapp_userprofile"."company_description", "myapp_userprofile"."company_website", "myapp_userprofile"."retailer_country", "myapp_userprofile"."avatar", "myapp_userprofile"."exclude_from_competitions", "myapp_userprofile"."default_frontpage_section", "myapp_userprofile"."default_gallery_sorting", "myapp_userprofile"."default_license", "myapp_userprofile"."default_watermark_text", "myapp_userprofile"."default_watermark", "myapp_userprofile"."default_watermark_size", "myapp_userprofile"."default_watermark_position", "myapp_userprofile"."default_watermark_opacity", "myapp_userprofile"."accept_tos", "myapp_userprofile"."receive_important_communications", "myapp_userprofile"."receive_newsletter", "myapp_userprofile"."receive_marketing_and_commercial_material", "myapp_userprofile"."language", "myapp_userprofile"."seen_realname", "myapp_userprofile"."seen_email_permissions", "myapp_userprofile"."signature", "myapp_userprofile"."signature_html", "myapp_userprofile"."show_signatures", "myapp_userprofile"."post_count", "myapp_userprofile"."autosubscribe", "myapp_userprofile"."receive_forum_emails" FROM "myapp_image" LEFT OUTER JOIN "myapp_apps_iotd_iotd" ON ("myapp_image"."id" = "myapp_apps_iotd_iotd"."image_id") INNER JOIN "auth_user" ON ("myapp_image"."user_id" = "auth_user"."id") LEFT OUTER JOIN "myapp_userprofile" ON ("auth_user"."id" = "myapp_userprofile"."user_id") WHERE ("myapp_image"."is_wip" = false AND NOT ("myapp_image"."id" IN (SELECT U0."id" AS Col1 FROM "myapp_image" U0 LEFT OUTER JOIN "myapp_apps_iotd_iotdvote" U1 ON (U0."id" = U1."image_id") WHERE U1."id" IS NULL)) AND "myapp_apps_iotd_iotd"."id" IS NULL AND "myapp_image"."id" < 372320 AND "myapp_image"."deleted" IS NULL) ORDER BY "myapp_image"."id" DESC LIMIT 1; QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- … -
How to upload multiple Images using DJango Rest Framework?
I am able to upload a single image with the following code. If I select multiple images then only the last image among the selected image is getting uploaded. models.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ( 'property_id', 'image', ) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ( 'property_id', 'image', ) views.py class ImageView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request): all_images = Image.objects.all() serializer = ImageSerializer(all_images, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, *args, **kwargs): file_serializer = ImageSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am a little new to Django. I want to loop over my array of images which is received in the request.data Can anyone tell me how to do it? -
I am unable to load django static files from css in html
I am unable to load static files from inline-css in html file, which is present in the templates file in the django app. For reference, the original file code is <a class="portfolio-item" style="background-image: url(img/portfolio8.jpg);" href=""> I am trying to import portfolio8.jpg that is originaly present in the img folder in static files in django. I changed the code to: <a class="portfolio-item" style="background-image: url({% static 'proj/img/portfolio8.jpg' %});" href=""> Doing this didnt work. It will be great if someone could help on how to load the img url from the style. -
Getting "too many values to unpack" error when adding choices to CharField
I'm trying to offer my users choices, but when I add a list of tuples to the charfield choices I get a "too many values to unpack" error. It seems Django won't allow me too offer my users more than 384 choices. This is an outrage. Does anyone know if there is a workaround for this? I need to offer about 120 more choices... -
cannot fix error "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet."
Hi I just started my Django project today and during my attempt to python manage.py migrate I got the following error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/danni/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/danni/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/danni/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/danni/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/danni/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/danni/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 12, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "/home/danni/.local/lib/python3.6/site-packages/django/db/migrations/autodetector.py", line 11, in <module> from django.db.migrations.questioner import MigrationQuestioner File "/home/danni/.local/lib/python3.6/site-packages/django/db/migrations/questioner.py", line 9, in <module> from .loader import MigrationLoader File "/home/danni/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 8, in <module> from django.db.migrations.recorder import MigrationRecorder File "/home/danni/.local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 9, in <module> class MigrationRecorder: File "/home/danni/.local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 22, in MigrationRecorder class Migration(models.Model): File "/home/danni/.local/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "/home/danni/.local/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "/home/danni/.local/lib/python3.6/site-packages/django/apps/registry.py", line 127, in check_apps_ready raise … -
Django form submit with ajax form.serialize()
views.py def login(request): password = request.POST.get('password') mobile = request.POST.get('mobile') user = authenticate(username=mobile, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect("/owner/?own=" + str(user.id)) login.html $('.login-form').on('submit', function(event) { event.preventDefault(); var form = $(this); $.ajax({ url: '/ajax/login/', type: "POST", data: form.serialize() success: function(data) { }); }); i'm getting error: Method Not Allowed (POST): / Method Not Allowed: / [20/Oct/2018 04:41:30] "POST / HTTP/1.1" 405 0 -
Attempting to add a class attribute to input element on django form.
I am trying to add a class attribute to some input elements on my Django form but I'm not sure how to do it specifically. Currently I just have a placeholder attribute, and I'd like to start adding classes/id's so that I can style the form. I have two questions. The first one is how would I go about adding a class/id attribute to the existing placeholder attribute(s) in the following code: forms.py class EditUserProfileForm(forms.ModelForm): class Meta: model = models.UserProfile fields = '__all__' widgets = { 'description': forms.TextInput(attrs={'placeholder': 'Motto'}), 'city': forms.TextInput(attrs={'placeholder': 'City'}), 'website': forms.TextInput(attrs={'placeholder': 'Website/Brand'}), 'phone': forms.TextInput(attrs={'placeholder': 'Phone Number'}), } and secondly, after I do this would I need to then makemigrations/migrate? From my understanding you need to migrate whenever a database level change has been made, but I'm not sure what that means entirely. Any insight is always greatly appreciated. Thanks -
None value passed on editing the form on HTML - Django
I am editing the Firtname and Lastname fetched from auth_User. When I edit the name and save, the None value is passed to the names. On verifying page source I dont see any error. form.py class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('first_name','last_name', 'email') view.py def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) if user_form.is_valid(): user_form.save() messages.success(request, 'Profile updated successfully!') else: messages.success(request, 'Error updating your profile!') else: user_form = UserEditForm(instance=request.user) return render(request, 'account/edit.html', {'user_form': user_form}) HTML <div class="form-row"> <label class="col-sm-2 control-label" placeholder="First Name">First Name:</label> <div class="col-sm-4"> <input type="text" class="form-control" id="first_name" value="{{ user_form.first_name.value }}"> </div> <label class="col-sm-2 control-label">Last Name:</label> <div class="col-sm-4"> <input type="text" class="form-control" id="last_name" value="{{ user_form.last_name.value }}"> </div> </div> -
How to make Admin for django-pushnotification to send custom messages?
I just want to make an admin where admin can send push notification to different users. I already have APN devices and FCM model (with registration_id). I want to make admin to send custom push notifications I am using django-push-notification module. -
How to upload Selenium python with django in the heroku, I am getting h12 error
I'm doing test python, selenium, django and heroku a quick query on google and return to the template I'm taking error timeout h12, all my applications are with the same error, I'm not sure how to configure this in my script. error: 2018-10-20T02:06:48.131091+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/" host=testeseleniu.herokuapp.com request_id=74b149 f3-48dc-4e1c-97f3-616d3564cc8c fwd="201.81.178.239" dyno=web.1 connect=1ms service=30000ms status=503 bytes=0 protocol=https View.py: from django.shortcuts import render from django.views import View from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import os class consuappView(View): def get(self, request): return render(request, 'consuapp/consulta.html') def post(self, request): chrome_exec_shim = os.environ.get("GOOGLE_CHROME_BIN", "chromedriver") chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = chrome_exec_shim chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') self.driver = webdriver.Chrome('/app/.chromedriver/bin/chromedriver', chrome_options=chrome_options) self.campo_cep_site = request.POST['cep'] self.campo_num_site = request.POST['num'] self.driver.get("https://www.google.com.br") wait = WebDriverWait(self.driver, 280) self.google(wait, self.campo_cep_site) self.driver.close() return render(request, 'consuapp/consulta.html', {'retorno_consulta': self.retorno_consulta}) def google(self, wait, campo_cep_site): wait.until(EC.element_to_be_clickable((By.ID, 'lst- ib'))).send_keys(campo_cep_site) wait.until(EC.element_to_be_clickable((By.ID, 'tsf'))).submit() form_emp = self.driver.find_elements_by_class_name('xpdopen') self.retorno_consulta = self.driver.find_element_by_xpath( '//* [@id="rhs_block"]/div/div[1]/div/div[1]/div[2]/div[2]/ div/div[2]/div/div/div/div[1]').text Buildpack: heroku/python https://github.com/heroku/heroku-buildpack-chromedriver.git https://github.com/heroku/heroku-buildpack-google-chrome In localhost it's working, time to consult is 5 seconds. only heroku crashed.