Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to redirect the page url when it fails?
I want to redirect the page when it fails, Accessing the page with this works fine http://192.168.0.114:8686/test/1/ http://192.168.0.114:8686/test/2/ but when I try to access this http://192.168.0.114:8686/test it throughs an error, when the error occurs it want the value as "page_no=1" urlpatterns = [ url(r'^', include(router.urls)), url(r'^test/(?P<page_no>\d+)/$', views.test.as_view(), name='test_page'), ] Page not found (404) Request Method: GET Request URL: http://192.168.0.114:8686/test Using the URLconf defined in couponer.urls, Django tried these URL patterns, in this order: ^ ^$ [name='api-root'] ^ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] admin/ ^ ^^p//$ [name='udemylinks-list'] ^ ^^p\.(?P<format>[a-z0-9]+)/?$ [name='udemylinks-list'] ^ ^^p//(?P<pk>[^/.]+)/$ [name='udemylinks-detail'] ^ ^^p//(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='udemylinks-detail'] ^ ^$ [name='api-root'] ^ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] ^pages/(?P<page_no>\d+)/$ [name='Pages'] ^html/(?P<page_no>\d+)/$ [name='index'] ^test/(?P<page_no>\d+)/$ [name='test_page'] The current path, test, didn't match any of these. -
Django - where can I find the output of print() statements in production?
Django - where can I find the output of print() statements in production? I'm using a Digital Ocean droplet, Ubuntu 16.04. I don't see print() output in access.log or error.log files. Is this something I need to set up manually? -
How do I retrieve specific objects from a model related to another model through a foreignkey?
I am building a django app which basically shows newsfeeds (a thematic + a series of news items). Thematics and items are manually entered in the DB through two models. These two models: a 'Feed' model, which describes a newsfeed thematic and a 'Feed_element' model, which describes news items which enter under a specific thematic (a 'feed'). The Feed_element is related to the Feed model through a Foreignkey. I'd like to get the feeds that respond to a criteria (front_feed = True, see attached models code) and the accompanying feed_elements, which I thought I could wove together in the view with a select_related(). But this doesn't work. I cannot figure the view syntax. MODELS # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Feed(models.Model): feed_name = models.CharField(max_length = 200, default = "country_name") feed_current = models.TextField(max_length = 10000, default = "feed_current") feed_country = models.CharField(max_length = 200, default = "feed_country") feed_front = models.BooleanField(default = False) def __str__(self): return self.feed_name class Feed_element(models.Model): parent_feed = models.ForeignKey(Feed, on_delete = models.CASCADE, related_name = "elements") element_date = models.DateField() element_short = models.TextField(max_length = 200, default = "element_short") element_long = models.TextField(max_length = 200, default = "element_long") def __str__(self): return … -
Django geoip2 + Maxmind working locally, but not in production?
I'm able to get a response object and render it to the page locally, but on my live site it doesn't work. I'm using Maxmind's binary database, which is the GeoLite2-City.mmdb file in my project folder. This also works in my website's Ubuntu 16.04 terminal: import geoip2.database reader = geoip2.database.Reader('/home/jake/project-main/project/GeoLite2-City.mmdb') ip = request.META.get('REMOTE_ADDR', None) location_lookup_response = reader.city(ip) print(location_lookup_resonse) However, it doesn't work on the site. Any thoughts here are appreciated. -
django-wiki: why does it have the root article?
I'm new to working with django wiki (and also Django) -- why is the root article in django wiki set up the way it is? Ideally I would like my wiki to have multiple articles at the first level, rather than starting with a single root article. With the way it works currently, I would have to create a root article whose only purpose is to branch out to the real articles. -
Serializing or passing json objects into Ajax
The Json object was returned and I want to extract the data in JavaScript In the sense of how to pass on the loop fields and extract data def For_Sale_Listing(request,id): try: listing = Listing.objects.filter(pk=id) listing_json = serializers.serialize("json", listing) except Listing.DoesNotExist: raise Http404('places not found!') data = {"listing_json": listing_json} return JsonResponse(data) $.ajax({ url: "/For-Sale-Listing"+"/" + parseInt(data[0]), type: "GET", data: {'Subscription': 1}, success: function(data) { console.log(JSON.parse(data.listing_json)); }, error: function(xhr, status, error) { } }); -
Django - Add extra field to choices
I want to have a choice, with three elements: 1: This will be saved in the database 2: This will be used as a human-readable representation 3: This will be used as an extra information fur humans. (db_value, represantation, description) I tried to add that using a custom widget, but I get this error: ValueError: too many values to unpack (expected 2) from django.forms import widgets This is my code: class ExplainingChoiceWidget(widgets.Select): description = "A choice field, which explains the choices" template_name = "django/forms/widgets/explaining_choice.html" def __init__(self, choices, *args, **kwargs): prepared_choices = [ [choice[0], choice[1]] for choice in choices ] self.choices = prepared_choices print(prepared_choices) super().__init__(choices=prepared_choices, *args, **kwargs) And this is my choices: comment_user_visibility_choices = [ ["public", "Öffentlich", "Dein Vorname und dein Personentyp sind öffentlich sichtbar"], ["limited", "Beschränkt", "Nur dein Personentyp ist öffentlich sichtbar"], ["anonymous", "Anonym", "Der Kommentar zeigt deine Person nicht an"] ] -
Django Channels: add/remove workers dynamically
Django channels adds the concept of channels for things like websockets for real time updates in a browser. The example app in the tutorials demonstrates a chat app where consumers can send data to and from a channels group without any centralized source. But how would this work in a scenario with a data source, i.e. a stocks app? This would be a one-to-many system: a single data source broadcasting data on a channels group with many consumers. In order for this type of system to work, each channels group would require a worker, but from the channels docs it seems that workers must be a static thing, they cannot be dynamically added or removed to channels. Is this type of worker system possible in Django Channels and if so how? -
Persistent MongoDB Connection With Django
I am currently using (or hoping to use) both PostgreSQL and MongoDB for my Django project. When it comes to MongoDB I've been looking at PyMongo to make the connection, and add/edit info using Python. Most likely I will be calling PyMongo in my views.py to read/insert/edit data from MongoDB. For the sake of this question, let's say I have a view called worksheet, which querys some data from MongoDB relevant to the current user. However I would like to maintain a persistent connection to the database so that I do not have to make a new connection every time a user visits the worksheet view. Is there any way I could make a persistent connection so I am not wasting time/resources making new connections to MongoDB every time? Thanks. -
How to display a Python list of strings that contains HTML and JavaScript in a template with JS
I have a python list that contains a list of strings. Those strings contain HTML and JavaScript. Right now, I am using sentences = json.dumps(l) in Django view, then in the template I use {{sentences|safe}}, it works for some strings, but it breaks on the strings that contain lots of HTML and JavaScript. How do I fix this problem? Thank you for your help. I tried JSON.parse(sentences), {{sentences|escapejs}}, {{escape|safe}} # in django view sentences = json.dumps(l) return render(request, 'detail.html', { }) // in template, attempt to pass the jsonified python list to js array var random = {{sentences|safe}}; SyntaxError: "" literal not terminated before end of script 73:78:35396 SyntaxError: unexpected token: identifier 73:78:12 SyntaxError: unexpected token: identifier 73:78:4 SyntaxError: unexpected token: identifier 73:78:20 SyntaxError: unexpected token: identifier 73:78:20 -
Two ways of including an app in INSTALLED_APPS
Say I have an app called polls. What is the difference between including an app in INSTALLED_APPS like this 'polls.apps.PollsConfig' and just specifying the app's name ( 'polls')? The official Django tutorial recommends the former. -
Save Django ModelForm with CheckboxSelectMultiple with no boxes checked
A Django Form using a CheckboxSelectMultiple widget posts back nothing for the field using the CheckboxSelectMultiple widget if no boxes are checked. class AlarmForm(forms.ModelForm): class Meta: model = models.Alarm fields = ['phone_contacts', 'disabled'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user = self.instance.user self.fields["phone_contacts"].widget = forms.widgets.CheckboxSelectMultiple() self.fields['phone_contacts'].queryset = user.phonecontact_set If the user viewing the form checks no checkboxes, the idea is that the model's phonecontact_set field ( a ManyToManyField) should be cleared. Instead, if no boxes are check, that field isn't saved at all. This is apparently because unchecked check boxes include no values in the form POST in the web browser. Still, it seems there must be a way to make Django do this without completely re-implementing the save functionality, but I can't seem to find the Django way to do this.. -
Pycharm can't find Django app 'users' when running tests
I was handed a project which uses Django and Docker, but when I run Django tests Pycharm always seems to have problem finding the users application. Other people in the project have it running without problems but even though we tried to copy their settings, it wouldn't work. I also downgraded to their exact Pycharm version without success. What could be wrong? I have Docker desktop running without any problem. It's able to create containers and all that. I've also included it in Pycharm with success. I've also created an interpreter through Docker-compose with a valid .yml file. This file is my colleagues. I've of course added it as my project interpreter. I've set up a Django test configuration with appropriate interpreter and with an empty target field so that all applications in INSTALLED_APPS are run, as per documentation. Still, the module 'users' cannot be found. Passing in DJANGO_SETTINGS_MODULE=config.settings.local to the test configuration yields the same error. However, when I run from the terminal, all works as expected. What might be the problem here? -
OperationalError at /admin/blogapp/post/220/change/ no such table: blogapp_post_likes?
I've made a django blog app and its working fine. Now I'm trying to add a like feature to the blogs by the users. I added a likes field in my Post model but as soon as I ran the makemigrations and migrations command and went into my django-admin and click on the Post model, I got this -no such table: blogapp_post_likes. I'm learning from this tutorial and he also did the same thing but his migrations worked. I've tried deleting the migrations folder from the project prior to the makemigrations and migration command but its not working. Here's my models.py file- from django.db import models from django.urls import reverse from django.utils import timezone from django.contrib.auth.models import User from datetime import datetime, timedelta from PIL import Image class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) contact = models.CharField(max_length=12,blank=True) image = models.ImageField(upload_to='profile_pictures', default='default.png') description = models.CharField(max_length=100,blank=True,null=True) def __str__(self): return f'{self.user.username}' class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True) likes = models.ManyToManyField(User,related_name='post_likes',blank=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('blogapp:post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) author = models.CharField(max_length=100) text = models.TextField(max_length=264) created_date = models.DateTimeField(default=timezone.now) … -
custom redirect to /admin/app/model/?q='search_criteria'
Python 3.6 Django 2.2 In django admin.py I have a button that have function of url redirection. What I need is when I press that button is to redirect to: /admin/app_label/model_label/search_criteria. looks like: "ip/app/model/?q='criteria'" Created buttons code: return format_html( '<a class="button" href="{}">Inventory</a>&nbsp;' '<a class="button" href="{}">Log Sync</a>', reverse('admin:Inventory_specs_change', args=[obj.id]), #The problem is here: #I need here redirect to "/admin/Inventory/sync/?q=obj.name" redirect('/admin/Inventory/sync/?q=obj.name') ) I tried a lot, but nothing helps. So, how can I achieve this redirection to app_model with search_criteria? -
Obscure fields from django GET request
I am fetching the relatedfiles_set in my ControlsSerializer, but I would like to obscure the uploaded_by_user_id and organization_id for security purposes. I still need those fields in the RelatedFileSerializer for when I create new relatedfiles, but I don't want them to show during GET requests. Is there any way I can hide these fields without creating separate serializers for these two types of requests? class RelatedFileSerializer(serializers.ModelSerializer): class Meta: model = RelatedFiles fields = ('control', 'file', 'uploaded_by_user_id', 'organization_id', 'note', 'uploaded_at') class ControlsSerializer(serializers.ModelSerializer): relatedfiles_set = RelatedFileSerializer(many=True, read_only=True) class Meta: model = Controls fields = ('relatedfiles_set', 'id', 'sorting_id', 'requirement', 'requirement_section', 'requirement_subsection',) -
How to insert list of integers into a string for a database query - Python 3
I am trying to use the cursor execute to make a query in a django application, but when I pass the list into the query string it comes with quotation marks and returns the following error: psycopg2.DataError: invalid input syntax for integer: "139,212,933,2303,2613" LINE 1: ...ados_ibge.sociodemografia_rmc sd WHERE sd.gid IN ('139,212,9... This is the code ive been working on so far.. if gids: with connection.cursor() as cursor: g = ','.join(gids) cursor.execute("SELECT * FROM poi.farmacias_rmc f, dados_ibge.sociodemografia_rmc sd WHERE sd.gid IN (%s) AND ST_Intersects(sd.geom, f.geom) = true", [g]) rows = cursor.fetchall() -
Django: unique constraint with a DESC order index
I'm trying to add a unique constraint with a desc index. I can create a desc index on two fields like that : class Meta: indexes = [ models.Index(fields=['some_field', '-date']), ] And I can create a unique constraint like this : class Meta: constraints = [ models.UniqueConstraint( fields=('some_field', 'date',), name='core_message_uniq_mmsi_time' ) ] This will create a unique index, but the order won't be the good one and for some reason using a '-date' in the UniqueConstraint does not seem to do the trick. Is there something I'm missing, or is it required to have two indexes, one with the unique constraint and another one with the correct order ? Thanks ! -
How to get user current location with react native and django
need your helps guys how get user current location with react native and django. Sample code if possible -
Is there any ORM for finding latest output for component and environment
Unable to get the value correctly while i am trying annotate in Django ORM query.Please can anybody help with the correct ORM? I am creating a deployment matrix Dashboard using django. Here this is a dashboard for deployment detail for deployment happens in some environment through jenkins the input to the models will be given manually but we need a output in html that env name - componens(as per environmnt) details of the deployment according to the env and compoment below i have showed you what output i need for my project Please help dtls = deploy_dtl.objects.values('env','comp','deploy_version').annotate(max_date=Max('updated_dt')).order_by('env','comp')``` This the table data under which i am querying here 1 env can have multiple comp and i component can have multiple deployment but we want to get the latest 'updated_dt' regarding the group of components. +----+--------+---------+----------------+---------------+--------------------+----------------------------+--------------+--------------+ | id | env_id | comp_id | deploy_version | deploy_status | deploy_reqster_nme | updated_dt | updated_by | remarks | +----+--------+---------+----------------+---------------+--------------------+----------------------------+--------------+--------------+ | 2 | 1 | 1 | 1.00024 | Deployed | Arun sahoo | 2019-09-03 12:50:41.934499 | Amit Samanta | NIL | | 1 | 1 | 1 | 1.00023 | Deployed | Arun Sahoo | 2019-09-03 10:56:52.472392 | Amit samanta | Amit samanta | | … -
Laravel and Python Integration
I want to integrate a web application built in PHP framework Laravel to a desktop raw Python Code. I am working for my University project i.e., Student Attendance Management System using Face Recognition. I've already created School Management System that contain Attendance Module in it. Now when I created Python desktop based Facial Recognition Attendance System so I want to link both of these system in a way that when face is recognised by the Python system it'll mark attendance in the database and on Laravel System ID-CARD of Student will popup as this student is checked in the school or university. I tried it by connecting both systems to same database, and used pusher, echo, and axios to make it realtime. But problem is Student ID-CARD only pops-up when attendace is marked from the web app (laravel app). When python system marks attendace it only displays when web-app is refreshed. NOTE: Reason of doing such complicated thing is, I can only code in these two languages. Raw Python and Laravel... Please Help Me Out :( -
Where to up django app startup code that must interact with the database?
I have some django code that needs to run once when my app is loaded. This code also needs to write to the database. This SO question "Where to put Django startups code?" recommends using AppConfig.ready for startup code. However, the docs for the ready function clearly warn against interacting with the database: Although you can access model classes as described above, avoid interacting with the database in your ready() implementation. This includes model methods that execute queries (save(), delete(), manager methods etc.), and also raw SQL queries via django.db.connection. Your ready() method will run during startup of every management command. For example, even though the test database configuration is separate from the production settings, manage.py test would still execute some queries against your production database! Is there some later startup hook I should use for code that does need to update the database? -
TypeError: cannot unpack non-iterable NoneType object --> But object exists?
I am going mad over some code. Executing a program that is made to generate product suggestions randomly always yields to the error TypeError: cannot unpack non-iterable NoneType object Yet I cant seem to see, where a NoneType object is returned. All print statements clearly indicate that I return an object and a Boolean. Unfortunately, it's quite a bit of code and I can't seem to reproduce the error with less code. @staticmethod def generate_random_product(variation): product_options = Product.objects.all() if not product_options: raise ValidationError( 'PRODUCT CREATION FAILED HARD COULD NOT ' 'GENERATE RANDOM PRODUCT FOR: ' + variation.name + '... PLEASE DELETE' 'ALL DELIVERIES THAT WERE CREATED TODAY' ) random_int = random.randint(0, (product_options.count() - 1)) return product_options[random_int], True def generate_random_product_from_category(self, variation, count): if count >= 10: return self.generate_random_product(variation, count) category = variation.package.category product_options = category.product_set.all() if not product_options: return self.generate_random_product(variation) random_int = random.randint(0, (product_options.count() - 1)) return product_options[random_int], True def generate_random_product_from_variation(self, variation, count): if count >= 5: return self.generate_random_product_from_category(variation, count) product_options = variation.product_set.all() if not product_options: return self.generate_random_product_from_category(variation) random_int = random.randint(0, (product_options.count() - 1)) return product_options[random_int], False def turn_variation_into_product(self, variation, delivery, count): if count < 15: # STEP 1: generate a random product random_product, failed_auto = self.generate_random_product_from_variation(variation, count) print(random_product) try: self.turn_variation_into_product(variation, … -
Docker+Django+SECRET_KEY: regenerate?
Imagine you create a docker-compose.yml with Django and a bunch of code and use an environment variable to configure the SECRET_KEY in settings.py. If you distribute that Docker image you won't share the SECRET_KEY. What SECRET_KEY should someone use when they deploy your Docker image? They can't make up their own SECRET_KEY right? According to the documentation, changing the secret key will invalidate: All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash(). All messages if you are using CookieStorage or FallbackStorage. All PasswordResetView tokens. Any usage of cryptographic signing, unless a different key is provided. What's the best way to 'renerate' a secret key after deploying a Docker container with a bunch of code that you created? (I have searched and searched but feel like I'm searching for the wrong things or completely missed something :-) -
How to set up the Django model architecture for unknown properties?
I have a Person model. class Person(models.Model): name_first = models.CharField(max_length=100) name_middle = models.CharField(max_length=100, null=True, blank=True) name_last = models.CharField(max_length=100) date_birth = models.DateField(null=True, blank=True) date_death = models.DateField(null=True, blank=True) I'm trying to extend it to different roles in the music world: a composer, a performer, and a patron. A person can be one, two or all three roles. If a person is a performer, I also need to assign one or more instrument for that person. You may not know if a person is a performer at the time of instantiation. Or their roles can change over time. I want to be able to search and display that a person is a composer, pianist and a patron, if he's all three. For example: Beethoven is a conductor, composer, and pianist. My initial thought on implementation is to inherit the Person class. class Composer(Person): pass class Performer(Person): instrument = models.CharField(max_length=100, blank=True) performer_type = models.CharField(max_length=100, blank=True) //conductor, performer class Patron(Person): pass Question 1: should I use some sort of abstract model instead? If so, how would I go about it? Question 2: how can I search for a person and know whether they are a composer, patron and/or performer and the kind of performer they …