Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin: Inline straight to second-level relationship
I have a three-levels Invoice model. One Invoice is conformed by several SubInvoices, and each SubInvoice is conformed by several Items, which contain a break down of the Products purchased by a customer. Something like this (hopefully the ascii art works) +---------- Invoice id=3 -----------+ | Full total: $100.00 | | | | +----- Sub Invoice id=1 -----+ | | | Subtotal $70 | | | | | | | | Item 1 in SubInv.1 | | | | Item 2 in SubInv.1 | | | | Item 3 in SubInv.1 | | | |____________________________| | | | | +----- Sub Invoice id=2 -----+ | | | Subtotal $30 | | | | | | | | Item 1 in SubInv.2 | | | | Item 2 in SubInv.2 | | | |____________________________| | | | |___________________________________| The models look more or less (it's been simplified for this question) like: class Invoice(models.Model): full_total = DecimalField(...) class SubInvoice(models.Model): sub_total = DecimalField(...) invoice: ForeignKey('server.Invoice', related_name='sub_invoices') class InvoiceItem(models.Model): sub_invoice: ForeignKey('server.SubInvoice', related_name='items') Now, I am aware that nesting two levels of relationships in Django Admin is very complex, and I'm not trying to nest the InvoiceItem into the SubInvoice and nest that one into … -
How to resize an image in Python without using Pillow
My Django site is hosted on Azure. It allows for users to upload photos. I need a way for the system to resize, and possibly rotate photos. Seems simple, and I tried to use the Pillow library but while it works locally it will not deploy to Azure for a number of reasons. I can be specific if needed but this is well documented like here. I even tried buiding a wheel of Pillow and deploying that but Azure refuses to load it saying it is the wrong platform (even though I matched the Python 2.7 version - and 32 bit). I tried to upload 64 bit versions as well, and nothing works. So at this point I just want to leave Pillow behind me and ask for another way to achieve this in Python without Pillow. -
How to Use gRPC with Protocol buffer with Django
I am using Django to make an E-commerce website and i want to use gRPC with Protocol Buffer, so, i can serve different client platform to like IOS, Android etc. i want to use gRPC because it is compatible with TensorFlow models to serve with live data of customers or using tensorflow models in productions I just want to know how to use in django, i am new to Django please help. -
Django Rest - Making a Connection between two Users (SQL)
Having some trouble with this one. Building a DJANGO REST API. I need to make a connection between two users. UserA signs in, and sends a connection to UserB (right now I simply do this in Admin interface). This creates an entry on the ConnectionTable which is as follows: class Connection(models.Model): user = models.OneToOneField(User, related_name='myuser_connection', on_delete=models.CASCADE) connected_user = models.OneToOneField(User, on_delete=models.PROTECT, related_name="connected_user", null=True, blank=True) are_they_connected = models.IntegerField(default=0) So, UserA's entry on the Connect table will be something like (id: 1, user_id: 1, connected_user: 2, are_they_connected: 0. How can this relationship be done, so that it creates an entry for UserB which they would have to confirm or reject? I think I'm overthinking things but I'm not sure the right way to approach this. -
Django - How to grant custom permissions to some users in DRF?
I'd like to grant some users retrieve access, some users update access and no retrieve/update access for unauthenticated users to my DRF API. In my extended user model, I have two fields that defines whether a user should be allowed Retrieve or Update to the API. How should I write the logic in my DRF custom permissions class to check these two fields and grant retrieve or update depending if True or False? Is there a better way to do this? models.py class UserProfile(models.Model): user = models.OneToOneField(User) allowRetrieveAPI = models.BooleanField(default=False,) allowUpdateAPI = models.BooleanField(default=False,) class Track(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Submitted by", default=1) artist = models.CharField(max_length=100,) title = models.CharField(max_length=100,) views.py class CheckAPIPermissions(permissions.BasePermission): # allow retrieve if userprofile.allowReadAPI is True # allow update if user userprofile.allowUpdateAPI is True def has_permission(self, request, view): # return something def check_object_permission(self, user, obj): # return something def has_object_permission(self, request, view, obj): # return something class TrackViewSet(viewsets.ModelViewSet): queryset = Track.objects.all() serializer_class = TrackSerializer permission_classes = (CheckAPIPermissions,) -
How do I remove the "u" prefix from a (json serialized) list of dictionaries?
I need the "u" prefixed removed because I am passing these json serialized lists over to the front end and handling them with javascript. Javascript can not make sense of these "u"'s. (I mention this because one of the answerers where this question has been asked before didn't answer the question, he just asked "why do you need it removed; it's the same thing" -- and this was marked as the correct answer!). Here is the code: context['list_of_dicts'] = serialize('json', my_list_of_dicts) # this function is wrapped with a @json response decorator @json_response looks like: def json_response(func): """ A decorator thats takes a view response and turns it into json. If a callback is added through GET or POST the response is JSONP. """ def decorator(request, *args, **kwargs): objects = func(request, *args, **kwargs) if isinstance(objects, HttpResponse): return objects try: data = simplejson.dumps(objects) if 'callback' in request.REQUEST: # a jsonp response! data = '%s(%s);' % (request.REQUEST['callback'], data) return HttpResponse(data, "text/javascript") except: data = simplejson.dumps(str(objects)) return HttpResponse(data, "application/json") return decorator On the frontend, I get the error: Uncaught SyntaxError: Unexpected token u in JSON at position 0 That's because the "u" prefix has not been removed. How do I remove the "u" prefix … -
Django Postman Auto Moderation issue
I I'm trying to install django-postman onto my website. http://django-postman.readthedocs.io/en/latest/moderation.html I have it working perfectly however i want to add auto-moderator, however im struggling to implement it. I've added the functions into the views and added the URL however i get the issue name 'mod1' is not defined, however I've clearly added it. Sorry but im very new to django. Here's the documention for django-postman. Auto moderators You may automate the moderation by giving zero, one, or many auto-moderator functions to the views. The value of the parameter can be one single function or a sequence of functions as a tuple or a list. Views supporting an auto-moderators parameter are: WriteView, ReplyView. Example: def mod1(message): # ... return None def mod2(message): # ... return None mod2.default_reason = 'mod2 default reason' urlpatterns = patterns('postman.views', # ... url(r'^write/(?:(?P<recipients>[^/#]+)/)?$', WriteView.as_view(auto_moderators=(mod1, mod2)), name='write'), url(r'^reply/(?P<message_id>[\d]+)/$', ReplyView.as_view(auto_moderators=mod1), name='reply'), # ... ) Each auto-moderator function will be called for the message to moderate, in the same order as the one set in the parameter. Input: message: a Message instance Output: The structure of the output is either a rating or a tuple (rating, reason). rating may take the following values: None 0 or False 100 or True … -
Django - POST method in relational database model - table doesn't exist
I would like to create Object2 for defined user ID in url. GET method in the example shown below works fine, but I can't create POST method. I will be grateful for help. Let's assume I have free sample objects in database: User: id Object1: id user_id Object2: id object1_id In urls.py it looks in this way: url(r'^users/(?P<user_id>[0-9]+)/object2$', views.UserObject2), In models.py: from django.contrib.auth.models import User class Object1(models.Model): user = models.ForeignKey(User) class Object2(models.Model): object1 = models.ForeignKey(Object1) object3 = models.ForeignKey(Object3, related_name='object2') In views.py: @api_view(['GET', 'POST']) def UserObject2(request, user_id): user = User.objects.get(id=user_id) if request.method == 'POST': serializer = Object2Serializer(data=request.data) object1 = Object1.objects.get(user=user) if serializer.is_valid(): serializer.save(object1=object1) else: return Response(serializer.errors) else: object2 = Object2.objects.filter(object1__user=user) serializer = Object2Serializer(object2, many=True) return Response(serializer.data) In serializers.py: from django.contrib.auth.models import User class Object3Serializer(serializers.ModelSerializer): class Meta: model = Object3 depth = 1 fields = '__all__' class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class Meta: model = User fields = '__all__' class Object2Serializer(serializers.ModelSerializer): object3 = Object3Serializer(read_only=True) class Meta: model = Object2 fields = ('object3', 'number', 'date') class Object1Serializer(serializers.ModelSerializer): class Meta: model = Object1 fields = '__all__' I'm trying in this way, but I have problem with object3 = models.ForeignKey(Object3, related_name='object2') in Object class Object2(models.Model): To wit, when I send … -
Django 1.11 can't connect to Postgres on RDS
I created a new EC2 Instance with Postgres on RDS. I confirmed that I can connect from the EC2 instance to the database using psql without any issue which means my security settings are fine. However, when I try to run manage.py runserver or manage.py dbshell (from the virtualenv) Django hangs then eventually gives a timeout error: psql: could not connect to server: Connection timed out Is the server running on host "whatever.rds.amazonaws.com" (172.xxx.xxx.xxx) and accepting TCP/IP connections on port 5342? Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/ubuntu/Env/xxxx/lib/python3.5/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/home/ubuntu/Env/ss2017/lib/python3.5/site-packages/django/core/management/init.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/Env/ss2017/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/Env/ss2017/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/Env/ss2017/lib/python3.5/site-packages/django/core/management/commands/dbshell.py", line 22, in handle connection.client.runshell() File "/home/ubuntu/Env/ss2017/lib/python3.5/site-packages/django/db/backends/postgresql/client.py", line 66, in runshell DatabaseClient.runshell_db(self.connection.get_connection_params()) File "/home/ubuntu/Env/ss2017/lib/python3.5/site-packages/django/db/backends/postgresql/client.py", line 58, in runshell_db subprocess.check_call(args) File "/usr/lib/python3.5/subprocess.py", line 581, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['psql', '-U', 'db_name', '-h', 'whatever.rds.amazonaws.com', '-p', '5342', 'user_name']' returned non-zero exit status 2 I tried creating a new copy of the Django app to see if there were perhaps corrupt files involved, and I played with some changes to my settings.py file, but no … -
Optimal pythonic way to achieve result output
I need some help regarding optimal and good solution for my answer. I have input dict like this: a = { (1, 1403): {1:0.1, 2:0.1, 3:0.2}, (1, 1412): {1:0.1, 2:0.1, 3:0.2}, (1, 1411): {1:0.1, 2:0.1, 3:0.2}, (1, 1402): {1:0.1, 2:0.1, 3:0.2}, (1, 1411): {1:0.1, 2:0.1, 3:0.2}, (2, 1501): {1:0.1, 2:0.1, 3:0.2}, (2, 1511): {1:0.1, 2:0.1, 3:0.2}, (2, 1700): {1:0.1, 2:0.1, 3:0.2}, (2, 1120): {1:0.1, 2:0.1, 3:0.2}, (2, 2133): {1:0.1, 2:0.1, 3:0.2}, (2, 2130): {1:0.1, 2:0.1, 3:0.2}, (2, 901): {1:0.1, 2:0.1, 3:0.2}, (3, 1111): {1:0.1, 2:0.1, 3:0.2}, } I want Output like this: {1: { 1403: {1: 0.1, 2: 0.1, 3: 0.2}, 1402: {1: 0.1, 2: 0.1, 3: 0.2}, 1411: {1: 0.1, 2: 0.1, 3: 0.2}, 1412: {1: 0.1, 2: 0.1, 3: 0.2}}, 2: {1120: {1: 0.1, 2: 0.1, 3: 0.2}, 2130: {1: 0.1, 2: 0.1, 3: 0.2}, 1700: {1: 0.1, 2: 0.1, 3: 0.2}, 901: {1: 0.1, 2: 0.1, 3: 0.2}, 1511: {1: 0.1, 2: 0.1, 3: 0.2}, 1501: {1: 0.1, 2: 0.1, 3: 0.2}, 2133: {1: 0.1, 2: 0.1, 3: 0.2}}, 3: {1111: {1: 0.1, 2: 0.1, 3: 0.2}}} I have done code below data_dict = defaultdict(dict) for (a,b), c in a.items(): data_dict[a].update({b:c}) I had already above answer to … -
Transforming an SQL table
I am trying to write a nice SQL query, but I am failing. I am trying to create a table like the following: Date | Cash | Checking | Savings -------------------------------------- May 2017 | 30 | 300 | 3000 Apr 2017 | 40 | 400 | 4000 My tables are like this: Balances * id * date * amount * item_id BalanceItems * id * name So the column names (cash, checking and savings for example) are stored in BalanceItems. Basically I don't know how I can get the name from BalanceItems in the column header. I am building this in Django, so ideas of how to elegantly do this there are also appreciated. These are the models: class Balances(models.Model): item = models.ForeignKey('BalanceItems', related_name='balances_balance_items') date = models.DateField() amount = models.DecimalField(max_digits=9, decimal_places=2) class BalanceItems(models.Model): name = models.CharField(max_length=100, unique=True) -
Django error after restore database
i have a very strange error after restore a db and i can't figure out why when i try to access /admin/login/?next=/admin/ i got Exception Type: MultipleObjectsReturned at /admin/login/ Exception Value: get() returned more than one Permission -- it returned 2! and here is my full error log : File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/admin/sites.py" in login 361. self.each_context(request), File "/home/ubuntu/crm/pepro/admin.py" in each_context 145. context = super(AdminSite, self).each_context(request) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/admin/sites.py" in each_context 284. 'available_apps': self.get_app_list(request), File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/admin/sites.py" in get_app_list 451. app_dict = self._build_app_dict(request) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/admin/sites.py" in _build_app_dict 397. has_module_perms = model_admin.has_module_permission(request) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/admin/options.py" in has_module_permission 476. return request.user.has_module_perms(self.opts.app_label) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/auth/models.py" in has_module_perms 438. return _user_has_module_perms(self, module) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/auth/models.py" in _user_has_module_perms 203. if backend.has_module_perms(user, app_label): File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/permission/backends.py" in has_module_perms 122. if handler.has_module_perms(user_obj, app_label): File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/permission/handlers.py" in has_module_perms 182. if user_obj.has_perm(permission): File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/auth/models.py" in has_perm 429. return _user_has_perm(self, perm, obj=obj) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/django/contrib/auth/models.py" in _user_has_perm 188. if backend.has_perm(user, perm, obj): File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/permission/backends.py" in has_perm 63. perm_to_permission(perm) File "/home/ubuntu/crm/venv/py3/lib/python3.5/site-packages/permission/utils/permissions.py" in perm_to_permission 77. codename=codename … -
django_cas_ng throws ssl error
Facing weird SSL error with django CAS client request when trying to authenticate using remote CAS server. Traceback (most recent call last): File "/home/test/p36d19/lib/python3.6/site-packages/urllib3/contrib/pyopenssl.py", line 438, in wrap_socket cnx.do_handshake() File "/home/test/p36d19/lib/python3.6/site-packages/OpenSSL/SSL.py", line 1638, in do_handshake self._raise_ssl_error(self._ssl, result) File "/home/test/p36d19/lib/python3.6/site-packages/OpenSSL/SSL.py", line 1378, in _raise_ssl_error _raise_current_error() File "/home/test/p36d19/lib/python3.6/site-packages/OpenSSL/_util.py", line 54, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')] and settings file has INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cas_ng', ) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'django_cas_ng.backends.CASBackend', ) CAS_SERVER_URL = "https://login.cas-example.com:8443/cas/login" CAS_EXTRA_LOGIN_PARAMS = {'renew': True} CAS_REDIRECT_URL = '/login_test' -
url for django updating user profile
So far i have done some research ,most of the solutions seems outdated .I have extended my user profile using the following codes below .The updating form is rendered but when i summit the form ,i get an error .Bellow is my code ,please help sort out the mistakes i did . model.py class UserProfile(models.Model): user = models.OneToOneField(User,unique=True,on_delete=models.CASCADE) bio = models.TextField(max_length=500,null=True,blank=True) picture = models.ImageField(upload_to="profile_image",null=True,blank=True,) company = models.TextField(max_length=500,null=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) views.py def update_profile(request): if request.method == 'POST' creat_account_form = Create_account(request.POST,instance=request) profile_form = ProfileForm(request.POST,instance=request.user.userprofile) if create_account_form.isvalid() and profile_form.is_valid() create_account.save() profile_form.save() return redirect('app_namespace:url_name') else : messages.error(request,'fill out the form correctly') else: create_account_form = Create_account(instance= request.user) profile_form = ProfileForm(instance= request.user.userprofile) return render(request,"app_name/editprofile.html") url.py urlpatterns =[ url(r'Update_profil/$',views.update_profile,name="profile_update") ] html {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} Save changes Error when i summit form i get the error bellow .I know the error has to do with the url and view ,i have done lots of research ,most are outed .please help me out with the most accurate working example of updating my userprofile thanks very much . ERROR ValueError at /Update_profil/ The view success.views.update_profile didn't return an HttpResponse object. It returned None instead. -
403 error because `id_token` being used as `access_token` in Django + python-social-app
I am confused. I am using the Django configuration for python-social-auth (spcefically social-auth-app-django v1.2.0) to get Google+ backend authentication working. I get this error: requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://www.googleapis.com/plus/v1/people/me?access_token=XYZ123&alt=json Social auth seems to be passing the param access_token but I don't know why since the docs say to pass to the backend the id_token. I have verified that what I'm getting is a valid id_token using this link: https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123 Also, I verify that it is a NOT a valid access_token using this link: https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=XYZ123 I mean, I'm doing what the python-social-apps docs and google's docs is telling me to do, and that is to pass id_token to the backend. Here's my js code: <script src="https://apis.google.com/js/api:client.js"></script> <script> var googleUser = {}; var startApp = function() { gapi.load('auth2', function() { // Retrieve the singleton for the GoogleAuth library and set up the client. auth2 = gapi.auth2.init({ client_id: '{{ google_plus_id }}', cookiepolicy: 'single_host_origin', // Request scopes in addition to 'profile' and 'email' scope: '{{ google_plus_scope }}', }); attachSignin(document.getElementById('google-plus-button')); }); }; function attachSignin(element) { console.log(element.id); auth2.attachClickHandler(element, {}, function(googleUser) { var authResponse = googleUser.getAuthResponse(); var $form; var $input; $form = $("<form>"); $form.attr("action", "/complete/google-plus/"); $form.attr("method", "post"); $input = $("<input>"); $input.attr("name", "id_token"); $input.attr("value", authResponse.id_token); … -
How to expose a rendering error caught by django in a unit test?
I have an error in django code (a typo in a variable name) that doesn't show up in a unit test which does in fact run the erroneous statement as I can see from a coverage report. I want the error to be exposed by the unit test. I use django 1.9.12, I have DEBUG = True in settings.py and TEMPLATES : OPTIONS : Debug = True as suggested in the django 1.9 documentation. I use a unit test like this: tests.py: class SomeTestClass(unittest.TestCase): @override_settings(DEBUG=True, TEMPLATE_DEBUG=True) def test_view(self): client = django.test.Client() response = client.get('someurl',{}) self.assertEqual(response.status_code, 200) The override_settings doesn't actually override anything as far as I know, but just in case, I took that from How to make test case fail if a django template has a rendering error that would silently fail in production As far as I understand, when the test case runs, it looks up the url: urls.py: urlpatterns = (r'someurl', views.method1, name='method1') and gets redirected to the views module: views.py: def method1(request): x = sometypo I use the coverage package to tell me that the sometypo statement was actually reached. The testcase passes however, and I get no warning of the error. If I replace the … -
Django - How to map object from another API and send in GET response
I would like to map object from another API and send in GET response. I'm going to change only id of received object. Let's assume I get data from another API in such format: { "id": "31242", "name": "sth1", "price": "44", "data": "2017-06-07", } In my database I have table object1 with values: { "id": "123", "name": "sth1", }, { "id": "124", "name": "sth2", }, { "id": "125", "name": "sth3", } Field name is unique both in data from API and in data from database. I receive an object named sth1. So now I would like to find it in my database and get his id, replace with id from API and send GET response. In this case my response would look in this way: { "id": "123", "name": "sth1", "price": "44", "data": "2017-06-07", } At this moment this is my URL - url(r'^data/(?P<name>\w+)$', views.DataList), but I would like to have such URL - localhost:8000/data?name=sth Myview.py: @api_view(['GET']) def DataList(request, name=None): if request.method == 'GET': quote = getDataFromAPI().get(name) return Response(quote) serializers.py: class Object1Serializer(serializers.ModelSerializer): class Meta: model = Object1 depth = 1 fields = '__all__' models.py: class Object1(models.Model): name = models.CharField(max_length=200) -
How create my own django model fiald to stor data in multy colums o related table
Help me find more complete examples of creating my own model fields, in special articles or simple examples from the source code. First of all interesting about store data in several columns of table or store or in a linked table. -
Sekizai TemplateSyntaxError where no sekizai is used
First of all this is Django 1.11.2 and sekizai 0.1 and this is in my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':[], 'APP_DIRS': True, 'OPTIONS': { 'builtins': ['mypage.templatetags.everywhere'], 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'sekizai.context_processors.sekizai', 'django.template.context_processors.i18n', ], }, }, ] Sekizai context processor included as it should be, however I still get this error: Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/ubuntu/workspace/project/apps/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/home/ubuntu/workspace/project/apps/django/core/handlers/wsgi.py", line 157, in __call__ response = self.get_response(request) File "/home/ubuntu/workspace/project/apps/django/core/handlers/base.py", line 124, in get_respon e response = self._middleware_chain(request) File "/home/ubuntu/workspace/project/apps/django/core/handlers/exception.py", line 43, in inner response = response_for_exception(request, exc) File "/home/ubuntu/workspace/project/apps/django/core/handlers/exception.py", line 93, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/ubuntu/workspace/project/apps/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/ubuntu/workspace/project/apps/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/ubuntu/workspace/project/apps/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/workspace/project/apps/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/workspace/hys/views/acc_settings.py", line 116, in horoscopedata context) File "/home/ubuntu/workspace/project/apps/django/shortcuts.py", line 21, in render_to_response content = loader.render_to_string(template_name, context, using=using) File "/home/ubuntu/workspace/project/apps/django/template/loader.py", line 68, in render_to_string return template.render(context, request) File "/home/ubuntu/workspace/project/apps/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/home/ubuntu/workspace/project/apps/django/template/base.py", line 207, in render return … -
Tastypie custom filtering model method
I have a UserCatalogResource which applies custom filtering on User model with apply_filters. Till this everything works fine and it returns the users whose username matches with the given query. Now I have a real() method in my actual User model class. I want to return u.real() for each users selected instead of returning the User Object. What method I need to override to do that ? -
Django. ImportError: No module named unicodedata
Today I was tried start my python web project by python manage.py runserver and get error: ImportError: No module named unicodedata When I tried to find solution of my problem I get some another errors. I try pip install unicodedata and get Fatal error in launcher: Unable to create process using '"' Then I try python -m pip install unicodedata LookupError: unknown encoding: idna So I try >>>import encodings.idna but have error again: ImportError: No module named unicodedata My python: 2.7.12. I tried to reinstall it, but it's did not help me So, this is my problem. -
How to write views.py for (status) check in models.py
how to select the choice parameter (published) in models from views.py. In models.py has choices option[draft,published] im using forms to collect the input and store it to database all the contents are working well except this one.sorry for my punishing english :) NameError at /blog/post/new/ name 'Published' is not defined models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES=( ('draft','Draft'), ('published','Published'), ) title=models.CharField(max_length=250) slug=models.SlugField(max_length=250,unique_for_date='publish') author=models.ForeignKey(User,related_name='blog_posts') body=models.TextField() publish=models.DateTimeField(default=timezone.now) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') objects=models.Manager() published=PublishedManager() views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone import datetime from .models import Post from .forms import PostForm def post_list(request): posts = Post.published.all() return render(request,'blog/post/list.html', {'posts':posts}) def post_detail(request,year,month,day,post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day ) return render(request, 'blog/post/detail.html', {'post':post}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published = timezone.now() post.slug=post.title post.status=Published post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post/post_edit.html', {'form': form}) Thanks for advance -
Python django serializer -> validated_data removes field
Goal: Add object to ManyToMany field of another DataModel. Data model with ManyToMany field: class ObservedDataModel(models.Model): domain_objects = models.ManyToManyField(DomainNameModel, blank=True) Following code works, but the foreign object id is hardcoded ((ObservedDataModel, id=2)): class DomainSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DomainNameModel fields = ('url', 'id', 'name') def create(self, validated_data): domain_obj = DomainNameModel.objects.create(name=validated_data['name']) observed_data_object = get_object_or_404(ObservedDataModel, id=2) # TODO !!!!!! observed_data_object.domain_objects.add(domain_obj) return domain_obj To let the user set the (ObservedDataModel, id=X) i´ve tried to send a request {'name': 'apple.com', 'observeddata': 2}, but the validated_data field does not contain the variable observeddata. So how can I add a custom (non-modell) field to the validated_data variable? -
How to Left Join on Django
I have to following models: class Playlist(models.Model): audio_files = models.ManyToManyField(AudioFile, related_name='in_playlists', class AudioFile(models.Model): listeners = models.ManyToManyField(User, related_name='listened_to', through='Progress', blank=True) class Progress(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE) lesson = models.ForeignKey(AudioFile, on_delete=models.CASCADE) progress = models.FloatField(default=0) Now I want a Django Query which lists all AudioFiles in a playlist but also attaches the progress in them for a specific user. In SQL this would be a LEFT JOIN. But I'm sure this is possible with django ORM as well. I have tried: playlistXYZ.audio_files.all().annotate(progress_num=models.Case(models.When(listeners__pk=1, then=models.F('listeners__progress__progress')), default=models.Value(0), output_field=models.FloatField())) But it doesn't do what i want. -
How to find the IP or Domain of a linking site.
I have three running web application A,B,C. A & B based on JAVA Wickets frame work. C is developed using Django. A & B have links to C which is Django app. Now I want to track from which app they have landed in C.