Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access nested attributes in values_list()
I'm not sure if I worded this right, but I have extended Django's User model, with my 'UserProfile' model, using class UserProfile(models.Model): user = models.OneToOneField(User) ... and I want to access all combined attributes of both User and UserProfile, by using something like this: UserProfile.objects.all().values_list('someAttr', 'user.otherAttr') But as I realised I can't access nested attributes like that -
Social Networking Newsfeed
I want to create a social networking site newsfeed view for my app but don't know how to go about it. Pls i need help. Got this tutorial online but could not understand the codes. views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.views.generic.edit import CreateView from django.contrib.syndication.views import Feed from django.contrib.auth.models import login_required from .models import Post from django.contrib.syndication.views import Feed from django.urls import reverse from stream_framework.activity import Activity from stream_framework.feeds.redis import RedisFeed from stream_framework.feed_managers.base import Manager def create_activity(pin): activity = Activity( pin.user_id, PinVerb, pin.id, pin.influencer_id, time=make_naive(pin.created_at, pytz.utc), extra_context=dict(item_id=pin.item_id) ) return activity class PinFeed(RedisFeed): key_format = 'feed:normal:%(user_id)s' class UserPinFeed(PinFeed): key_format = 'feed:user:%(user_id)s' class PinManager(Manager): feed_classes = dict( normal=PinFeed, ) user_feed_class = UserPinFeed def add_pin(self, pin): activity = pin.create_activity() self.add_user_activity(pin.user_id, activity) def get_user_follower_ids(self, user_id): ids = Follow.objects.filter(target=user_id).values_list('user_id', flat=True) return {FanoutPriority.HIGH:ids} manager = PinManager() @login_required class NewsFeed(request): context = RequestContext(request) feed = manager.get_feeds(request.user.id)['normal'] activities = list(feed[:25]) context['activities'] = activities response = render_to_response('newsfeed/newsfeed.html', context) return response -
WSGIScriptAlias Invalid option to WSGI script alias definition
I'am trying to run Django on Apache on Windows Server. I installed Python, Apache etc. according to thetrevorharmon and mod_wsgi according to Graham Dumpleton. I start server httpd -k start and get the following error C:\Apache24\htdocs>httpd -k start AH00112: Warning: DocumentRoot [C:/Apache24/docs/dummy-host.example.com] does not exist AH00112: Warning: DocumentRoot [C:/Apache24/docs/dummy-host2.example.com] does not exist AH00526: Syntax error on line 55 of C:/Apache24/conf/extra/httpd-vhosts.conf: Invalid option to WSGI script alias definition. My httpd-vhosts.conf # Virtual Hosts # # Required modules: mod_log_config # If you want to maintain multiple domains/hostnames on your # machine you can setup VirtualHost containers for them. Most configurations # use only name-based virtual hosts so the server doesn't need to worry about # IP addresses. This is indicated by the asterisks in the directives below. # # Please see the documentation at # <URL:http://httpd.apache.org/docs/2.4/vhosts/> # for further details before you try to setup virtual hosts. # # You may use the command line option '-S' to verify your virtual host # configuration. # # VirtualHost example: # Almost any Apache directive may go into a VirtualHost container. # The first VirtualHost section is used for all requests that do not # match a ServerName or ServerAlias in any <VirtualHost> block. … -
Remove/Hide detail object in inline
I want to remove/hide OrderDetail object which is under Frame Image. I'm using inline here. Also I'm using Django-admin-bootstrap but it is irrespective of it because detail object is also shown in default Django admin panel. -
I wanna get excel files excepting temporary files in a folder
I wanna get excel files excepting temporary files(has ~$ in front of file name) in a folder.Now I wrote codes that can be got all excel files in a folder like files = glob.glob('./data/*.xlsx') But in this case, I can get all excel file including temporary files.How can I do it?What should I write it?I searched the way of using regular expression&try-catch statement,but I cannot understand how to write it. -
Django auth.group custom permission
im creating a custom group with some permissions like this // create new group new_group, created = Group.objects.get_or_create(name='AdminGroup') ct = ContentType.objects.get_for_model(User) // Add permission to new group p3 = Permission.objects.create( codename='DELETE', name='can_Delete', content_type=ct) new_group.permissions.add(p3) now i want to check if user has this permission like this user_right = request.user.has_perm('can_Delete') print(user_right) this print returns me false. how ?? and of course, i added this group to the user like this g = Group.objects.get(name='AdminGroup') request.user.groups.add(g) and another thing, I've checked this in admin panel group is assigned with permission successfully can someone explain to me how this is false ?? -
Uncaught reference error for WOW.js
Building a Django website using Bootstrap 4 and the MDB (Modern Bootstrap) theme. Included in MDB is WOW.js, the animation library, but for some reason when I am trying to initialize it with <script> new WOW().init(); </script> it gives me an Uncaught ReferenceError: WOW is not defined. My code is as follows: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>Title</title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'mdb/css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'mdb/css/mdb.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% sass_src 'scss/mystyle.scss' %}"> </head> <body> ...... My Code Goes Here ..... <script type="text/javascript" href="{% static 'mdb/js/jquery-3.2.1.min.js' %}"></script> <script type="text/javascript" href="{% static 'mdb/js/popper.min.js' %}"></script> <script type="text/javascript" href="{% static 'mdb/js/bootstrap.min.js' %}"></script> <script type="text/javascript" href="{% static 'mdb/js/mdb.js' %}"></script> <script> new WOW().init(); </script> </body> The wow.js code is present within the mdb.js file, but just in case I also included wow.js separately. Still nothing. I have double checked and all the files are in the correct locations and they are all correct without any mistakes. Really not sure what is going on here as the first line within wow.js is var WOW = function (properties) { etc... so how can … -
Django Rest API: How to get rid of 'UUID' in json when serializing models?
Why does 'UUID' appear in front of the value of 'profile' key and how do I remove it properly? roster/serializers.py class ShiftSerializer(serializers.ModelSerializer): class Meta: model = Shift fields = ('id', 'profile', 'location', 'date', 'start_time', 'end_time') profile/models.py class Profile(models.Models): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) roster/models.py id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) profile = models.ForeignKey('profiles.Profile', null=True, blank=True) python manage.py shell from roster.models import Shift from roster.serializers import ShiftSerializer myshift = Shift.objects.first() serializer = ShiftSerializer(myshift) serializer.data Output: {'id': '92ca258e-8624-434a-b61d-e1cd3b80e0e8', 'profile': UUID('0081b028-0a11-47fb-971e-c47177ed93be') -
How to perform a reverse lookup of the localized version of a string to it's original string
I need to perform a lookup of the original string based on it's localized version in Django. Is there a built in method for that (couldn't find it in the docs) or is there a smart way to achieve something like that? -
Django error with oracle database error(ORA--0001: Message -1 not found;) - database connection
I have created a tool for massive update for some users with Django 1.8 with WSGI and for quite a while the following error occurs frequently that it gets resolved by restaring (or reload) web server(apache). Internal Server Error: /mass_update/reasons/cells/halted/ Traceback (most recent call last): File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/mass_update/mass_update/views.py", line 308, in cells_halted if form.is_valid(): File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/forms/forms.py", line 184, in is_valid return self.is_bound and not self.errors File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/forms/forms.py", line 176, in errors self.full_clean() File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/forms/forms.py", line 392, in full_clean self._clean_fields() File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/forms/forms.py", line 407, in _clean_fields value = field.clean(value) File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/forms/fields.py", line 162, in clean value = self.to_python(value) File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/forms/models.py", line 1218, in to_python value = self.queryset.get(**{key: value}) File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/models/query.py", line 328, in get num = len(clone) File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/models/query.py", line 144, in __len__ self._fetch_all() File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 838, in execute_sql cursor = self.connection.cursor() File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/utils.py", line 98, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/root/.virtualenvs/dashboard/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File … -
Django {% trans "May" context "verb" %} caching
I have problem with {% trans %} tag in django I deploy me page to server and on one page translation work correctly but on the other the same template of page and same translation not working. It looks like some caching problem or so on pages: http://gdzn.tk/products/novy-level-team-panska-7/ - the button say "add to card" http://gdzn.tk/products/kiobk-16/ - the button say "Pridať do košíka" both is same template with same trans tag. I don't understand could someone help me? -
Python Programming Django Deployement
I am trying to develop a project in a company in a remote server using django frame work ,i have to run django applications in the remote server using Apache Web server ,Apache is already installed ,i do not have access to Apache.confi file .How should i run? -
merge django's auth_user with existing user table
Currently I have a legacy app which refers to a user table with all the custom fields. Since there is a good amount of legacy code referring to that table I cannot simple rename that table as auth_user. So the thing I'm trying to do is somehow merge (i don't know that its the right term) auth_user and user. Below is user table: +-------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+--------------+------+-----+---------+----------------+ | user_id | int(10) | NO | PRI | NULL | auto_increment | | name | varchar(100) | NO | | NULL | | | address | varchar(100) | NO | | NULL | | | phone_no | varchar(15) | NO | | NULL | | | city | varchar(100) | NO | | NULL | | | state | varchar(100) | NO | | NULL | | | pin_no | int(10) | NO | | NULL | | | type | varchar(100) | NO | | NULL | | | email | varchar(100) | NO | | NULL | | | password | varchar(100) | NO | | NULL | | | is_active | tinyint(1) | NO | | NULL | … -
How to use POST in Django
I use Django 1.11.3 and python2.7 I want write a easy message board and here is my code <form name='my form' action='/talkpost/' method='POST'> {% csrf_token %} {% for m in moods %} <input type='radio' name='mood' value='{{ m.status }}'>{{ m.status }} {% endfor %} <textarea name='user_post' rows=3 cols=70></textarea><br/> <label for='user_id'>nickname:</label> <input id='user_id' type='text' name='user_id'> <label for='user_pass'>password</label> <input id='user_pass' type='password' name='user_pass'><br/> <input type='submit' value='submit'> <input type='reset' value='reset'> <input type="hidden" name="ok" value="yes"> </form> urls.py url(r'^talkpost/', talkpost), url(r'^talk/', talk), talk is just for user to see the from and talkpost is for Django to get the post request views.py def talk(request): template = get_template('talk.html') moods = Mood.objects.all() message = 'Leave some message!' html = template.render(locals()) return HttpResponse(html) def talkpost(request): template = get_template('talk.html') if 'ok' in request.POST: user_id = request.POST['user_id'] user_pass = request.POST['user_pass'] user_post = request.POST['user_post'] user_mood = request.POST['mood'] message = 'success!' request_context = RequestContext(request) request_context.push(locals()) html = template.render(request_context) return HttpResponse(html) I try using {% csrf_token %} and RequestContext But i still get CSRF token missing or incorrect. I have no idea how to fix it -
Which IP address should I put on 'Server IP Whitelist' facebook developer console? (400 error from Facebook)
I'm building oauth2 facebook authorization and the errors prints "This IP address is not on the Server IP whitelist" Is the 'IP address' referring to my public ip address or my localhost? I put both but I'm getting still same error. From Facebook Developer Console > Advanced, Server IP Whitelist: 10.0.2.2, 223.108.215.xxx <- replaced numbers with x Update Settings IP Whitelist: 223.108.215.xxx Which IP address should I put? Thanks -
how to make breakpoints stop in my application's code in Pycharm
I am new to python and django. I have a project, myforum, that uses an application askbot (with some customization). In Pycharm, I open 2 folders, myforum, askbot-devel, in the same project window. I install askbot with python setup.py develop. It installs askbot as a link under site-packages of my python runtime: if I set a breakpoint in myforum's code and run server in debug mode, the program will stop at the breakpoint. But if I set a breakpoint in an askbot's code, e.g. writers.py, the program still doesn't stop at the breakpoint. How can I make the program stop at the breakpoint in askbot's code? -
if condition not working in python comparing float
If condition in my code is not working properly. Here's my code: if confidence < 0.50: dialog = "Sorry" else: dialog = "ok" return HttpResponse(dialog) Only else part is working. When confidence is less than 0.50 "local variable 'dialog' referenced before assignment error" comes.Confidence type is numpy.float64 . I am using python 2.7. Thanks -
Nginx + uWSGI + Django 502 on POST requests
I'm trying to set up django server with uWSGI and nginx. The problem I have is that it works, except all POST requests return 502 Bad Gateway. Logs of uWSGI don't show my POST requests, so problem might be with nginx, though this same nginx configuration worked with gunicorn instead of uwsgi. So what might be a problem in this case? My nginx configs (not full): upstream serverapi { server unix:///opt/server-api/server_api/server.sock; } server { listen 80; server_name example.com; return 301 https://example.com$request_uri; location / { allow all; autoindex on; uwsgi_pass serverapi; include /etc/nginx/uwsgi_params; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } uWSGI.ini: [uwsgi] chdir = /opt/server-api module = server_api.wsgi home = /opt/server-api/venv master = true processes = 3 socket = /opt/server-api/server_api/server.sock chmod-socket = 664 vacuum = true Using python3.5, Django1.10.2, uWSGI2.0.15, nginx1.10.3 -
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\x19Microso'
I got an error, xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\x19Microso' . I wanna parse excel and put data in the model(User).Now views.py is files = glob.glob('./data/*.xlsx') for file in files: book = xlrd.open_workbook(file) sheet = book3.sheet_by_index(0) cells = [ ('company_id', 0, 4), ('name', 0, 5), ('user_id', 1, 4), ('adress', 1, 5), ] data_dict = OrderedDict() for key, rowy, colx in cells: try: data_dict[key] = sheet3.cell_value(rowy, colx) except IndexError: data_dict[key] = None print(data_dict) I searched the error meaning, so I found maybe this error happened to open excel file.But my xlrd.VERSION is '1.1.0' and I catched not pdf but excel in the code files = glob.glob('./data/*.xlsx'),so I really cannot understand why this error happens.How can I fix this? -
Python Django project not working on live server
When I am using this setting then its not working on live sever but When I am using simple html then its working fine , So what is pending in this setting server { listen 80; #listen 443 ssl; server_name example.com; root /home/baxter/django/app_baxter_com/; #index test.html index.htm; #root /etc/nginx/circ.travelpress.com #ssl on; #ssl_certificate /opt/keysm.crt; #ssl_certificate_key /opt/keyss.key; } When I am using this #index test.html index.htm; then its working file with html but not with django/python So what is wrong in this setting . Thanks -
I wanna make table has only most newest data each user_id in models.py
I wanna make Transaction table in models.py. I wanna parse excel& make dictionary and put the model(User) which has same user_id of dictionary. There is 2 excels I read 1st Excel,and the data is in User. Now I wanna read 2nd Excel,but if i do so,user_id=1 Blear&user_id=2 Tom 's data has 2 data are from Excel1&2.So,I wanna try to make a table has only most newest data each user_id. models.py is #coding:utf-8 from django.db import models class User(models.Model): user_id = models.CharField(max_length=200) name_id = models.CharField(max_length=200) nationality = models.CharField(max_length=200) dormitory = models.CharField(max_length=200) group = models.CharField(max_length=200) How can I make it?How can I sort most newest data and put them in model? -
Error message " 'str' object is not callable" in django
I saw that there was a similar question in this site, however, even if I looked at the similar question, I couldn't solve my problem. Therefore, I will ask you a question. I have a question regarding django. I developed blog site in local enviroment. When I checked how to display of my test article, Although I clicked following button marked red flame, The error message was displayed as follows. enter image description here The error message is as follows. TypeError at /admin/r/7/1/ 'str' object is not callable Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/r/7/1/ Django Version: 1.11.4 Python Version: 3.6.2 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'engapp', 'taggit') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "F:\01_pro\kaso3\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "F:\01_pro\kaso3\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "F:\01_pro\kaso3\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "F:\01_pro\kaso3\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\01_pro\kaso3\lib\site-packages\django\contrib\admin\sites.py" in wrapper 242. return self.admin_view(view, cacheable)(*args, **kwargs) File "F:\01_pro\kaso3\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "F:\01_pro\kaso3\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "F:\01_pro\kaso3\lib\site-packages\django\contrib\admin\sites.py" in inner 224. return view(request, *args, **kwargs) File "F:\01_pro\kaso3\lib\site-packages\django\contrib\contenttypes\views.py" in shortcut 31. … -
getting blank page while editing pages in djangocms
getting blank page while editing pages in django cms, sometime i can able to edit but some time getting blank page, please help it is on urgent base. <nav> <ul class="nav nav-pills" id="mainNav"> {% show_menu 0 100 100 100 %} </ul> {% render_block "js" %} </nav> -
realtime blog update using django channels means when database changes , the changes reflects on webpage in realtime
i read the channels documentation and do some practice on django channels. Its easy to do chat server using channels. But i want to know about the process how can i update my webpage without refresh when database changes with channels. how can i send a request to change on database and show on webpage realtime using channels. i allready tried to understand channels concept and i tried to make simple chat server. Now i want to know about realtime database update and show on webpage. thank you -
Django - Calling ManytoMany Feild inside jQuery
I am using Django Model field values inside a Javascipt file by using the following code: var action_type =$('#id_strength').val(); Here strength is a Charfield. But the same doesn't work for a ManytoMany Field var action_type =$('#id_batches').val();