Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access request object from within django admin's authenticate()
Is this anyhow possible to access the request object from within the django admin's authenticate() in custom auth backend? The reason for this is I want to keep and re-use the user's password (or a Kerberos ticket - not sure yet) to authorize an operation in another system, which uses the same LDAP backend. For this purpose I wanted to use request.session - but it doesn't seem to be accessible, at least not the easy way. If there's any other possibility to pass a value from the auth to the model, I'd be happy to get a suggestion as well. Thanks. -
How to translate an Angular Bootstrap UI modal in a Django app
There's an application written in Django 1.8 where some modals are displayed with angular.js using UI Bootstrap. I would like to add translations to this modal, however while adding django translations tags, e.g. {% load i18x %}, {% trans 'some text'%}, etc., into the modal they are not interpreted by Django and simply displayed as text. Is there something I need to do before I get this working the Django way of doing it, or should I approach translations in this UI Bootstrap modal in a angular.js way? It the latter is true - how to do it? Translations outside of this modal are working fine... -
Django model form saves m2m after instance
I am having an issue with the way Django class-based forms save a form. I am using a form.ModelForm for one of my models which has some many-to-many relationships. In the model's save method I check the value of some of these relationships to modify other attributes: class MyModel(models.Model): def save(self, *args, **kwargs): if self.m2m_relationship.exists(): self.some_attribute = False super(MyModel, self).save(*args, **kwargs) Even if I populated some data in the m2m relationship in my form, I self.m2m_relationship when saving the model and surprisingly it was an empty QuerySet. I eventually found out the following: The form.save() method is called to save the form, it belongs to the BaseModelForm class. Then this method returns save_instance, a function in forms\models.py. This function defines a local function save_m2m() which saves many-to-many relationships in a form. Here's the thing, check out the order save_instance chooses when saving and instance and m2m: instance.save() save_m2m() Obviously the issue is here. The instance's save method is called first, that's why self.m2m_relationship was an empty QuerySet. It just doesn't exist yet. What can I do about it? I can't just change the order in the save_instance function because it is part of Django and I might break something else. -
Why do I get a small window for confirmation of change of a password?
I have a class named CambiarPassword into views.py. This class change a password. It's working! But when I'm changing a password I am getting this windows. Here is my code into views.py file: from django.views.generic import UpdateView from django.contrib.auth.forms import PasswordChangeForm class CambiarPassword(UpdateView): form_class = PasswordChangeForm template_name = 'app/edit_pass.html' success_url = '/index' def get_object(self, queryset=None): return self.request.user def get_form_kwargs(self): kwargs = super(CambiarPassword, self).get_form_kwargs() kwargs['user'] = kwargs.pop('instance') return kwargs How can I hide this window? -
How to save data about deleted records in the django-reversion?
To save the history of changes of objects I started using django-reversion. But there is one moment when a record is deleted from the database cannot get the record in the table changes history. What could be the problem?I have not found anything in the documentation. Does this library the historicity of the deleted data? -
Gunicorn in multithread gives a segfault on a lib when compiled with nuitka
When I run my django app with gunicorn in one thread everything is fine. When I run it with --threads=2 I get a segfault at launch time. My Django app contains a Python library compiled with nuitka to a .so file. When I replace this .so file with original .py files, it works well. To summarize Mono thread + original py files OK Mono thread + nuitka .so file OK Multi threads + original py files OK Multi threads + nuitka .so file segfault I use Python 3.5.2. Nuitka does not support 3.6 yet -
Freeze database time in unittests (django & sqlite)
I have a query which generates a score based on the age of a view. As you can see I am doing the age calculation in the SQL. The query looks something like. SELECT SUM(1.0 / (julianday('now') - julianday(view.date))) as score FROM view; In my unit tests I want to do something like self.assertEqual(actual_score, expected_score) Normally, if I was doing the age calculation in python I could just freeze time with something like django.test.utils.freeze_time. However since the date diff is being done in SQL that is not a possibility. How can I freeze time in my unit tests such that julianday('now') produces a configured value and I can accurately calculate the expected score. -
Django with Mariadb can't insert data
database user can connect to server from another place. of course it has access permission. server firewall disabled. import pymysql def ConnectToDatabase(): return pymysql.connect(host = "hostName", user = "databaseUserId", password = "databaseUserPw", db = "databaseName", charset = "utf8") def DisconnectDatabase(databaseConnection) : databaseConnection.close() def ExecuteQueryToDatabase(executeAbleQuery) : databaseConnection = ConnectToDatabase() databaseResultDataCursor = databaseConnection.cursor() databaseResultDataCursor.execute(executeAbleQuery) databaseResultDataRows = databaseResultDataCursor.fetchall() DisconnectDatabase(databaseConnection) return databaseResultDataRows def ClientRequestQuery(request) : dbQuery = request.GET.get('query',';') print dbQuery return HttpResponse(ExecuteQueryToDatabase(dbQuery)) def TestQuery(request): ExecuteQueryToDatabase('insert into User2 (`a`, `b`, `c`, `d`) values(1, 2, 3, 4);'); return HttpResponse("test") the code is just connect to mariadb and insert some data but when i try this code, the data is gone with no error and return "test" successfully the table structure is MariaDB [ServiceDatabase]> desc User2; │+-------+---------+------+-----+---------+-------+ │| Field | Type | Null | Key | Default | Extra | │+-------+---------+------+-----+---------+-------+ │| a | int(11) | NO | | NULL | | │| b | int(11) | NO | | NULL | | │| c | int(11) | NO | | NULL | | │| d | int(11) | NO | | NULL | | │+-------+---------+------+-----+---------+-------+ │4 rows in set (0.00 sec) the django version is 10.0.2 the python version is 2.7.12 can anyone help me? -
filter by month in list_filter django admin
I need to add to the list_filter in Django Admin sheet filter with filtering by month, so it appears as a month and year. January 2017 December 2016 November 2016 -
Django server error: ImportError: No module named dal
I'm working with a Django server not coded by me. I have already installed all dependencies using pip install -r requirements, but when I'm trying to execute manage.py I get this error. Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named dal The solution should be something like pip install dal, but when I try it, I get another error: there is no dal module. I'm using Python 2.7 and Django 1.9.8 -
Apache does not respond and no mod_wsgi.pyc is created
in my Debian server I have installed 4 Django projects. All of them with similar configurations. One of them is not responding. Apache tries for 1-2 minutes and then gives me an Error 500. In the log file I get this error message: Premature end of script headers: wsgi.py I also notice that wsgi.pyc is not created, that means that wsgi.py is not compiled. Some facts that might help: Debian Server has 4GB or RAM, only At my work PC I am using python3, on Debian Server I have to use Python2.7 and so my debian's virtualenv is created using python2.7 (I am not using an python3 specific libraries, though). Site worked the first time. Then a bug appeared and had to correct it. Since then, Apache does not want to load it. However this problem is not related to this bug because I reverted the modified file and I still can't load the whole site I uploaded all files from my work-pc to the server (even *.pyc) (apart from migration files, settings.py, etc) -- this is not the production server so that's ok, I guess. This is my wsgi.py import os, sys, site site.addsitedir('/home/user/.virtualenvs/project/lib/python2.7/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") activate_this = os.path.expanduser("/home/user/.virtualenvs/project/bin/activate_this.py") … -
Connect to MySql on VPS from google app engine app
I have a MySql database on my VPS which is updated daily(php app). I want to access this database on my google app engine project(django app). What is the best way to do? I know it can be done using sockets api on google app engine. Can someone help me with a sample code or suggest me other options if available? Thank you! -
Check User online Django 1.10.
Hi trying to do like in example: How to check whether a user is online in django template? but when adding 'userprofile.middleware.ActiveUserMiddleware', to MIDDLEWARE_CLASSES recieving next error: Unhandled exception in thread started by <function wrapper at 0x7fcf6e0b8668> Traceback (most recent call last): File "/home/pavlo/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/pavlo/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 40, in inner_run http_consumer=self.get_consumer(*args, **options), File "/home/pavlo/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 136, in get_consumer return StaticFilesConsumer() File "/home/pavlo/.local/lib/python2.7/site-packages/channels/handler.py", line 332, in __init__ self.handler = self.handler_class() File "/home/pavlo/.local/lib/python2.7/site-packages/channels/staticfiles.py", line 18, in __init__ super(StaticFilesHandler, self).__init__() File "/home/pavlo/.local/lib/python2.7/site-packages/channels/handler.py", line 179, in __init__ self.load_middleware() File "/home/pavlo/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 82, in load_middleware mw_instance = middleware(handler) TypeError: this constructor takes no arguments Thx for help. -
Embed a .doc/.docx/.odf/.pdf/.ppt/.pptx file in html and render them
I have few documents stored in s3. The formats they are in are not in my control. I need to render/view them in my html page. When I used the below code it is downloading the file when i load that tab instead of rendering them. My application is written in python, django. Can you help me with any plugins/javascripts or anything that can help me solve the issue. -
Django auto assign a value to a model field on_save in admin
I am a bit lost again. I am a beginner in this. I have two models: class Person(models.Model): name = models.CharField(max_length=200, default="Name") phone = models.CharField(max_length=12, default="+22123456789") ... class Adress(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) city = models.CharField(max_lenght=200, default="City") ... In my admin.py I edit them inline so on one form I can have all the person data and few of his addresses. This is important. I do need to have a relation of a single person to 1-3 addresses. from django.contrib import admin from .models import Adress from .models import Person class AdressInline(admin.TabularInline): model = Adress class PersonAdmin(admin.ModelAdmin): inlines = [ AdressInline ] admin.site.register(Person, PersonAdmin) Now ... the problem is that there is no way to create a list_display with fields from both models. For my understanding list-display is flat, and there is no where to put 3 values of same field on it. I would like to have a list looking like this: list_display = ('name', 'phone', 'city') So ... my idea is to create an extra field in model Person called 'maincity' that would not be editable by user, but would be filled automatically based on the value in Adress model. After we save the form. I have found … -
Django - creating foreignkey for "to_field" if does not exist
I've got 2 models (+2 not important). Link custom save method is supossed to create kod automatically on create, and on update keeping kod unchanged. On create Lead, I want to create Link automatically if it does not exist. Whats the best method to do that? It's my second day of searching for best approaches when it comes to custom save methods with foreignkeys but im lack of ideas. class Link(models.Model): landing = models.ForeignKey(Landing, default=1, on_delete=models.PROTECT) partner = models.ForeignKey(Partner, default=1, on_delete=models.PROTECT) kod = models.CharField(max_length=16, unique=True, blank=True, null=False) def save(self, *args, **kwargs): if self.kod is None: self.kod = id_generator(16) if len(self.kod) != 16: self.kod = id_generator(16) if self.pk is not None: current = Link.objects.get(pk=self.pk) if current.kod != self.kod: self.kod = current.kod super(Link, self).save(*args, **kwargs)` class Lead(models.Model): link = models.ForeignKey(Link, to_field='kod', on_delete=models.PROTECT) transactionid = models.CharField(max_length=64, blank=True) -
saving the first model only when the submit is clicked on the second form
First Model: Sub, Second Model: Seq. I'm having trouble implementing a next button. All I need to do is save the first Model when the second Form's submit button is pressed on seq.html. The data must save on both models when the submit button is pressed on seq.html. My current method where the code is below saves the first Model and then second model separately. Thanks in advance I would appreciate a short a example with some explanation. There could be some Javascript involved but I'm pretty sure there is a way to do it with Django. Models.py class Sub(models.Model): description = models.TextField(max_length=1000, blank=True) submitter = models.ForeignKey(User, null=True, blank=True, default=None) class Seq(models.Model): submission = models.OneToOneField(Sub) size = models.PositiveSmallIntegerField(default=0) description = models.TextField(max_length=1000, blank=True) Forms.py class SubForm(forms.ModelForm): class Meta: model = Sub fields = ('description') class SeqForm(forms.ModelForm): class Meta: model = Seq fields = ('size', 'description') Views.py def view_sub(request): form = SubForm(request.POST) if request.method == 'POST': if form.is_valid(): save_it = form.save(commit=False) save_it.submitter = request.user save_it.save() return HttpResponseRedirect('/view_seq/') else: form = SubForm(instance=request.user) return render(request, 'sub.html', {'form':form}) def view_seq(request): form = SeqForm(request.POST) submission = Submission.objects.filter(submitter = request.user).latest('created') if request.method == 'POST': if form.is_valid(): save_it = form.save(commit=False) save_it.submission = submission save_it.save() return HttpResponseRedirect('/pack_00') else: form … -
Indexing Django ArrayField or not?
Using Django 1.8 on a Postgres 9.6. One of my model has an ArrayField: packages = ArrayField( models.CharField( max_length = 200 ), blank = True ) First question is should I add index to it ? Documentation says At present using db_index will create a btree index. This does not offer particularly significant help to querying. A more useful index is a GIN index, which you should create using a RunSQL operation. But it's not clear what I should do with that. If yes, second question, is where to place "db_index = True" ? Like so?: packages = ArrayField( models.CharField( db_index = True, max_length = 200 ), blank = True ) -
Select a valid choice. '"xxx" is not one of the available choices
I know many people have been asking this question "Select a valid choice. 'xxx' is not one of the available choices." but I just think my scenario is somewhat different. Well, what I was trying to do is; I have an input choice field that allow someone to choose between two choices (Let's say choices are A and B). Hence if someone decides to choose choice A; some of available input fields will disappear while holding default values that i have assigned to them (this is to allow form submission. I can't make them required=False since if you choose choice B, this input fields will appear and if required=False they may be submitted without values.Something that I don't want): $('select[name=fuel] option:eq(1)').attr('selected', 'selected'); $('#id_cars').append($('', { value: 'AA', text: 'AA', })); $('id_total_fruits').val(0); The challenge was, cars input choice field is retrieving information from the database, but i wanted to make sure even if the table is empty someone have to be able submit the form. This is why I decided to append value to be able to submit my though; even though doing this makes me getting this error: "Select a valid choice. 'xxx' is not one of the available choices." I … -
Is it safe to delete the `django_session` table if my Django app is using a cache-based session backend?
I've enabled cached-based sessions, and it looks like the application is no longer using the django_session database table. Is it safe to delete it? Or will the next migrate just recreate it? Should I should just leave it in place, even if it's empty and isn't being used? Does it even matter? Thanks! -
Django ManyToManyField: 'function' object is not subscriptable
So you realize that the foreign key you have in your model should really be a m2m and you've adopted the practice to provide models.CASCADE as positional argument to a Foreign Key. So you end up with this code: class Group(models.Model): members = models.ManyToManyField(Person, models.CASCADE) You "fix" a few other things and suddenly end up with this tail of a backtrace with everything you try to do: File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 157, in __new__ new_class.add_to_class(obj_name, obj) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.5/site-packages/django/db/models/fields/related.py", line 1516, in contribute_to_class elif self.remote_field.is_hidden(): File "/usr/local/lib/python3.5/site-packages/django/db/models/fields/reverse_related.py", line 144, in is_hidden return bool(self.related_name) and self.related_name[-1] == '+' TypeError: 'function' object is not subscriptable What's going on? -
Celery tasks same schedule with offset
I have several tasks, something like this: CELERYBEAT_SCHEDULE = { 'task1': { 'task': 'api.tasks.task1', 'schedule': timedelta(seconds=10), }, 'task2': { 'task': 'api.tasks.task2', 'schedule': timedelta(seconds=30), }, 'task3': { 'task': 'api.tasks.task3', 'schedule': timedelta(seconds=15), }, ... } So, task1 will be run in *:*:10, *:*:20, *:*:30, *:*:40, *:*:50 and *:*:00 task2 will be run in *:*:30 and *:*:00 task3 will be run in *:*:15, *:*:30, *:*:45 and *:*:00 Then the tasks concurs always in *:*:30 and *:*:00. Is there any way to add an offset. I want to get something like this: task1 (offset=2) run in *:*:12, *:*:22, *:*:32, *:*:42, *:*:52 and *:*:02 task2 (offset=7) run in *:*:37 and *:*:07 task3 (offset=0) run in *:*:15, *:*:30, *:*:45 and *:*:00 I have read the documentation, and I think I must use crontab, but is not there another way more nice? -
django - how to query by string
In Product model and i want to query by food title html url: <a href="{% url 'product' food_name=catalog.food_name|urlencode %}">some text</a> views.py: def product(request, food_name): product = Catalog.objects.get(food_name=food_name) return render(request, 'food/product.html', {'product':product}) url.py url(r'^product/(?P<food_name>\w+)/', food_views.product, name='product'), Trace NoReverseMatch: Reverse for 'product' with arguments '()' and keyword arguments '{u'food_name': u'%D9%86%D8%A7%D9%86%20%D8%A8%D9%88%D8%B1%DA%A9'}' not found. 1 pattern(s) tried: [u'product/(?P<food_name>\\w+)/'] -
Django project cannot find application module
I am following the Tango with Django book's tutorial. I tried to do: from range import views in tango_with_django_project/urls.py where rango is the application. The IDE I use is pycharm and it cannot find or doesn't recognize rango. The folder hierarchy is as follow: rango __init__.py ... views.py tango_with_django_project __init__.py ... urls.py Any help or comment is greatly appreciated. Thank you. -
Database tables viewing and filtering app in Django
I am working on a Django based database system. Up to this point I was using django's admin app as a base. It seemed great at first but when I got to the point that I want to present the data from tables and enable user to search and filter columns I noted that the 'admin' app was really not meant to be used in such context. My question is if there is a better base that I could use? I searched django packages repository but could not find any app devoted to the above problem specifically. I could write my own app for this but the functionality I need seems so common that I am sure that it was done in the past and I don't want reinvent the wheel, so to speak. All suggestions are welcomed.