Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Codebase migration from PHP to Python - is it worth it?
I want to ask if it's worth it to move big project (developed for couple of years) written in PHP to another language? For instance Python (with Django framework)? Is it better to move part by part? Or maybe start new separate project in Python? Or leave it as is and improve PHP code quality? Do you have any experience with such migrations? Thanks! -
Using Lunrjs full text search in Django backend for adding items to search?
Would it be possible to use the lunrjs object in the Django backend from an axios ajax call and then add an object to the lunrjs object? I want to do this in my Django backend. I'm able to pass the object as a parameter to Django but when I try adding an item the lunrjs object won't let me add it. I think this is because the object is being treated as simply a dictionary and not actually the lunrjs object that I created on the frontend side. lunrjsObject.add({ "title": "Twelfth-Night", "body": "If music be the food of love, play on: Give me excess of it…", "author": "William Shakespeare", "id": "1" }) I'm doing this on the backend and not on the frontend because I have a bunch of items to add to the lunrjs object and that would cause the UI to freeze for a few seconds since it's a lot of data processing (bunch of loops/iterations to add the items to lunrjs object) -
Optimise Django subquery (currently using `annotate` and `Count`)
Using: Django 1.11, Postgres 9.6 I need to optimise a Django ORM query for consumption by the Django Rest Framework. The query must return records that: Match a list of IDs in their target field Limit the result set to records where a source ID appears more than once in the set. The current approach is to create a subquery using annotate and Count but the sheer amount of processing behind each request added to pagination means that the apps that it's causing timeouts or very slow behaviour. If there is anything that can be done by Postgres on the server as a raw query I'm fine with that. Model: class Relationship(models.Model): id = models.AutoField(primary_key=True) source = models.BigIntegerField(db_index=True) target = models.BigIntegerField(db_index=True) View snippet: match_list = [123, 456, 789] # dummy data for example queryset = Relationship.objects.filter(target__in=match_list) sub_queryset = (Relationship.objects.filter(target__in=_match_list) .values('source') .annotate(source_count=Count("source")) .filter(source_count__gt=1) ) sub_ids = [i["source"] for i in sub_queryset] queryset = (queryset.filter(source__in=sub_ids) ) The API takes a list of target IDs as an argument and responds with a list of all source IDs that are connected to that target. However, I'm filtering the queryset to only return source records that are connected to two or more targets. As background, … -
huey django version compatibility
I checked huey's documentation and searched online, but couldn't find version compatibility information of huey with django. Can someone please provide me this information? -
yaml file creator app with GUI
I'm newbie. I want to make a simple app where you enter some data and the app will generate a yaml file. with GUI. I know you might need more info, but I just need to know where to start. -
Django is not recognizing new table created in postgres
I have a table, say table_old, in postgres that is created by django ORM. I want to create a new table exactly like table_old except that it's empty with no data. To achieve this I have run following queries: CREATE TABLE table_new (like table_old); ALTER TABLE table_old RENAME TO table_old_backup; ALTER TABLE table_new RENAME TO table_old; As you see I want to replace an empty table with old one but django is not recognizing this new table. What's wrong with this solution? -
Share generic views between models
Is there any way to share a generic view between different models? I have 5 models and all of them need a ListView, CreateView, UpdateView, DetailView and DeleteView so, instead of creating all these classes for those 5 models, I'd like to create just one of each type for them. Any idea? -
Bad request 400 in Production because of static files
I have a problem with static files in Production after upgrading to Django 1.11. Before everything was working fine and I assume that all the setup is correct except some parts which probably have changed in new version of Django. To be more specific about the problem. I have static image on my index page. After update my Production server returns "Bad request 400" on index page. If some configurations are required then I can post it. Any ideas how to solve it are welcome! -
Django LDAP authn backend: user authenticated but unable to login
I have a strange issue with django ldap backend. this is my configuration: AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend' ) AUTH_LDAP_SERVER_URI = "ldap://XXXXXXx" AUTH_LDAP_BIND_DN = "CN=Pti Release,OU=Service-Accounts,OU=DD,DC=ad,DC=como,DC=com" AUTH_LDAP_BIND_PASSWORD = "XXXXXXXX" AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=DD,DC=ad,DC=como,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_X_TLS_REQUIRE_CERT: False, } AUTH_LDAP_GROUP_SEARCH = LDAPSearch("OU=DD,DC=ad,DC=como,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_superuser" : "CN=airflow-super-users_GLOBAL,OU=Global,OU=Security-Groups,OU=DD,DC=ad,DC=como,DC=com", "is_active" : "CN=airflow-data-profilers_GLOBAL,OU=Global,OU=Security-Groups,OU=DD,DC=ad,DC=como,DC=com", } AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_PROFILE_MODULE = 'main.UserProfile' AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "country": "c" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 When I attempt to login, the django auth_user is populated correctly but django shows me this form: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. And no way to login. Any ideas? -
Django French Translation - how to handle single quotes in translation strings?
I am using Python 3.5.2 and Django 1.10. I have received the French translation .po file and can run the compilemessages command without receiving any errors. However, when I run the site, many pages refuse to load. I suspect that this is because the French translation .po file contains many single quotes (') in the translation strings. For example, #: .\core\constants\address_country_style_types.py:274 msgid "Ascension Island" msgstr "Île de l'Ascension" I remember reading somewhere (but cannot find that reference anywhere) that the single quotes must have either a forward or back slash before them. So I tried that, but when I ran the compilemessage command, I got an error message of: C:\Users\me\desktop\myapp\myapp\locale\fr\LC_MESSAGES\django.po:423:18: invalid control sequence So how do I escape the French single quote in strings issue? here is the header of my French language .po file: # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-05-04 12:55+1000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" -
Different versions of Django are imported when Run and Debug in Pycharm
I want to upgrade a Django project from Django 1.2.5 to Django 1.11 on a server, and I added a remote project interpreter in Pycharm on my local machine. In order to switch between Django 1.2.5 and Django 1.11 conveniently, I downloaded the source code of Django 1.11 and added it to sys.path in manage.py by sys.path.insert(0, 'Django_1_11') where Django_1_11 is the folder of source code. When I Run my project, it works and Django 1.11 is imported. But when I Debug my project, Django 1.2.5 is imported even if Django_1_11 is in the sys.path. How can I import Django 1.11 in the Debug mode? -
Download array of images on click of a button
I have a very basic html block, which has a button to download: <div id="getImageWrapper"> <div class="image"> <p class="image-name">{{imageName}}</p> <button class="download-btn" @click="getImage">Download image/s</button> </div> </div> The getImage() function of the download button fetches an array of image list from the server. getImage() { const getImagesUrl = this.$store.state.website + '/api/get-requested-user-Images/'; this.$http.get(getImagesUrl) .then(function (response) { console.log(response.data); }) .catch(function (response) { console.log(response); }); } Response data from the server looks something like this: [ { "image": "/media/1492960503_66.jpeg" }, { "image": "/media/1492963100_0.jpeg" } ] My problem is what to do next so that this array of images is downloaded into the user's device (not as a single zipped file, but as separate single image files) which would work in most browsers? If it helps, I am using Django as the backend and Vuejs for the front-end. -
How to make sure one function is invoked only once in a period?
There is a chatting app which can transmit the message to my server, I do it because I want to save all the message record on my own server. Basically the chatting app send messages to the certain url, and I use Django to save them, I have done it already, I use a function called save_message(request) to save them(just write the messages to a text file). And now I want to write a program on the server which can send me an email when the message comes to the server, I have done it as well, I use a function called send_email() to do it. However, the problem is, I want to send email periodically. For example: If the server receives 1000 messages in 2 hours, I just want to receive one email.That is to say, this email will be sent once the first message is received, and for the rest of 2 hours, whether there are new messages, I won't receive any messages. If the server doesn't receive any messages in 2/4/8/... hours, then I won't receive any emails. I think every time the server receives message, it needs to invoke save_message(request), and also I think the send_email() … -
Annotate a QuerySet with the latest value from a filtered join
How can I, in a single expression, get the latest value from the filtered results of a many-to-one relationship to annotate a Django QuerySet? For the purpose of making a custom QuerySet in a Django LoremAdmin (for the Lorem model), I need to: Derive foo_status and bar_status each from separate JOIN clauses to a LoremStatusEvent model: lorem.loremstatusevent_set__status. Filter each join to only include those events which are for the corresponding Ipsum value: foo_status_events=LoremStatusEvent.filter(ipsum='foo'). Aggregate the set of status events to only the latest for each corresponding join: foo_status=LoremStatusEvent.objects.filter(ipsum='foo').latest('created').status. Annotate the results with a couple of extra values, foo_status and bar_status: queryset = queryset.annotate(foo_status=???).annotate(bar_status=???). How can I aggregate in an QuerySet.annotate on “latest by 'created' field”? I don't see any such documented aggregation function. The model knows how, with LoremStatusEvent.objects.latest, but I need an annotation function to use it in an annotation on a different queryset. Remember that all this needs to be done on a queryset of Lorem instances, accessing the related instances via Lorem.loremstatusevent_set; so I can't directly use methods of LoremStatusEvent. -
Django. Q objects dynamicaly generate
There is a filter for the model fields queryset = queryset.filter( Q(title__icontains=search_text) | Q(description__icontains=search_text) | Q(name_icontains=search_text) ) How i can do generate block according to circumstances Q(title__icontains=search_text) | Q(description__icontains=search_text)| Q(name_icontains=search_text) For example, in one case it is necessary that the filter be such Q(description__icontains=search_text) | Q(name_icontains=search_text) or Q(title__icontains=search_text) | Q(description__icontains=search_text) | or Q(title__icontains=search_text) I could generate Q objects using a dictionary for example search_text = 'somthing text' fields_name = ['title', 'description', 'name'] queries = [ Q({field+'__icontais': search_text}) for field in fields_name] but how this [<Q: (AND: {'title__icontais': 'first'})>, <Q: (AND: {'description__icontais': 'first'})>, <Q: (AND: {'name__icontais': 'first'})>] paste into filter and use OR separator -
Combine multiple tables for a json response in django rest framework
I am using django rest framework for my serializers. I need to create a webservice which combines fields in three tables and gives a json. I have three models like below : class FlightSchedule(models.Model): tail_number = models.ForeignKey(TailNumber, null=False) flight_number = models.CharField(max_length=30, null=False) flight_group_code = models.ForeignKey(FlightGroup, null=False) origin_port_code = models.ForeignKey(Port, null=False, related_name="Origin") destination_port_code = models.ForeignKey(Port, null=False, related_name="Destination") flight_departure_time = models.TimeField() start_date = models.DateField() end_date = models.DateField() # route_id = models.CharField(max_length=30, null=True) def __unicode__(self): return u'%s' % self.flight_number class Meta: verbose_name_plural = "Flight Schedule" class FlightScheduleDetail(models.Model): flight_date = models.CharField(max_length=30, null=False) # tail_number = models.ForeignKey(FlightSchedule, null=False, related_name="tail_number_schedule") flight_number = models.ForeignKey(FlightSchedule, null=False, related_name="flight_number_schedule") route_id = models.CharField(max_length=30, null=False, unique=True) flight_status = models.ForeignKey(Status, null=True, default=1) def __unicode__(self): return u'%s' % self.route_id class Meta: verbose_name_plural = "Flight Schedule Details" class LegDetail(models.Model): route_id = models.ForeignKey(FlightScheduleDetail, null=False, related_name="route_id_leg_detail") origin_port_code = models.ForeignKey(Port, null=False, related_name="Origin_leg") destination_port_code = models.ForeignKey(Port, null=False, related_name="Destination_leg") sequence_number = models.IntegerField() def __unicode__(self): return u'%s' % self.route_id + " > " + str(self.sequence_number) class Meta: verbose_name_plural = "Flight Leg Details" I need a response in json format as below : [ { "daily_details": [ { "date": "12/06/2017", "route_id": 123456 }, { "date": "13/06/2017", "route_id": 123457 } ], "flight_schedule": { "tail-number": "tailnumber1", "flight_number": "flightnumber1", "flight_group_code": "code1", "origin_port_code": "MUM", "destination_port_code": "BLR", … -
FastTenantTestCase django-admin sqlflush error
Using Django 1.10, DRF, postgresql as my DB. I have a tenant based system and I have used Django-Tenants to achieve it. I am writing test cases for my system. An example snippet class FastTenantTestCase(TenantTestCase): def setup_tenant(self, tenant): """ Add any additional setting to the tenant before it get saved. This is required if you have required fields. """ user = User.objects.create(email="admin@xxx.com", is_active=True) user.set_password('xxx') tenant.owner = user user.save() def remove_allowed_test_domain(self): if ALLOWED_TEST_DOMAIN in settings.ALLOWED_HOSTS: settings.ALLOWED_HOSTS.remove(ALLOWED_TEST_DOMAIN) def setUp(self): self.sync_shared() tenant_model = get_tenant_model() test_schema_name = self.get_test_schema_name() test_tenant_domain_name = self.get_test_tenant_domain() if tenant_model.objects.filter(schema_name=test_schema_name).exists(): self.tenant = tenant_model.objects.filter(schema_name=test_schema_name).first() else: self.tenant = tenant_model(schema_name=test_schema_name) self.setup_tenant(self.tenant) self.tenant.save(verbosity=0) self.domain = get_tenant_domain_model()(tenant=self.tenant, domain=test_tenant_domain_name) self.setup_domain(self.domain) self.domain.save() connection.set_tenant(self.tenant) def tearDown(self): connection.set_schema_to_public() self.remove_allowed_test_domain() class BaseSetup(FastTenantTestCase): def setUp(self): super(BaseSetup, self).setUp() self.c = TenantClient(self.tenant) self.tenant.create_roles(TENANT_DEFAULT_ROLES) self.tenant.assign_user_role(self.tenant.owner, TENANT_ROLE_ADMIN, True) def test_login_api_unsuccessful(self): response = self.c.post('http://xxx.localhost:8000/api/login/', {'email': 'xxx@xxx.com', 'password': 'xxx'}) self.assertEqual(response.status_code, 401) When i run this test, it gives this error: Traceback (most recent call last): File "/home/xxx/Documents/env_rest/local/lib/python2.7/site-packages/django/test/testcases.py", line 216, in __call__ self._post_teardown() File "/home/xxx/Documents/env_rest/local/lib/python2.7/site-packages/django/test/testcases.py", line 908, in _post_teardown self._fixture_teardown() File "/home/xxx/Documents/env_rest/local/lib/python2.7/site-packages/django/test/testcases.py", line 943, in _fixture_teardown inhibit_post_migrate=inhibit_post_migrate) File "/home/xxx/Documents/env_rest/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/home/xxx/Documents/env_rest/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/xxx/Documents/env_rest/local/lib/python2.7/site-packages/django/core/management/commands/flush.py", line 82, in handle six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2]) File "/home/xxx/Documents/env_rest/local/lib/python2.7/site-packages/django/core/management/commands/flush.py", line 72, … -
how to select * group by in Django models
I have a model: Syscheck(PostgreSQL table name: syscheck_syscheck), include some fields changes, size, uid, gid, filepath, syscheck_path How can I perform a SQL query like this SELECT * FROM syscheck_syscheck GROUP BY filepath I have tried: Syscheck.objects.values('filepath').annotate(Count('filepath')) It worked, but only filepath field return, when I want more fields return, I tried this: Syscheck.objects.values('filepath', 'size', 'uid', 'gui').annotate(Count('filepath')) It didn't work -
django.db.utils.DataError: numeric field overflow - django
I am trying migrate using django but I get this error and I have no idea what to do to fix it. I have google the error message but all it was talking about postgres. I have this in my model budget = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) # I used to have this though budget = models.IntegerField(null=True, blank=True) I was using this command python manage.py makemigrations which generates the alter table fine but when I run the migrate python manage.py migrate this error would pop up. Can someone please give me a hand? Thanks in advance. -
Django Custom Admin Panel Site Settings
For my learning I am making a forum style site in django. Previously I had created a Class based view for logging in and registering users. The next step I am hoping to complete is the admin control panel (not the django one, a custom one for the forum). There I want to be able to set site settings, like what is the default theme, etc. I am not sure how to proceed with this, any code or tutorial links will be taken. -
Redirecting to originally requested page after login in Django
I am new to Django. I needed to code the login feature to redirect to originally requested URL after login. I looked around and found the following on a stackoverflow thread. django redirect after login not working "next" not posting? I see the following in the Django documention login_required() does the following: If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example: /accounts/login/?next=/polls/3/. I also read that the login() method of django.contrib.auth package passes next to the template. So I defined the login() function in my view (I cannot use the one from the 'auth' package since I need some customization). def login(request): next = request.GET['next'] return render(request, 'user/login.html', {'next': next}) In my template <form method="post" action="{% url 'user:login_user' %}" > {% csrf_token %} <p><label for="id_username">Username:</label> <input autofocus="" id="id_username" maxlength="254" name="username" type="text" required /></p> <p><label for="id_password">Password:</label> <input id="id_password" name="password" type="password" required /></p> <input type="hidden" name="next" value="{{next}}" /> <button type="submit">Login</button> </form> In my login_user() function, if I see that the value of next is present, I redirect to that URL once I have logged the user in. However, solution presented in the thread above was a bit more involved. What am missing … -
django format_html not working with string_concat
I am trying to display a two line error message to a user. All attempts I have made have failed and I cannot figure this out, despite searching SO & google. The error I am getting is: Exception Type: IndexError Exception Value: tuple index out of range The issue seems to be the use of the format_html() with the string_concat(). Here is my python code: from django.utils import translation from django.utils.html import format_html from django.utils.translation import string_concat from django.utils.translation import ugettext_lazy as _ .... if not request.user.is_staff and language_versions_num_enabled > max_languages: error_message = format_html( string_concat( _(u'You are only permitted <b>{}</b> <u>enabled</u> Language Versions for the selected <b>{}</b> subscription plan.'), ' <icon class="fa fa-frown-o icon_size26 icon_padding"></icon>', '<br /><br />', _(u'Either select a different subscription plan or disable <b>{}</b> of your <b>{}</b> <u>enabled</u> Language Versions.'.format(max_languages, stripe_plan['title'], language_versions_num_enabled-max_languages, language_versions_num_enabled)) ) ) messages.add_message(request, messages.ERROR, error_message) else: I am really hoping someone can point out what I am doing wrong here. -
Django file validation error
I've been struggling with file validation for a while now but I think I'm on the right track. I'm trying to validate an audio file 'sound' when I post a form. Whenever I try and submit the form I get an 'InMemoryUploadedFile' object has no attribute 'content'. The problem seems to happen at form.is_valid(). So far I have in forms: class PostForm(forms.ModelForm): def clean_sound(self): file = self.cleaned_data.get('sound',False) if file: if not file.content-type in ["audio/mpeg","audio/mp3", "audio/wav"]: raise ValidationError("Content-Type is not mpeg") if not os.path.splitext(file.name)[1] in [".mp3",".wav"]: raise ValidationError("Doesn't have proper extension") return file else: raise ValidationError("Couldn't read uploaded file") class Meta: model = Places fields = [ 'usersave', 'title', 'longitude', 'latitude', 'sound', ] in the view: @login_required(login_url='/accounts/login/') def post_create(request): form= PostForm(request.POST or None, request.FILES or None) if form.is_valid(): # handle_uploaded_file(request.FILES['sound']) instance = form.save(commit=False) instance.save() messages.success(request, 'Successfully Created') return HttpResponseRedirect('/') context= { 'form': form, } return render(request, 'location/post_form.html',context,) I'm not sure what the 'InMemoryUploadedFile' error is, and would much appreciate any advice that could point me in the right direction! -
Django Rest Framework not working with simple nested serializer
I was converting my existing app to api based. The structure of my file is as follow: models.py class BookDetail(models.Model): title= models.CharField(max_length=10, default='title') author= models.CharField(max_length=10) series= models.CharField(max_length=10) edition= models.CharField(max_length=10) description= models.CharField(max_length=10) keywords= models.CharField(max_length=10) reading_age= models.CharField(max_length=10) genre= models.CharField(max_length=10) publishing_rights= models.CharField(max_length=10) def __str__(self): return self.title class Addon(models.Model): header= models.CharField(max_length=10) footer= models.CharField(max_length=10, default='1') additional_features = models.ForeignKey(BookDetail, related_name='additional_features', on_delete=models.CASCADE, null=True) def __str__(self): return self.header views.py class BookDetailsList(APIView): def get(self, request): stocks = BookDetail.objects.all() serializers = BookDetailsSerializer(stocks, many=True) return Response(serializers.data) def post(self, request): serializer = BookDetailsSerializer(data=request.data) print(serializer.is_valid()) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py class AddonSerializer(serializers.ModelSerializer): class Meta: model = Addon fields = ('header', 'footer') class BookDetailsSerializer(serializers.ModelSerializer): additional_features = AddonSerializer(many=True) class Meta: model = BookDetail fields = ('title', 'author','series', 'edition', 'description', 'keywords', 'reading_age', 'genre', 'publishing_rights','additional_features') # fields = '__all__' def create(self, validated_data): additional_feature = validated_data.pop('additional_features') book_detail = BookDetail.objects.create(**validated_data) for a in additional_feature: Addon.objects.create(additional_features=book_detail, **a) # Addon.objects.create(additional_features=book_detail, **additional_feature) return book_detail My input data is in JSON format { "title": "lolwa", "author": "asd", "series": "string", "edition": "a", "description": "as", "keywords": "sd", "reading_age": "aasd", "genre": "adasda", "publishing_rights": "aadasd", "additional_features": [{"header":"head", "footer":"foot"}] } This is working fine. But what I really want is not passing my additional_features as a list which I'm currently doing, I want … -
Django use base.html but table can't show
wanip.html base.html use base.html in wanip.html ,can't show table .how can I use base.html right?