Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I inherit from "app_settings.py" for django-allauth module's 'accounts' app?
I'm trying to extend django-allauth to do something specific to my projects. I'm basically trying to write my own wrapper on top of django-allauth, and want the installation, configuration and other stuff to be quite similar to allauth. For this, I started with extending AppSettings class from allauth/accounts/app_settings.py. I created my own app_settings.py did something like this: from allauth.account import app_settings as AllAuthAppSettings class MyAppSettings (AllAuthAppSettings): def __init__(self, prefix): # do something Also, at the end of the app_settings.py, I simply put the following (copying it from django-allauth itself): import sys my_app_settings = MyAppSettings('MY_PREFIX_') my_app_settings.__name__ = __name__ sys.modules[__name__] = my_app_settings Now, when I start my project, it gives me the following error: TypeError: Error when calling the metaclass bases __init__() takes exactly 2 arguments (4 given) Honestly, I'm quite new to the python-django world, and don't really understand what's happening in those last 4 lines. What is metaclass bases? What are the 4 arguments that are being passed to it? How do I make this flow work? Any help would be highly appreciated. -
Compare with lowercase in django authentication
I am using django authentication from django.contrib.auth import authenticate email = request.data['email'].lower() password = request.data['password'] user = authenticate(email=email, password=password) I want to compare email in lowercase from database. I know that we can compare using below method. user = User.objects.get(email__iexact=email) But how can I do in my case? How can solve this problem? -
502 Bad Gateway nginx/1.1.19 on django
I am new to this. I took the image of running django application and spawned the new vm that points to a different database but I am getting this "502 Bad Gateway nginx/1.1.1" when i tested this in development mode, it works fine but not otherwise. i looked into /var/log/nginx/access.log and error.log but nothing found there. Any help would be appreciated -
Creating file from Django <InMemoryUploadedFile>
I have a couple of .xlsx files uploaded from a form within a Django website. For reasons that aren't worth explaining, I need to get a file path for these file objects as opposed to performing actions directly upon them. Tl;dr: I'd have to spend days re-writing a ton of someone else's code. Is the following the best way to do this: Save objects as files Get filepaths of newly created files do_something() Delete files Thanks. -
Django - Migrating from Sqlite3 to Postgresql
I'm trying to deploy my Django app in Heroku, so I have to switch to PostgreSQL and I've been following these steps However when I run python manage.py migrate I get the following error: C:\Users\admin\trailers>python manage.py migrate Operations to perform: Apply all migrations: auth, movies, sessions, admin, contenttypes Running migrations: Rendering model states... DONE Applying movies.0012_auto_20160915_1904...Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\backends\ utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: foreign key constraint "movies_movie_genre_genre_id_d 9d93fd9_fk_movies_genre_id" cannot be implemented DETAIL: Key columns "genre_id" and "id" are of incompatible types: integer and character varying. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\base.py", line 399, in execute output = self.handle(*args, **options) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem ent\commands\migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\migration s\executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_ini tial) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\migration s\executor.py", line 121, in _migrate_all_forwards state = … -
Model instance not reflecting data passed from pre_save in custom field
I have a custom field for generating slug and I am using it in my model. The strange thing I can't figure out is why is the value I am generating in this custom field's method pre_save not set on the current instance. My question is not about generating slug different way but about this behavior. To simplify this example I defined this classes: Model: class MyModel(models.Model): slug = MyCustomField(blank=True) def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) print 'in save' print self.slug Field: class MyCustomField(models.SlugField): def pre_save(self, model_instance, add): value = super(MyCustomField, self).pre_save(model_instance, add) if not value: value = 'random-generated-slug' return value Post save signal: @receiver(post_save, sender=MyModel) def test(sender, **kwargs): print 'in signal' print kwargs['instance'].slug print 'from database' print MyModel.objects.get(pk=kwargs['instance'].pk).slug Code to run: instance = MyModel() instance.save() >> 'in signal' >> '' >> 'in database' >> 'random-generated-slug' >> 'in save' >> '' instance.slug >> '' Like you can see, the value is set in the database, but it's not on the current instance nor in post_save signal. I have Django version 1.10. Should I set the value in a different way in MyCustomField? What is going on? -
Django rest framework : Do not return array but list of objects with id as key
Django rest framework returns the following output at an API endpoint [ { "id": "QFELD_2.3.2.QF1", "siteuxid": "VBKM02_Abschlusstest", "section": 2, "maxpoints": 4, "intest": true, "uxid": "KA0", "points": 0, "value": 0, "rawinput": "", "state": 3 }, { "id": "QFELD_2.3.2.QF2", "siteuxid": "VBKM02_Abschlusstest", "section": 2, "maxpoints": 4, "intest": true, "uxid": "KA1", "points": 0, "value": 0, "rawinput": "", "state": 3 }, ... Is it possible to return the data in an list object format like: { "QFELD_2.3.2.QF1" : { "siteuxid": "VBKM02", "section": 2, "maxpoints": 4, "intest": true, "uxid": "KA0", "points": 0, "value": 0, "rawinput": "", "state": 3 }, "QFELD_2.3.2.QF2" : { "siteuxid": "VBKM02", "section": 2, "maxpoints": 4, "intest": true, "uxid": "KA1", "points": 0, "value": 0, "rawinput": "", "state": 3 }, ... My Serializer is: class ScoreSerializer(serializers.ModelSerializer): id = serializers.CharField(required=False, allow_blank=True, max_length=100, source='q_id') class Meta: model = Score fields = ('id', 'siteuxid', 'section', 'maxpoints', 'intest', 'uxid', 'points', 'value', 'rawinput', 'state') And View is: class ScoreViewSet(viewsets.ModelViewSet): serializer_class = ScoreSerializer -
AttributeError: 'unicode' object has no attribute '__name__'
I'm trying to dynamically create a form depending on which model is selected (the model is acquired via the URL). When loading up my page, I get the following error. I'm getting the following error: AttributeError: 'unicode' object has no attribute '__name__' And the output of my console: File "/Users/User/platform/ENV/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/User/platform/product/views.py", line 239, in admin_add_object ModelFormSet = modelform_factory(model, fields=("__all__")) File "/Users/User/platform/ENV/lib/python2.7/site-packages/django/forms/models.py", line 527, in modelform_factory class_name = model.__name__ + str('Form') The relevant code inside my views.py def admin_add_object(request, model): ModelFormSet = modelform_factory(model, fields=("__all__")) return render(request, 'product/admin/add.html', {'formset': formset, 'model': model}) -
Django file upload with UpdateView
I tried a minimalistic django implementation of generic views to upload profile pictures. views.py class UpdateProfile(UpdateView): form_class = UpdateUserProfileForm model = UserProfile success_url = reverse_lazy('show_profile') models.py class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True) picture = models.ImageField(upload_to='user/img/%Y-%m-%d/', blank=True) forms.py class UpdateUserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['website','picture'] userprofile_form.html <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans "Save" %}"/> </form> Everything works fine. Now error message. The website field will be updated properly, and a search button allows to choose a file for upload. However the file never appears in the system and the database field remains empty. Unfortunately the django documentation on file upload (https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/) does not include generic views, so I wonder if it is possible at all. -
broadcast not supported by sql broker transport
I am getting this error with my celery configuration.Emails are not working for notifications. when i check status with python manage.py celery -A app status it gives me : broadcast not supported by sql broker transport My celeryconfig.py has following settings: CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' BROKER_URL = 'django://' My set up is Django 1.6 + celery3.1.12 + postgresql + gunicorn Thanks. -
Limit a Django ManyToMany by id
I need to show in admin view a list of cars to add to parking, so far so good with this code class Car(models.Model): name = models.CharField(max_length=200) class Parking(models.Model): name = models.CharField(max_length=200) options = models.ManyToManyField(Car) but in car's list appear all cars from all parkings, I need to show only cars added to a certain parking not all of them. How can achive that ? In pure sql I would make a join with the mapping table and I would filter by parking id -
Django - setting global default from Database on startup
Building an application as Frontend to some LdapDatabases in Django I have several Ldap Parameter sets in the Django Database. # myapp.models LdapParams(models.Model): name = models.CharField() user = models.CharField() pass = models.CharField() The application serves both as webpage as well as an API. I would like to achieve the following: Set global 'ldap_params' for user session. If in any request there is no 'ldap_params', use the global one (I need that for simple api requests) The global 'ldap_params' is defined once by searching the database. users should be able to change the 'ldap_params' My actual approach is using the AppConfig: class MyAppConfig(AppConfig): ... def ready(self): self.ldap_params = self.get_model('LdapParams').objects.get(name="myname") ... The login contains something like: def login(self, request, **kwargs): ... request.session['ldap_params'] = LdapParams.objects.get(name="MyName") ... And in Views I do: class MyView(AppView): ... def get(self, request, **kwargs): try: ldap_params = request.session["ldap_params"] except KeyError: ldap_params = apps.get_app_config("myapp").ldap_params I am not very satisfied with this because there is always that check for ldap_params (the try/except block). What seems better (in performance) would be to override the ldap_params in the AppConfig on login, how would I do it? Defining a setter method on the AppConfig? Or what would be the standard way to handle this … -
Where to keep SASS files in a Django project?
I understand that static files (such as CSS, JS, images) in a Django project are ideally to be kept in a static/ directory, whether inside an app or the project root. A sample folder structure may look like project_root/my_app/static/my_app/css, js or img, or project_root/static/project_name/css, js or img Also, I will run collectstatic command to make them ready to be served. But my question is where should I keep my SASS files? If I create a sass directory inside static/my_app/ along with css, js and img directories, won't they become available to public when I make them ready to be served? What could be the best location/directory to keep my SASS (or SCSS) files in a Django project so that they are not available to public as they will already be processed into CSS which is finally available to public? Also, please let me know if my concepts are not clear about static files. Thank you -
Create a API without third parts, like Django rest framework or similar
I want to create a Rest API with Django and all information that I found is using third parts like Django-Rest-framework or other similar. I create an app to return the data in JSON def get_multiproject_info(project_name): db = MySQLdb.connect(host='...', port=.., user='..', passwd='..', db='..') try: cursor = db.cursor() cursor.execute('SELECT * FROM proj_cpus WHERE project in %s', [project_name]) columns = [column[0] for column in cursor.description] # all_rows = json.dumps(cursor.fetchall(), cls=DateTimeEncoder) all_rows = cursor.fetchall() data = {} data = {'names': []} for item in project_name: data['names'].append(item) data.update({item: {}}) jobs_running = [] jobs_pending = [] for row in all_rows: if (str(item) == row[1]): time_job = int(row[5].strftime("%s")) * 1000 jobs_running.append([ time_job, row[3]]) jobs_pending.append([ time_job, row[4]]) data[item].update({'jobs_running': jobs_running}) data[item].update({'jobs_pending': jobs_pending}) items = json.dumps (data, cls=DateTimeEncoder) finally: db.close() return HttpResponse(items) def find_multiple_project(request): projects = request.GET.getlist('projects[]') projects_info = get_multiproject_info(projects) return HttpResponse(projects_info, content_type='application/json') I call this function from my jquery file using AJAX my URLs file is like this urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^find_project/$', views.findProject, name='findProject'), url(r'^find_multiple_project/$', views.find_multiple_project, name='find_multiple_project'), url(r'^media_data/$', views.media_data, name='media'), ] The URL that I execute is like this and work http://127.0.0.1:8000/connect/find_project/?project%5B%5D=adr The next step was to create an API to put this all logic and could call this URL from other apps. Any idea … -
Django 1.10 Using a dropdown menu to filter queries
I have a database with a bunch of pictures and the countries they were taken in. This is for a photo album on this site I'm making. Currently, I have all the pictures on one page. I like this. I want to now be able to search for all the pictures from a certain country, or city. My design calls for two buttons on top (filter by country, filter by city), and all the pictures from the database displayed below when no filter is used. I want these buttons to be a dropdown list of all the countries and cities respectively. When a user clicks on the countries button a dropdown is called - using bootstrap. They can then click on the country of choice and see all the pictures that are there, ordered by city. If they click on the dropdown for cities, then all the pictures from that city are called. If they select countries, then the cities dropdown only displays the cities in that country. Right now, I have no clue how to do this. I can populate the dropdowns - but I get all the photo's countries - meaning repeats. How can I do this? Here … -
Using Django add-to-model logic outside of the Django admin interface
I've made a custom admin interface (for the client) based on the Django admin interface. I can display all models and their objects, but when I want to add a new object to a given model, I'm at a loss. How would I go by creating a dynamic add page based on what the models fields are? -
How to debug django with VSCode?
Default configuration kind of does not work: { "name": "Django", "type": "python", "request": "launch", "stopOnEntry": false, "pythonPath": "${config.python.pythonPath}", "program": "${workspaceRoot}/manage.py", "console":"externalTerminal", "args": [ "runserver" ], "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "DjangoDebugging" ] }, -
Member of a CBV in Django
I'm, trying to implement a LoginRequiredMixin. For example, if user goes to /post/6 and he isn't logged in, he is redirected to /auth/login/?next=/post/6. I'm trying to make a function that will redirect user either to /post/* (according to next in the url) or to the / if there is no next in the url. I tried to get a url param in GET request, save it to CBV member and then use it in post. But for some reasons it isn't actually saved. Here is a piece of my code: class LoginView(View): redirect_to = '' def post(self, request, *args, **kwargs): user = authenticate(username=request.POST['login'], password=request.POST['password']) print(self.redirect_to) # It's equal to '' here if user is not None: login(request, user) else: print("Account doesn't exists!") return HttpResponseRedirect(reverse('blog:index')) def get(self, request, *args, **kwargs): self.redirect_to = 'edited' form = RegistrationForm() return render(request, 'authorization/login.html', { 'form': form }) Maybe there is any other solutions? Thanks in advance! -
django paginated sitemap url pattern
The short question is: what is the url pattern for the paginated sitemap? So, I have in urls.py: url(r'^sitemap\.xml$', sitemaps_views.index, {'sitemap_url_name': sitemaps}), url(r'^sitemap-(?P<section>.+)\.xml$', sitemaps_views.sitemap, {'sitemaps': sitemaps}), When I go example.com/sitemap-detail.xml, ..it works perfectly fine. I have a limit of 10 (to do the pagination). However, I have forgotten how I move to the next page. I have tried: example.com/sitemap-detail-1.xml, example.com/sitemap-detail/1.xml, and they dont work. Shortly speaking, which url do I need to access to move to the next page of the sitemap? Thanks... -
Accessing values from fetched object?
I have 2 models class Period(CommonInfo): version = IntegerVersionField( ) order_value = models.PositiveSmallIntegerField() start_date = models.DateField() end_date = models.DateField() name = models.CharField(max_length=30) class LeaseDiscount(CommonInfo): version = IntegerVersionField( ) amount = models.DecimalField(max_digits=7, decimal_places=2) amountpayed = models.DecimalField(max_digits=7, decimal_places=2) leaseterm = models.ForeignKey(LeaseTerm) period_date = models.ForeignKey(Period) period = Period.objects.filter(order_value__gte = start, order_value__lte = end).prefetch_related( Prefetch( "leasediscount_set", queryset=LeaseDiscount.objects.filter(is_active=True, leaseterm = activeterm), to_attr="all_discount" ) ) In the view, I want to list all the discounts I have for certain periods of my lease. period = Period.objects.filter(order_value__gte = start, order_value__lte = end).prefetch_related( Prefetch( "leasediscount_set", queryset=LeaseDiscount.objects.filter(is_active=True, leaseterm = activeterm), to_attr="all_discount" ) ) but when I display the list of periods in my template for the all_discount the output is [<LeaseDiscount: LeaseDiscount object>] Why? How I access the values of this object? In general am I doing it the right way? -
Best practice for sequential execution of group of tasks in Celery
I have page that allows user to select tasks which should be executed in selected order, one by one. So, it create group of tasks. User can create several of them. For each group I should make possible to look on tasks progress. I'm looked into several things like chain, chord, group but it seems very tricky for me, and I don't see any possibility to look on each task progress. What's good solution for this kind of problem? -
No module named sqlite
i am a beginner i need to create a python virtual_environment for installing Django. I am using the following steps for installing python and virtualenv cd /usr/src/ wget http://www.python.org/ftp/python/3.5.1./Python-3.5.1.tgz tar zxf Python-3.5.1.tgz cd python-3.5.1 mkdir /usr/local/python-3.5 ./configure --prefix=/usr/local/python'.$python.' --with-threads --enable-shared --with-zlib=/usr/include && make && make altinstall echo "/usr/local/python3.5/lib" > python3.5.conf mv python3.5.conf /etc/ld.so.conf.d/python3.5.conf /sbin/ldconfig ln -sfn /usr/local/python3.5/bin/python3.5 /usr/bin/python3.5 wget https://pypi.python.org/packages/source/s/setuptools/setuptools-11.3.1.tar.gz tar xzf setuptools-11.3.1.tar.gz cd setuptools-11.3.1 /usr/local/python3.5/bin/python3.5 setup.py install /usr/local/python3.5/bin/easy_install-3.5 pip ln -sfn /usr/local/python3.5/bin/pip3.5 /usr/bin/pip3.5 /usr/local/python3.5/bin/pip3.5 install virtualenv then i am created a virtualenv based on this, and enter into python shell and use import sqlite i got following error Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named 'sqlite' And i tried to run a django project installed in the virtalenv i got following errors. raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc) django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named '_sqlite3' I am using CentOS release 6.8 (Final). -
Cant find Gunicorn file in deployment for django app
I am following a guide about deployment of django application using gunicorn mysql and nginx without virtualenv. Now the problem here is when installing the gunicorn using pip install gunicorn i cannot find where its installation directory. Im new on exploring ubuntu os. I have searched and cant find anything where the gunicorn file resides. Here is the guide link but it use virtualenv -
ModelFormset base on Model and Form
I would use modelformset_factory mixed with formset_factory. I will try explain what I need. I have this pice of code: FieldTranslationFormSet = modelformset_factory(ProductTitle, fields=('object', 'language', 'translation'), widgets={'language': forms.RadioSelect()}) And I dont want specific fields and widgets when creating formset, I would use for it my FieldTranslationForm where I define all widgets initial and what I want. In the end i want use it like: FieldTranslationFormSet = modelformset_factory( ProductTitle, FieldTranslationForm ) -
Index DateTimeField in django by year, month, day, hour
I use django 1.10 with PostgresSQL DB. I have a table with millions and in the future billions of records. Each record has a DateTimeField as a timestamp. Obviously, querying this table is very long and therefore needs some indexing, which I have on several fields (not on the timestamp), but when I need to count all the records in a specific timeframe, the indexing is not helpful. I wonder if django has a smart built-in way to index a DateTimeField based on year, month, day, hour resolutions. Or do I have to separate the timestamp field to multiple fields for every resolution, and then to index each of them? Thanks!