Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
psycopg2.OperationalError: FATAL: role "postgresql" does not exist
I am a postresql novice. When I was ready to migrate INSTALLED_APPS in 'settings' to database,there appeared the following error: psycopg2.OperationalError: FATAL: role "postgresql" does not exist and I have displayed the full exception message: c:\fanhuaxiu\Scripts>activate (fanhuaxiu) c:\fanhuaxiu\Scripts>cd .. (fanhuaxiu) c:\fanhuaxiu>cd fhx (fanhuaxiu) c:\fanhuaxiu\fhx>python manage.py migrate Traceback (most recent call last): File "C:\fanhuaxiu\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\fanhuaxiu\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\fanhuaxiu\lib\site-packages\django\db\backends\postgresql\base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "C:\fanhuaxiu\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: role "postgresql" does not exist It has taken me nearly 2 hours to find a solution and failed 233333. Thanks in advance. -
how to avoid circular django model import?
I have these models below # user profile models file from ad.models import FavoriteAd class UserProfile(models.Model): def get_user_favorite_ad(self): return FavoriteAd.objects.filter(fav_user=self) # ad models file from user_profile.models import UserProfile class FavoriteAd(models.Model): fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE) I have tried using these but it give me the NameError UserProfile not found # ad models files class FavoriteAd(models.Model): fav_user = models.ForeignKey('user_profile.UserProfile', blank=False, on_delete=models.CASCADE) Also tried these as well still got error that model are not ready # ad models files from django.apps import apps UserProfile = apps.get_model('user_profile', 'UserProfile') class FavoriteAd(models.Model): fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE) -
Relating a model on a foreign key
I have the following custom User model. It has a field coid that i'd like to relate to my facility dimension table. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_cfo = models.BooleanField(default=False) facility = models.CharField(max_length=140) officename = models.CharField(max_length=100) jobdescription = models.CharField(max_length=140) positioncode = models.CharField(max_length = 100) positiondescription = models.CharField(max_length=140) coid = models.CharField(max_length=5) streetaddress = models.CharField(max_length=140) title = models.CharField(max_length=100) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); def get_short_name(self): return self.username I've defined the foreignkey in my Facility_Dimension table, but it's trying to create the relationship on formattedusername. class FacilityDimension(models.Model): unit_num = models.CharField(db_column='Unit_Num', max_length=5, blank=True, null=True) # Field name made lowercase. company_code = models.CharField(db_column='Company_Code', max_length=1, blank=True, null=True) # Field name made lowercase. coid = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='Coid',primary_key=True, serialize=False, max_length=5) # Field name made lowercase. coid_name = models.CharField(db_column='COID_Name', max_length=50, blank=True, null=True) # Field name made lowercase. c_level = models.CharField(db_column='C_Level', max_length=6, blank=True, null=True) # Field name made lowercase. company_name = models.CharField(db_column='Company_Name', max_length=50, blank=True, null=True) # Field name made lowercase. s_level = models.CharField(db_column='S_Level', max_length=6, blank=True, null=True) … -
cannot start gunicron on server in django project
I've been going through the process of creating a django project on my ubuntu server and I reached gunicorn start but i am getting this erorr: gunicorn projectname.wsgi [2017-12-15 00:12:32 +0000] [32264] [INFO] Starting gunicorn 19.7.1 [2017-12-15 00:12:32 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:32 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:33 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:33 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:34 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:34 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:35 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:35 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:36 +0000] [32264] [ERROR] Connection in use: ('127.0.0.1', 8000) [2017-12-15 00:12:36 +0000] [32264] [ERROR] Retrying in 1 second. [2017-12-15 00:12:37 +0000] [32264] [ERROR] Can't connect to ('127.0.0.1', 8000) -
TypeError execute_sql() got an unexpected keyword argument 'chunk_size'
I try to run ldapdb with rest_framework and get an exception: Type: TypeError at /users/ Value: execute_sql() got an unexpected keyword argument 'chunk_size' Location: /usr/local/lib/python3.5/dist-packages/django/db/models/query.py in __iter__, line 54 models.py: import ldapdb.models from ldapdb.models.fields import CharField, IntegerField class User(ldapdb.models.Model): # LDAP meta-data base_dn = "ou=user,o=foo" object_classes = ['person'] # user attributes uid = CharField(db_column='uid', max_length=8, primary_key=True, unique=True) employeeID = IntegerField(db_column='employeeID', unique=True) def __str__(self): return self.uid def __unicode__(self): return self.uid serializers.py: from rest_framework import serializers from api.models import User class UserSerializer(serialisers.HyperlinkedModelSerializer): class Meta: model = User fields = ('uid', 'employeeID') views.py from rest_framework import generics from api.models import User from api.serializers import UserSerializer class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer urls.py from django.conf.urls import url from api import views urlpatterns = [ url(r'^users/$', views.UserList.as_view()), ] and last but not least pip freeze: Django==2.0 django-ldapdb==0.9.0 djangorestframework==3.7.3 -
Emails sent by django-allauth are not translated
I have translated my project to Spanish I have ran python manage.py makemessages -l es and python manage.py compilemessages -l es both. My project strings are properly translated and shown when user has language set to es, but emails from django-allauth are sent in English. What am I missing? Thanks in advance. -
Why is this Django-Channels consumer running synchronously?
My understanding of websockets and django-channels is very superficial, so please bear with me. Before testing a more serious use case, I'm trying to gradually append a piece of data to my HTML, using jquery and django-channels. Here's my app/consumers.py: @channel_session_user def ws_receive(message): user_group = str(message.user.username) user_profile = message.user.user_profile.id message_text = json.loads(message['text']) room = "pk" for i in range(1, 5): time.sleep(1) Group(user_group).send({'text': json.dumps(room)}) I have the jquery code successfully connecting to the websocket, and calling this consumer upon a button click. First identify the click: $('#search_button').on('click', function(e) { e.preventDefault(); // prevent form submission var myval = $('#qos').val(); console.log(myval); mysocket.send(JSON.stringify(myval)); }); Which triggers onmessage: mysocket.onmessage = function message(event) { var data = JSON.parse(event.data); console.log(data); if (data === 'pk') { console.log("True"); $('#result_div').append('<p>' + data + '</p>') } }; The problem is, All of the pk pargraphs (4 in total) are being "spit out" in one bunch to my page. I thought this: for i in range(1, 5): time.sleep(1) Group(user_group).send({'text': json.dumps(room)}) Is supposed to send the message one-by-one to the websocket, which should then also inject the HTML one by one..that's happening is that it's waiting ~5 seconds (number of loops), and then adding 5 pk paragraphs at once. What am I misunderstanding? … -
same name in INSTALLED_APPS for 3rd party lib
I have a project with 4 marketplaces one of which is Jet. Also I've got 'jet-admin' skin that I should add to INSTALLED_APPS as 'jet'. My marketplace app is defined as 'vmode.apps.marketplaces.jet'. There's a conflict between them and it's close to impossible to rename everything connected to marketplaces.jet. I guess that renaming 3rd party lib 'jet' is an option. I made some research and found that there's a label in AppConfig, so I tried to make class JetAppConfig(AppConfig): name = 'jet' label = 'jet_skin' and added to: INSTALLED_APS = [ 'vmode.apps.marketplaces.base.apps.JetAppConfig', 'vmode.apps.marketplaces.jet', ] after I made migrations it returned: CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0001_initial, 0002_delete_userdashboardmodule in jet_skin). To fix them run 'python manage.py makemigrations --merge' and after I made it returned: raise ValueError("Could not find common ancestor of %s" % migration_names) ValueError: Could not find common ancestor of set([u'0001_initial', u'0002_delete_userdashboardmodule']) How can I change lib name without touching marketplace.jet.models\migrations? Any help appreciated. -
Django application memory usage
I am running Django application (built on Django Rest Framework) on Digital Ocean server with following characteristics: 4gb RAM 2 CPUs 60 GB drive I am using Gunicorn to run Django app and Celery to manage queue. Database is MySQL. As I can see CPU usage is really low, but memory usage seems to be large. After I deploy I noticed that python3 process uses even more memory (something around 75%). Whenever I deploy I am running after_deploy script, which contains following: service nginx restart service gunicorn restart chmod +x /mnt/myapplication/current/myapplication/setup/restart.sh source /mnt/env/bin/activate cd /mnt/myapplication/current/ pip3 install -r requirements.txt python3 manage.py migrate --noinput >> /mnt/migrations/migrations.log rm -f celerybeat.pid rm -f celeryd.pid celery -A myapplication beat -l info -f /var/log/celery/celery.log --detach celery -A myapplication worker -l info -f /var/log/celery/celery.log --detach Are these numbers expected? And if not, how can I investigate what is going wrong? -
check file extension in html using jinja
i was working making a project using django and using jinja for template design. My questions:- i have a file in localhost server and i don't no what kind of file is that So how i choose tags in html to show the file means or . i searched in web and find out that i should upload my videos in youtube and insert the embedded url in html using tag. But i don't wanna do that .I want to save files on my server please provide my some jinja logic r something else so that i can insert some conditions like if file is image: use <img> tag else: use <video> tag -
Django Admin and Multi-table inheritance: Show parents data in child list
like in the title i have two models: Company and PartnerCompany, the later of the two inheriting from the first model. Now, I already have a lot of saved companies that I can see in it's admin page. There is some way to show the same companies in the PartnerCompany (that inherit from Company) in it's admin page? models.py class Company(models.Model): ... ... class PartnerCompany(Company): ... admin.py class CompanyAdmin(admin.ModelAdmin): inlines = [ ... ] list_display = ('name', ...) search_fields = ['^name'] fieldsets = ( (None, { 'fields': ( ('name',...) ) }), ) class PartnerCompanyAdmin(CompanyAdmin): ... -
Django- Stuck and cannot get data to display on webpage
Here’s my issue. I can display data from one of my other tables (the stats table that I don’t show here) on my stats page and home page. That was the first time I was able to get it to work, (I am new to Django). Then I made another table in my database (the Alstandings table) and I made an app for that was well because I want a standings page. For some reason I cant get the data from my Alstandings table to display on the standings page. As far as I know I thought I replicated the process but maybe I’m missing something I don’t know about. Yes, I have registered the app in my settings. I’m not getting any errors right now. Please, if anybody has valuable input on how to get this to work, please respond. Your help will be greatly appreciated. Thank You. Standings/models from django.db import models class Alstandings(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. team = models.CharField(db_column='TEAM', max_length=30, blank=True, null=True) # Field name made lowercase. w = models.IntegerField(db_column='W', blank=True, null=True) # Field name made lowercase. l = models.IntegerField(db_column='L', blank=True, null=True) # Field name made lowercase. pct = models.DecimalField(db_column='PCT', max_digits=4, … -
Django: Custom Permission without Model
I have a reusable django app which does not have any model. This app is an optional module for a bigger project. This app has no models, but it should provide a custom permission. According to the docs you need a model to create a custom permission: See: https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#custom-permissions Of course I could create a useless empty model ..... but it feels like being on the wrong track. How to create a custom permission if the app has no models? -
Restric django developers access to models from other apps
What are the best practice to manage developers permissions on a Django project (in a Linux environment)? Let's assume I have a project with the following architecture: my_project/ manage.py my_project/ app_1/ models.py views.py urls.py app_2/ models.py views.py urls.py How can I allow someone to develop app_2 content without being able to access app_1 content? Especially the models. At the moment I manage files access via Linux permissions but my main concern is that you can import models from app_1 in the views from app_2 for example. This is actually needed in most of cases but is there a way to restrict that? What is there is confidential data in the tables from app_1 models that should not be accessible from app_2 developers? I'm not talking about basic django users permissions here, I would like to restrict how people can do import app_1.models from app_2/views.py for example. I'm probably missing a whole concept here and some best practice. -
how to get request.user in UpdateView django
I want to restrict the updateview to specefic user.How do I know which user requested the update view.I am new to django.Thanks in advance -
Emailing a Django SimpleUploadedFile without saving in a FileField
I have been struggling to email a file am generating,would love to be able to be able something like this. How do you email directly without saving the file in my model object.Getting this error 'str' object has no attribute 'read pdf_file = HTML(string=rendered_html, base_url=settings.MEDIA_ROOT).write_pdf() certificate = SimpleUploadedFile( 'Certificate-' + '.pdf', pdf_file, content_type='application/pdf') attachment = certifcate.read() msg.attach_file(attachment, 'application/pdf') -
help_text for username and email fields always output in browser
I have this model: class User(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' email = models.EmailField( _('email address'), max_length=150, unique=True, help_text=_('Required. 150 characters of fewer. Must be a valid email address.'), error_messages={ 'unique':_("A user with that email address already exists."), }, ) this form class: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username','email','password'] this view class: class UserFormView(View): form_class = UserForm template_name = 'workoutcal/register.html' def get(self, request): print("Hi again") form = self.form_class(None) return render(request, self.template_name, {'form':form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('workoutcal:calendar') return render(request, self.template_name, {'form': form}) and this url: url(r'^register/$', views.UserFormView.as_view(), name='register') So when I go to /workoutcal/register, I see this: The "help text" is always shown in the browser. Is this default Django behaviour, or is it due to some error I have made? Also, how do I make the text only show up if the user has entered bad data into the respective fields? -
How to make dict always available to a particular template with Django/Jinja2?
I have a template (using jinja2) that is used in lots of views (via {% include %} statements). The template will always require (amongst other data that changes, and will be passed in via the context) a dict, that is a constant. It would be cumbersome to add the dict to the context in every view that will potentially use the template. I could add the dict as a global variable in the jinja2 env.globals, but that doesn’t seem like a particularly good idea either. It is only needed in one template in one app, not the entire project. The Jinja2 documentation mentions template globals specific to a particular template, but I can’t figure out how to implement this with Django. Any help appreciated, thanks :) -
Nginx receive post request from client server then pass request and client ip to backend specific url
I'm receiving post request from client server where it comes in with some post data and then be saved to database after being passed to my server which is running nginx, I don't know exactly how to configure Nginx to receive those request and foward them to application backend using specific url where I will be able to save them in database. I would like nginx to give the client ip address and the posted request. Thank you, Im still learning how to use Nginx properly. Here is what i have tried to do but no success server{ listen 80; server_name my_server_ip; error_log /var/log/nginx/error.log; # proxy_pass_header Server; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; } location /user/user_request/{ if ($request_method != 'POST'){ return 405; } return 200; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; keepalive_requests 10; keepalive_timeout 75s; proxy_pass http://my_server_ip$request_uri; } } -
Print as you type in Ajax using python
Problem Statement: As we type in the text box it has to display exactly the same text in the index.html file that is entered in the text field without clicking submit button using Ajax To do this I have coded in this way shown below: Index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head><title>Submit after typing finished</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> function myFunction() { var x = document.getElementById("search-input"); x.value = x.value.toUpperCase(); $('#search-input').keyup(function (event) { var query =($('#search-input').val()); if (query != '' || query != ' ') { $.ajax({ type: 'GET', url: "/ajaxmssql/XViews.py", data: { 'q': query }, dataType: "html", success: function(data) { var params = $(html).filter(function(){ return $(this).is('p') }); params.each( function() { var value = "<li>" + $(this).html() + "</li>"; $("#main-results").append( value ); } ); }, error: function(request, ajaxOptions, thrownError) { $("#debug").html(request.responseText); $("#debug").html("Could Not Print"); } }); } }); } </script> </head> <body> <h1>Print This List...</h1> <input type="print" onkeyup="myFunction()" id="search-input" placeholder="Type to Print Here ..."/> <div id="main-results"></div> <div id = "debug"></div> </body> </html> XViews.py #!C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/python.exe import cgi import cgitb cgitb.enable() def print_header(): print("""Content-type: text/html\n <!DOCTYPE html> <html> <body>""") def print_close(): print ("""</body> </html>""") def display_error(): print_header() print ("<p>An Error occurred parsing the parameters passed to this … -
django javascript value match
In the template i have following {{ form.attributes.value }}'.split(',').toString() this has value as Cluster_1_Liferay,Cluster_4_Liferay result[key] has the follwing value ji,1,Cluster_1_Liferay,Cluster_2_Liferay,Cluster_3_Liferay which comes one by one like for loop ji 1 Cluster_1_Liferay Cluster_2_Liferay Cluster_3_Liferay Now i want to put a if condition if ('{{ form.attributes.value }}'.split(',').toString().match(/result[key]/)) { alert('yes');} I should get two 'yes'. But getting non . Can anybody help . -
Any resource that explain python oop using Django source code? [on hold]
Any one knows good resource to unleash some python oop technics used in django framework? thanks. -
Transform a dictionary in a list in Python
I would like get data from id property and transform in a list queryset = [{"id":1,"name":"John"},{"id":2,"name":"John"}] Expected result ('1','2') ## ID PROPERTY -
Creating Django User object for each user in backend
I'm writing a custom backend for authenticating users by their email address instead of username. I've already written a custom User model that inherits from AbstractUser: class User(AbstractUser): email = models.EmailField( _('email address'), max_length=150, unique=True, primary_key=True, help_text=_('Required. 150 characters of fewer. Must be a valid email address.'), error_messages={ 'unique':_("A user with that email address already exists."), }, ) As you can see, I've made the email-field unique, and also, a primary key. I'm following the docs for how to write the backend, and I've read this: The Django admin is tightly coupled to the Django User object. The best way to deal with this is to create a Django User object for each user that exists for your backend (e.g., in your LDAP directory, your external SQL database, etc.) You can either write a script to do this in advance, or your authenticate method can do it the first time a user logs in. It says that I should create a Django User object (which I'm guessing is the default User object django.contrib.auth.models.User) for each user in my backend. Question 1: If a backend is a class that implements get_user(user_id) and authenticate(request, **credentials) (this is said in the docs), how … -
Django fire signal user_logged_out on browser close
I'm working on a django application with a chat for users. Therefore I need to present the status logged in or logged out to the other users. To accomplish this I used the signals environment of django. As long as the users are using the log out button everything works well. In case they are jut closing the browser or the tab there's no way to detect the status switch to offline. What is the best way to fire the user_logged_out signal, when the browser or tab gets closed?