Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid Syntax error in URLS.py in DJango
Getting following error in my urls.py Django/Projects/first_project/simple_app/urls.py", line 7 re_path(re'^details/(?P<id>\d+)/$', views.details), ^ SyntaxError: invalid syntax urls.py is as follows : from django.contrib import admin from django.urls import path, re_path, include from . import views urlpatterns = [ re_path(re'^details/(?P<id>\d+)/$', views.details), path('', views.index) ] -
Incorporating AGI Cesium into Django HTML
I've been trying to create a Cesium viewer in my html on Django. I can't seem to incorporate the widgets, images, styles, etc. I'm not exactly sure how to get the entire build folder into the static folder in my django project since all the necessary widgets and things needed by Cesium are located in that particular file. I tried to do the @import url(Build/Cesium/Widgets) but it did not work. Any help is greatly appreciated! Here is what I have so far: Index.html <html> <head> <title>Lab00</title> </head> <body> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'mystyle.css' %}" /> <style> @import url(/Build/Cesium/Widgets/widgets.css); </style> <!-- Use correct character set. --> <meta charset="utf-8"> <!-- Tell IE to use the latest, best version. --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Make the application on mobile take up the full browser screen and disable user scaling. --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> {% load staticfiles%} <script src= {% static "js/Cesium.js" %} type="text/javascript"></script> <div id="cesiumContainer"></div> <script> var viewer = new Cesium.Viewer('cesiumContainer'); </script> </body> </html> mystyle.css body { background-color: lightblue; color:purple; font-family: "Tahoma"; } #cesiumContainer { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; } h1 { color: navy; background-color: green; margin-left: 20px; … -
One to One relationship seriazling in django
I have the following User, class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) username = models.CharField(null=False, unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And the following UserProfile model, class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, ) level = models.CharField(default="Noob", max_length=255) reputation = models.IntegerField(default=0) status = models.CharField(max_length=255, null=True, blank=True) The User has a one to one relationship with Profile. This is the UserSerializer, class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) location = LocationSerializer(read_only=True) profile = UserProfileSerializer(read_only=True) class Meta: model = models.User fields = ( 'id', 'email', 'mobile', 'username', 'full_name', 'password', 'is_active', 'profile', ) And this is the profile serializer. class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = models.UserProfile fields = ('level', 'reputation', 'status', '',) The issue is that in the serialized output for the user there's no nested profile data.How do I fix this. Any help appreciated. -
Django and Folium integration
Django newbie here: my aim is to integrate Folium to an html page. so what I have at the moment: polls/views.py def show_map(request): #creation of map comes here + business logic m = folium.Map([51.5, -0.25], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m) context = {'my_map': m} return render(request, 'polls/show_folium_map.html', context) polls/urls.py urlpatterns = [ path('show_my_map', views.show_map, name='show_map'), ] and show_folium_map.html <h1>map result comes here</h1> {{ my_map }} problem is that I get the 'to_string' value of the map (I promise you I saw that coming). So how can I integrate the map in such way that I can actually see the map and also define the size? -
Reordering database after deleting an element in Django Python
Suppose I have 5 elements in my Django model user. Now I have deleted 4th element like this user.objects.filter(id=4).delete() Now The ID's after deleting will be 1,2,3,5. I like to reorder them like this : 1,2,3,4. How can I achieve this ? Any Django method or python code or sql code ? -
djangoappengine cannot find app.yaml even file exists
djangoappengine raised "runtimeError unable to find app.yaml" even file is already exist on path. Thank you in advance -
Sanitizing user inputs in Django
Wondering how to go about sanitizing user inputs in django. I currently have a views and serializer file but I am unsure of how to implement the process within these two files. -
what is better and what to use?
Hey I understands that Django-cms is for small website but my questions is that, can I make other users login post stuff like normal django? does they have the same features?, what should I use if I want dynamic website, use python plugins and let users log in and out. -
Django Model set @property with filter and show it on template
I have case that need to count and show user that doesn't have a blog. here my views.py class Blog(models.Model): desc = models.TextField(blank=True, null=True) user = models.ForeignKey(Employee, null=True, on_delete=models.CASCADE, related_name='blogs') @property def DOESN_HAVE_BLOG(self): blog = Self.Blog.all().values_list('user', flat=True) value = Self.User.exclude(id__in=blog) return value here mytemplate.html {{ DOESN_HAVE_BLOG.count }} but its doesn't work -
Django complex query for OR
I'm using django 1.10 I've created this query which works for me: filters_qs = filters_qs.filter( Q( user__in=[cache.user for cache in caches], status_id__in=[ Status.Open['id'], Status.Empty['id'] ], revision=0 ) | Q( user=None, status_id__in=[ Status.Open['id'], Status.Empty['id'] ], revision=0 ) ) I used the 'OR' because I'm looking for a result where the query set is either None or in the list. But - it looks not so 'pythonic'... it repeats the same code for minor change. Is there another way? for example something like - (doesn't work) Q( user__in=[cache.user for cache in caches] + [None], status_id__in=[ Status.Open['id'], Status.Empty['id'] ], revision=0 ) Thanks. -
How to place a package on the PYTHONPATH?
I want to add this package to my project https://django-el-pagination.readthedocs.io/en/latest/start.html. The documentation tells me to place the distribution on the PYTHONPATH. What do they mean and how am I supposed to do that? -
Wagtail "has no field name"
I'm fairly new to wagtail so please excuse any glaring mistakes. I'm attempting to create a new page type called PortfolioItemPage. I am getting the following error when trying to use runserver, makemigrations or migrate: Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x10900f048> Traceback (most recent call last): File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/db/models/options.py", line 566, in get_field return self.fields_map[field_name] KeyError: 'project_title' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/admin/checks.py", line 62, in get_form_class_check edit_handler = cls.get_edit_handler() File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/utils/decorators.py", line 53, in __call__ return self.value File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/utils/decorators.py", line 49, in value return self.fn(self.cls) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 768, in get_edit_handler return edit_handler.bind_to_model(cls) File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 131, in bind_to_model new.on_model_bound() File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 276, in on_model_bound for child in self.children] File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 276, in <listcomp> for child in self.children] File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 131, in bind_to_model new.on_model_bound() File "/Users/jlspencergarlitz/.venvs/jls-jmSlWnDA/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 276, in on_model_bound for child … -
attrs for widget isn't working, Issue with "from django.contrib.auth.models import User"
attrs isn't applied, not even label and placeholder. basically, can't apply any css to the form fields. works alright for other classes. from django import forms from django.contrib.auth.models import User from .models import Profile attr_dict = {'class': 'form-control'} class LoginForm(forms.Form): username = forms.CharField(label='Password', widget=forms.TextInput(attrs=attr_dict)) password = forms.CharField(widget=forms.PasswordInput(attrs=attr_dict)) class Meta: model = User fields = ('username', 'password',) -
Django doesn't find file just in remote server
I have a project in Django where I have a function that read a file. In my local enviroment using virtualenv all it's ok, it reads the file. But, when I put it in our remote server (using LINUX Ubuntu + Apache 2), it show's that Python can't find the file. What I'm doing wrong? utils.py def set_vehicles_negotiations(self): # This method will get all current negotiations that means and set it in the database with open("reports/dash_diversos.csv", 'rt', encoding='utf8') as csvfile: ... views.py ... def dashboard(request): csvReaders = CSVReaders() csvReaders.set_vehicles_negotiations() settings.py ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # This line exist's only in the remote server Directory structure: mydashboard - dashboard -- utils.py -- views.py - reports -- dash_diversos.csv The error message: [Errno 2] No such file or directory: 'reports/dash_diversos.csv' I already search in various websites as well it StackOverflow. I just don't understand why it works in my local machine and not in my server. -
How to use one db to run the django service and other to fetch data
i have an existing application data base from which my web site should only fetch the data according to user input. Added database details in the settings.py file and I tried python manage.py integratedb and get the all the 300+ tables came off to my models.py file. I was never able to do python manage.py runserver it threw a million errors. Now i found a work around but i need your opinion on this. I added the default server into the settings.py and using it i was able to run the server. settings.py looks like this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', }, 'user': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME' : 'test', 'USER' : 'testuser', 'PASSWORD': 'readonly', 'HOST' : '10.20.30.40', 'PORT' : '5446', } } Now can i access the user db to fetch data from my form? for example views.py looks like this from django.shortcuts import render_to_response from .models import TestCases from django.shortcuts import HttpResponse from django.http import JsonResponse from django.forms.models import model_to_dict from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def index(request): posts = TestCases.objects.all()[:10] return render_to_response('index.html',{'posts':posts}) where TestCases is a class name from the models.py file. Now when i click the button to retrieve … -
Kubernetes + Django / PostgreSQL - How do I specify HOST of my PostgreSQL Database when I deploy it to Kubernetes Cluster
I am having a lot of issues configuring My Dockerized Django + PostgreSQL DB application to work on Kubernetes Cluster, which I have created using Google Cloud Platform. How do I specify DATABASES.default.HOST from my settings.py file when I deploy image of PostgreSQL from Docker Hub and an image of my Django Web Application, to the Kubernetes Cluster? Here is how I want my app to work. When I run the application locally, I want to use SQLITE DB, in order to do that I have made following changes in my settings.py file: if(os.getenv('DB')==None): print('Development - Using "SQLITE3" Database') DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR,'db.sqlite3'), } } else: print('Production - Using "POSTGRESQL" Database') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'agent_technologies_db', 'USER': 'stefan_radonjic', 'PASSWORD': 'cepajecar995', 'HOST': , #??? 'PORT': , #??? } } The main idea is that when I deploy application to Kubernetes Cluster, inside of Kubernetes Pod object, a Docker container ( my Dockerized Django application ) will run. When creating a container I am also creating Environment Variable DB and setting it to True. So when I deploy application I use PostgreSQL Database . NOTE: If anyone has any other suggestions how I should … -
Getting "AttributeError: 'ManyToManyField' object has no attribute 'm2m_field_name'" When trying to add placeholders to auth_views.login
I'm trying to add a placeholder to my built-in authentication login form. I added a form to my forms.py: class loginPlaceHolderForm(AuthenticationForm): username = forms.CharField(widget=TextInput(attrs={'class':'validate','placeholder': 'Email'})) password = forms.CharField(widget=PasswordInput(attrs={'placeholder':'Password'})) Then I added that to my the authentication_form attribute via kwargs here: url(r'^$',auth_views.login, name='login',kwargs={'authentication_form':loginPlaceHolderForm}), The 'authentication_form' attribute is mentioned here: https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.views.LoginView Why would I be getting this error and how would I fix this? -
Hashtags feature in django
I am building an instagram clone and i want to implement this feature. Suppose A user uploaded an Image and its descriptions goes as follows: This is me #HappyTimes #tbh #helloall #blogger #writer I want that all the hashtags automatically converts to links. Like there should be no separate field for image description and hashtags. User write the description and hashtags gets converted. any way to implement it?? Currently, I have a model for User, UserProfile and Image. Image will be connected to user via foreign key. -
Local env using Heroku, Django, Postgres and Docker: server does not support SSL
I'm trying to configure a local environment with: Python 3.6/Django 1.11 installed locally on mac OS PostgreSQL 10 docker container on this mac (official docker image) I use django-heroku package so in my settings.py, the database configuration is one line: settings.py file: import django_heroku django_heroku.settings(locals(), databases=True, .....) .env file: DATABASE_URL=postgres://root:hudiroot@127.0.0.1:5432/fugodb When I run a heroku local:run python manage.py runserver command, I get an error: django.db.utils.OperationalError: server does not support SSL, but SSL was required After digging into django_heroku source code, I noticed this line: dj_database_url.parse(url, conn_max_age=MAX_CONN_AGE, ssl_require=True). I think this ssl requirement seems to be the problem here. What should I do? -
Django Custom Migration Not Executing
So I added a new "status" field to a django database table. This field needed a default value, so I defaulted it to "New", but I then added a custom migration file that calls the save() method on all of the objects in that table, as I have the save() overridden to check a different table and pull the correct status from that. However, after running this migration, all of the statuses are still set to "New", so it looks like the save isn't getting executed. I tested this by manually calling the save on all the objects after running the migration, and the statuses are updated as expected. Here's the table model in models.py: class SOS(models.Model): number = models.CharField(max_length=20, unique=True) creator = models.ForeignKey(Profile, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, related_name="customer", on_delete=models.CASCADE) end_user = models.ForeignKey(Customer, related_name="end_user", on_delete=models.CASCADE) title = models.CharField(max_length=100) template = models.ForeignKey(Template, on_delete=models.CASCADE) latest_version = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=False) final = models.BooleanField(default=False) # the default="New" portion is missing here because I have a migration to remove it after the custom migration (shown below) that saves the models status = models.CharField(max_length=20) def __str__(self): return self.number + ' - ' + self.title def save(self, *args, **kwargs): self.status = self.history_set.get(version=self.latest_version).status if … -
How to annotate field without duplicate fields django
So I basically have this simple model: class BaseLesson(models.Model): YOUTUBE_VIDEO = '0' TYPE_CHOICES = ( (YOUTUBE_VIDEO, 'youtube-video'), ) type = models.CharField( max_length=10, choices=TYPE_CHOICES, default=MARKDOWN, verbose_name=_('type')) shown_users = models.ManyToManyField( User, related_name='lessons', verbose_name=_('shown users'), blank=True) objects = managers.BaseLessonManager() There is a many-to-many relationship with the User model in shown_users And I wanna annotate the is_shown status based on the many-to-many table, so I did this: class BaseLessonManager(InheritanceManager, CachingManager): def get_lesson_with_is_shown(self, user): shown_user_case = django_models.Case( django_models.When(shown_users__id=user.id, then=django_models.Value(True)), default=django_models.Value(False), output_field=django_models.BooleanField()) return self.get_queryset().annotate( is_shown=shown_user_case) The problem with this is that if user1 and user2 saw the same lesson it will be duplicate, for example: +-----------------+-----------+ | lesson_id | user_id | +-----------------+-----------+ | 1 | 1 | | 1 | 2 | | 1 | 3 | +-----------------+-----------+ For such case, I will get these duplicated lessons: { "title": "creating wireframe", "slug": "creating-wireframe", "type": "2", "markdown_url": "http://www.coretabs.com/1/1", "is_shown": true }, { "title": "creating wireframe", "slug": "creating-wireframe", "type": "2", "markdown_url": "http://www.coretabs.com/1/1", "is_shown": false }, { "title": "creating wireframe", "slug": "creating-wireframe", "type": "2", "markdown_url": "http://www.coretabs.com/1/1", "is_shown": false }, So it's checking each related lesson field in the SHOWN_USERS table... sample photo: https://imgur.com/GJCPWjk I added an exclude expression to get rid of the extra lessons: return self.get_queryset().annotate( is_shown=shown_user_case).exclude( django_models.Q(is_shown=False) … -
DjangoViewflow - Not executing the complete flow
I've a workflow consisting of multiple nodes. @frontend.register class Flow1(Flow): process_class = CreationProcess start = ( flow.StartFunction(this.create) .Next(this.credit_line) ) credit_line = ( flow.Handler(this.cibil) .Next(this.seynse_score) ) score = ( flow.Handler(this.seynse) .Next(this.score) ) check_score = ( flow.If(lambda activation: activation) .Then(this.send_task) .Else(this.end) ) send_task = ( flow.Handler( this.send ).Next(this.end) ) end = flow.End() I run the flow like this:- Flow1.start.run() The problem that I'm facing is that it only runs the start node. The following nodes are not executed. Why? -
CMS (Python/Django) user enter a Weblink on the Create Article page. How is this done?
I am new to coding and this is my first attempt at making a CMS in (Python/Django) so this may be a simple question: Along with (title, body, thumb) I want the user to be able to enter a Weblink on the Create Article page. How is this done? -
Django DISTINCT issue related to database
In my database I have a report_id that is 100, but it has two parts to the report_id which have nothing to do with my application. I was able to use .distinct() in the example below. Which worked great at one point. In the example below my data returns correctly in my form, but I need to POST the data with an ID that doesn't exist in this first example. reportaccess = QvReportList.objects.filter(report_id__in= reportIds).values_list('report_name_sc', flat = True).distinct() I had to change my query set to the following to allow the report_id to POST to the next view. currreportaccess = QvReportList.objects.filter(report_id__in= reportIds).distinct() My problem is because I no longer have values_list with a single field as flat. It's coming back as two rows as distinct. My HTML is defined as the following: {% for app in currreportaccess %} <li> <input type="checkbox" name="current_report" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} Is it possible to get a distinct in this situation? If so, how should I go about it? I've added my model for the table QVReportList. class QvReportList(models.Model): qv_dept_id = models.CharField(db_column='QV_Dept_ID', max_length=100) # Field name made lowercase. report_id = models.CharField(db_column='Report_ID',primary_key=True, max_length = 100, serialize=False) # Field name made lowercase. report_name … -
How to pass in user input into Custom User Model in Django
I have a custom user model that I need to add an extra field to. The problem I have is that the information needed is user input from the registration page. This is the code from the form: team = forms.ChoiceField(choices=teamChoices) This is my user model: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() I need to add something like this: groups = 'team' But I don't know how I would get that information to my model. My user model is in models.py and my registration form is in forms.py.