Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving protected files in Django without AWS S3
How to serve a protected files like picture, mp3, videos without amazon s3 in Django with Nginx and Digital Ocean? I am gonna use to Digital Ocean Droplet and want to configure it for serving protected files like pictures,mp3 and videos with Nginx. How can I implement it? Is it like I serve my file as FileSystemStorage on my local computer? With setting up all permissions related thing? from django.core.files.storage import FileSystemStorage class ProductFile(models.Model): file = models.FileField( upload_to=uploade_protected_file, storage=FileSystemStorage(location=settings.PROTECTED_ROOT) ) In my local environment, I serve my files in this way. And its work well. So same type of setup will work in Digital Ocean also? Thanks for help. -
Django private posts and public post example?
I am developing a django application that has private section and public section. How can I develop such app with django? I have tried having Model Manager and also template tags but neither make a user's post private. the following is my PostModelManager: class PostManager(models.Manager): def public_post(self, *args, **kwargs): # Post.objects.all() = super(PostManager, self).all() return super( PostManager, self).filter(public=True) def private_post(self, *args, **kwargs): # Post.objects.all() = super(PostManager, self).all() return super( PostManager, self).filter(public=False) -
Apache ImportError: No module named 'django'
Using django (I have tried many versions 1.8.7, 1.11.X, 2.0.1) python3.5 amd wsgi 4.5.24 compiled from source making sure that the python path set correctly /usr/bin/python3.5 I have an apache file with several wsgi sript aliases, all of which work except for the django script alias, which only failed when parsing the wsgi.py file because it can't import django. So first is the error from apache: [Tue Jan 02 18:46:32.247088 2018] [wsgi:error] [pid 2475:tid 139822294771456] [remote 192.168.254.101:2418] mod_wsgi (pid=2475): Target WSGI script '/var/www/protectionprofiles/protectionprofiles/wsgi.py' cannot be loaded as Python module. [Tue Jan 02 18:46:32.247260 2018] [wsgi:error] [pid 2475:tid 139822294771456] [remote 192.168.254.101:2418] mod_wsgi (pid=2475): Exception occurred processing WSGI script '/var/www/protectionprofiles/protectionprofiles/wsgi.py'. [Tue Jan 02 18:46:32.247523 2018] [wsgi:error] [pid 2475:tid 139822294771456] [remote 192.168.254.101:2418] Traceback (most recent call last): [Tue Jan 02 18:46:32.247637 2018] [wsgi:error] [pid 2475:tid 139822294771456] [remote 192.168.254.101:2418] File "/var/www/protectionprofiles/protectionprofiles/wsgi.py", line 12, in <module> [Tue Jan 02 18:46:32.247699 2018] [wsgi:error] [pid 2475:tid 139822294771456] [remote 192.168.254.101:2418] from django.core.wsgi import get_wsgi_application [Tue Jan 02 18:46:32.247772 2018] [wsgi:error] [pid 2475:tid 139822294771456] [remote 192.168.254.101:2418] ImportError: No module named 'django' and my apache config: <VirtualHost *:80> WSGIScriptAlias /certs /var/www/scripts/CavsCertSearch/CavsCertSearch/certstrip.wsgi WSGIScriptAlias /testcerts /var/www/scripts/CavsCertSearchTest/CavsCertSearch/certstriptest.wsgi WSGIScriptAlias /debug /var/www/scripts/debug/debug.wsgi WSGIDaemonProcess protectionprofiles python-path=/var/www/protectionprofiles WSGIProcessGroup protectionprofiles WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias /pp /var/www/protectionprofiles/protectionprofiles/wsgi.py process-group=protectionprofiles <Directory /var/www/protectionprofiles/protectionprofiles> … -
Django shared db with restricted views per user
I have a db that is to be shared. Where if a object has a certain value I need specific users to be able to see and edit it. No other users can see or edit these objects. I am trying to understand what way one should do this. I don't know django very well. I am currently looking at conditionals for views. Not sure if that is even possible given i don't know if conditionals on views can filter objects from models. If anyone could point me in the right direction I would greatly appreciate it. -
Django Client().login() creates Anonymous user even when returning True
I am writing Django tests for views and have run into a problem where Client().login(...) returns True but creates AnonymousUsers, which have no attributes. First, I create the user in a test mixin class like : @classmethod def setUpTestData(cls): super(BareSetupClass, cls).setUpTestData() cls.regular_user = User.objects.create(email='test_user@test.com', first_name='test', last_name='user', confirmed_email=True ) cls.regular_user.set_password("password") cls.regular_user.save() Then I login in the test class like so: class UserGroupViewTestSuite(BareSetupClass): @classmethod def setUpTestData(cls): super(UserGroupViewTestSuite, cls).setUpTestData() cls.user = Client() cls.user.login(username="test_user@test.com", password="password") I have checked the value returned by calling login and it is True but the user I get from Client is still AnonymousUser, which inhibits my views from functioning properly. Thank you ahead of time! -
How to select unique records with minimum value of specific field in django?
I have a following model: class Product_shipment(models.Model): product_dscr = models.ForeignKey(Product_dscr, related_name='product_dscr', on_delete=models.CASCADE) import_date = models.DateTimeField(auto_now=True) stock = models.PositiveIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) I need to create an object with unique product_dscr. Duplicates should be chosen based on the minimal value of import_date. Following SQL code works fine: select id, import_date, stock, product_dscr_id from shop_product_shipment where import_date = ( select min(import_date) from shop_product_shipment as s where s.product_dscr_id = shop_product_shipment.product_dscr_id); Can anyone gimme a tip how to translate in Django? -
Updating a model from a dictionary object efficiently
I have a simple model: class A(models.Model): status=models.CharField() and I have a list of dictionary items in this way: data=[ {'id':1, 'status':'moved'}, {'id':2, 'status':'sized'} ] the id and status keys are related to the model fields. Currently, I am updating them by looping the data and it was ok. But the web service sent a long list the other day and it got me thinking, what if they don't send for days and when they send, it can be a big list. Since i don't have control over the data passed to me, what would be the most efficient way to make the updates? Currently: for i in range(len(data)): record=A.objects.get(pk=data[i]['id']) record.status=data[i]['status'] record.save() I am looking for something like .filter().update(....) but with status that can apply differently to each record. Any one? -
Django Set Form Field Value In Post Request
I am trying to set a form field value in views.py inside the Post request using data from request.session and then save that data to the db. However, I am having trouble figuring out how to do that. Here is what I've tried: if self.form.is_valid(): #attempt 1 request.POST._mutable = True self.form.data['field'] = request.session['key'] #attempt 2 self.form.fields['field'] = request.session['key'] #attempt 3 self.form.cleaned_data['field'] = request.session['key'] self.object = self.form.save() Is there a way to do this? -
List in template tag used in javascript file
As title say I want to use list from views.py to javascript file. I read this topic, but in my case it doesn't work: link My views.py: ... arr = ['first', 'second', 'third'] return render(request, "something.html",{"array": arr}) ... something.html: ... <script> array_js = eval("{{ array|escapejs }}"); </script> <script src="{% whatever.js %}"></script> ... I am using array_js in whatever.js file. It's works fine, but I am using eval function. I don't want to use it, but I don't know how to make it work without eval function. I am beginner, so please be patient. Thank You -
Django access the uploaded file from a model form
I am currently learning to use Django to create web apps and have problem with the admin site of Django. I created a model named AccountList and registered it in admin site, then I am able to add an account or modify one. Now, I want to make the administrator could add multiple accounts by upload a file. Here is what I have already done: I create a modelform in forms.py called AccountForm, add a new filefield called extra_file, which is used to upload the file containing accounts. class AccountForm(forms.ModelForm): extra_file = forms.FileField() def save(self, commit): ``` Some work here ``` pass class Meta: model = AccountList fields = ['game_id'] Then in admin.py, I override the get_form method so when i click add button, it would let me to upload a file rather than fill in every fieldsite manully. class UploadAccount(admin.ModelAdmin): list_display = ('game_id' , 'account_id' , 'name_list' , 'type_list') def get_form(self, request, obj=None, **kwargs): if obj: return super(UploadAccount, self).get_form(request, obj, **kwargs) else: return AccountForm Now, when I click the add button at admin site , the view looks like this, result I suppose the uploaded file should be handled in AccountForm.save() method, like loading each line and save it … -
Django rest framework and Cloudinary
Can someone help me to understand why I got this error response: [02/Jan/2018 22:05:11] "POST /api/v1/images/ HTTP/1.1" 400 43 when I try to upload a new image. { "error": "Not a valid string." } I completely new in Django world and a try to follow a tutorial but for some reason, my code didn't work and I try to debug my code but I can't understand why is not work for me. I hope someone can orientate me to go a good way. This my model from django.db import models from core.models import TimestampedModel class Image(TimestampedModel): image = models.CharField(max_length=350) def __str__(self): return self.image this my view from random import randint from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from rest_framework.parsers import MultiPartParser, FormParser from cloudinary.templatetags import cloudinary from .serializers import ImageSerializer from .models import Image class ImageCloud(APIView): parser_classes = (MultiPartParser, FormParser,) serializer_class = ImageSerializer def get(self, request, format=None): images = Image.objects.all() serializer = ImageSerializer(images, many=True) return Response ({'images': serializer.data}, status=status.HTTP_200_OK) def upload_image_cloudinary(self, request, image_name): cloudinary.uploader.upload( request.FILES['image'], public_id=image_name, crop='limit', width='2000', height='2000', eager=[ {'width': 200, 'height': 200, 'crop': 'thumb', 'gravity ': 'auto', 'radius': 20, 'effect': 'sepia'}, {'width': 100, 'height': 150, 'crop': 'fit', 'format ': 'png'} ], tags=['image_ad', 'NAPI'] … -
Django: Referencing objects within a model - best practise
I'm currently going around in a bit of a "QuerySet' object has no attribute '' <> app.models.DoesNotExist: Messages matching query does not exist loop. Essentially, I'm trying to define "last_activity" on a Room model that is referencing the time at which the last Message associated to that room was sent. This is my attempt: class Room(models.Model): """ This model class sets up the room that people can chat within - much like a forum topic. """ title = models.CharField(max_length=255) staff = models.BooleanField(default=False) slug = models.SlugField(max_length=250, default='') banner = models.ImageField(storage=USER_UPLOAD_LOC, null=True, blank=True) def last_activity(self): last_persisted_message = Messages.objects.filter(where=self.title).order_by('-sent_at')[:1] return last_persisted_message.sent_at class Messages(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) where = models.CharField(max_length=255) message = models.TextField(default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) username_from = models.CharField(max_length=255) username_to = models.CharField(max_length=255, default='all') sent_at = models.DateTimeField(default=datetime.datetime.now) I've tried so many things now and referenced the query set documentation and nothing seems to be working. I can also confirm that the "where" field for the Messages model is populated when a message is created by {{ room.title }}. I'm using a web socket connection on the client side to pass a "message" back to the websocket consumer.py which then persists the message to the DB). -
How to pass Django Context dict to Angular JS
I am pretty new to Angular and learned only so much to help with the project i am working on. I have a scenario where i want to pass context dictionary from Django view to imported Angular JS file. I was able to read properly to JS as jdata but unable to pass same data to Angular js js/main.js file . I tried following did not work. <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>Welcome to My Site!</title> <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.0- rc.0/angular.js" data-semver="1.4.0-rc.0"></script> <script type="text/javascript"> var jdata = "{{ data | safe }}"; console.log(jdata); </script> <script src="{% static "js/main.js" %}"></script> </head> <body ng-controller="MainCtrl" > {% verbatim %} <div ng-init="weights={{ data }}"> </div> {% endverbatim %} <div ng-repeat="weight in weights"> {% verbatim %} <input type="radio" ng-model="selectedValue.name" ng-value="weight.name" ng-change="changeValue(weight.name)"> <label for="{{ weight.name }}">{{ weight.name }} </label> {% endverbatim %} </div> <div ng-repeat="weight in weights" ng-if="weight.name === selectedValue.name"> {% verbatim %} <label ng-repeat="wei in weight.values"> <input type="checkbox" ng-click="checkBoxChange(wei)" ng-value="wei" /> {{wei}} {% endverbatim %} </label> </div> {% verbatim %} <div>Selected object : {{selectedValue}}</div> {% endverbatim %} </body> </html> cs/main.js file app.controller('MainCtrl', function($scope, $window) { //$scope.weights = data; $scope.weights = [ { name: 'class1', values: ['1','2','3'] }, { name: 'class2', values: ['4','5','6'] }, { name: … -
Django ORM: Extremely slow response when no record exists
There are about 10 million records in the PostgreSQL table described by the following Django (1.11) model: class Tweet(models.Model): id = models.BigIntegerField(primary_key=True) user_id = models.BigIntegerField(db_index=True) text = models.TextField() created = models.DateTimeField(db_index=True) meta = JSONField(blank=True, null=True) To find the last Tweet by a user, I execute the following query: Tweet.objects.filter(user_id=user.id).order_by('-created').first() If the user has tweets in the db, it returns the last tweet instantly. However, if the user.id does not exist, it takes minutes to return a None. Even more strangely, when I run the generated queries directly on Postgres console, they both execute very fast. I've found a solution to check if any record exists first with .exists(): Tweet.objects.filter(user_id=user.id).exists() and then check for the last record. Now the total query times are reasonable but it doesn't feel right and there seems to be something wrong with Django ORM layer's interpretation of this case. Any ideas? -
How can I edit the urls.py of allauth?
I want to edit the urls.py of allauth by removing the links to the change email and password reset pages. Is there a way I can edit the urls.py in order for these pages to not display and return a 404 when the user tries to access them? -
Using django-postman with tabination
Currently, I'm working on some Django project which requires messaging between users. I've read some posts and I've decided to use django-postman. Now, I want to have two tabs on my homepage. The first one should contain a form to send a message to a particular user and I know how to create it. The second one should be an inbox (like on Gmail), where the user should find all of the incoming messages. My question is - what's the best way to implement django-postman on the second tab? I've found a snippet called django-tabination, but I'm not sure if I need this tool and I find it a little bit too complicated. Maybe I should follow this tutorial (with some changes - for example, uses Django includes instead of extra divs). Thanks for your help! -
Javascript not adding class to html element
I have stumbled upon a somewhat weird problem. I don't seem to be able to edit the class on my html elements. I have been looking into similar cases here on SO but found nothing that solves my problem. The only thing that makes this case somewhat different is that I am using the Django framework to reflect the backend. My code down here adds the class "form-control-danger" to all input fields that in some way have received erroneous inputs. Observe the code within the tags on the bottom. <form class="form" method="post" action="/register/"> {% csrf_token %} {% for field in register_form %} {% if field.name != "agree_to_terms" %} <div class="input-group"> <span class="input-group-addon"> {% if field.name == "first_name" %} <i class="now-ui-icons users_circle-08"></i> {% elif field.name == "last_name" %} <i class="now-ui-icons text_caps-small"></i> {% elif field.name == "email" %} <i class="now-ui-icons ui-1_email-85"></i> {% elif field.name == "password1" %} <i class="now-ui-icons ui-1_lock-circle-open"></i> {% elif field.name == "password2" %} <i class="now-ui-icons ui-1_lock-circle-open"></i> {% endif %} </span> {{ field }} </div> {% else %} <div class="form-check"> <label class="form-check-label"> {{ field }} <span class="form-check-sign"></span> I agree to the <a href="#">terms and conditions</a>. </label> </div> {% endif %} {% endfor %} {% if error_fields_by_id %} <script> {% for … -
Django - operate on database within transaction.atomic block after raising error
I would like to perform an action on my database within a transaction.atomic() block, even in the event that an error is raised. Here is some sample code to demonstrate my issue: Sample code # Outer try block try: # Enclose in atomic transaction for database rollbacks with transaction.atomic(): # If this line fails, all database updates within the outer try: block should be rolled back u = UU.create(email='test@test.com') # Inner try block try: cc = CC.objects.get(id=1) perform_action(cc) # If this exception triggers, the 'cc' object should be deleted, but all other database updates within the outer try: block should be rolled back except: cc.delete() raise # If this line fails, all database updates within the outer try: block should be rolled back u = UU.create(email='test@test.com') # If any exception triggers, this error should be printed except: print("Error occured.") If an error occurs in my inner try: block, I want the cc object to be deleted, but all other database transactions within the outer try: block to be rolled back. However, as the code stands now, the cc.delete() transaction will be rolled back if any error occurs within the inner try: block. Any suggestions? -
Django 1.8.5 migrations not working
I'm working on a Django 1.8.5 app with a MySQL database, with two other developers. We've made changes to models.py, and now I'm trying to run migrations. When I run python manage.py makemigrations it returns "No changes detected." When I run python manage.py migrate it returns: Operations to perform: Synchronize unmigrated apps: webstack_django_sorting, staticfiles, debug_toolbar, messages, linaro_django_pagination, humanize, django_tables2 Apply all migrations: admin, schools, contenttypes, auth, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: No migrations to apply. I've tried deleting migration files/resetting migrations, as suggested in other posts, and nothing changed when I ran the makemigrations or migrate commands after deleting/resetting. I've also tried python manage.py makemigrations app_name but get the same results. The two other developers on my team have run the migrate commands successfully. When they run python manage.py makemigrations they're then prompted to rename old fields to match new fields in both models in our app. I'm not prompted with this; as I mentioned above, I'm told no changes are detected. I'm working from the same code they are; pulled it from GitHub this morning, and we made sure what I'm working with is the most recent version. It … -
How do you convert a Django model with ManytoMany field to an elasticsearch_dsl DocType class?
I'm using elasticsearch_dsl to help with interfacing with elasticsearch and this is the model I currently have and I'm trying to recreate as a DocType: class HouseIndex(DocType): house_type = String() #people sold = Boolean() built_datetime = Date() #alerts # associated_locations hash = String() class House(models.Model): house_type = models.ForeignKey(HouseType, db_index=True, on_delete=models.CASCADE) people = models.ManyToManyField(to='Person', db_index=True, through='PersonToHouseMap') sold = models.BooleanField(default=False) built_datetime = models.DateTimeField() alerts = models.ManyToManyField(Alert) associated_locations = models.ManyToManyField(to='Location') hash = models.CharField(max_length=64, unique=True, null=True) objects = DistinctAlertManager() But I'm not sure what to do when it's a ManyToMany field. Such as with people, alerts, and associated locations. -
Django - Why PATCH returns in response correct data which I would like to save but it doesn't save this data in database?
Any ideas why PATCH returns in response correct data which I would like to save but it doesn't save this data in database? def patch(self, request, object_id): try: object = Object.objects.get(id=object_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django-admin.py makemessages -l fa doesn't crate .po files
i want to add fa(persian) language to my app, i created the locale folder inside my app and a folder named 'fa' inside that. when i use the following command it runs without any errors,but doesn't create .po file(i use cmd inside my app's folder) django-admin makemessages it only writes this processing locale fa i also used this command but it didn't help django-admin.py makemessages -l fa i use windows 7 -
How can a type be incompatible with itself?
In my django application (Django 1.6.0, python 2.7.5 running on Red Hat), my database driver is seeing an error from ctypes: TypeError: incompatible types, LP_c_int instance instead of LP_c_int instance The code looks like this: is_null = value is None param.value.is_null = pointer(c_int(is_null)) <-- error occurs on this line I'm not really familiar with ctypes (I inherited this code) but on the surface, this error message makes no sense. The code has been running for years but I'm now seeing this error all over the place. Am I doing something obviously wrong? -
Django admin: Making a required field read-only
I have a number of models with a ForeignKey relationship to a Person model. For example: class PersonData(BaseModel): person = models.ForeignKey(Person) data = models.TextField() I want to lock down the admin such that once a PersonData object is created, an admin user can change the data, but can't change the Person. At first it seemed pretty straightforward -- I put this in the PersonDataAdmin class: def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ('person',) return self.readonly_fields On the display side, that worked as expected -- I see the value for person, but it's grayed out so I can't change it -- but then when I try to change the data and submit the form, I get an error message, "Please correct the error below." No other message appears, but with a bit of digging, I discovered that the form is missing a value for the required person field. I've investigated a solution that would involve creating a custom form that would disable this field selectively (something like this or this), but (a) I wasn't successful in getting it to work, and (b) it seemed like a ton of code for what seems like a much simpler situation. Any ideas … -
Template is displaying object name instead of value
My template used to show the data correctly before I changed my model to add the following OrgLevel prior to my custom User table. class OrgLevel(models.Model): coid = models.CharField(db_column='Coid', max_length=5, primary_key = True, unique = True) # Field name made lowercase. slevel = models.CharField(db_column='SLevel', max_length=6) # Field name made lowercase. blevel = models.CharField(db_column='BLevel', max_length=6) # Field name made lowercase. rlevel = models.CharField(db_column='RLevel', max_length=6) # Field name made lowercase. dlevel = models.CharField(db_column='DLevel', max_length=6) # Field name made lowercase. class Meta: managed = False db_table = 'OrgLevel' My Custom User model is defined as the following: 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.OneToOneField(OrgLevel, null=True, blank = True) 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 In my view I have the owner defined as: def profile(request): owner = User.objects.get …