Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx to serve Django (uWSGI socket) from specific path with another domain
Currently have uWSGI mediating requests and responses between nginx and Django. There are two sites A and B: A) alpha.com B) www.beta.com Now I want to serve site B from the path alpha.com/awards by pointing nginx to B's uWSGI socket at /home/web/beta/uwsgi/site.sock, such that page P1 can be accessed from both www.beta.com/one and alpha.com/awards/one or P2 can be accessed from both www.beta.com/two and alpha.com/awards/two. The urls are defined in django, not static assets in nginx. How do I do this? The configuration files: # /etc/nginx/sites-available/alpha server { listen 80; listen 443 ssl spdy; server_name www.alpha.com; # Set certificate files. ssl_certificate /etc/nginx/cert/alpha.cert; ssl_certificate_key /etc/nginx/cert/alpha.key; return 301 $scheme://alpha.com$request_uri; } server { listen 443 ssl spdy; server_name alpha.com; # Set certificate files. ssl_certificate /etc/nginx/cert/alpha.cert; ssl_certificate_key /etc/nginx/cert/alpha.key; # Rewrite all news articles to HTTP, because comments don't work in HTTPS. #rewrite "^/(news/\d+/\d+/\d+/.*)$" http://$http_host/$1 redirect; include sites-available/alpha.shared; } # /etc/nginx/sites-available/alpha.shared root /usr/share/nginx/www; index index.html index.htm; # Use the custom error page. error_page 500 /error/500.html; error_page 502 /error/502.html; # Serve custom error pages from the Django templates directory. location ^~ /error/ { internal; alias /home/web/alpha/templates/; } location / { include uwsgi_params; uwsgi_pass unix:/home/web/alpha/uwsgi/site.sock; } # Set up all static files. location /robots.txt { alias /home/web/alpha/static/robots.txt; } … -
Git- local master branch appears to be broken
I am working on a Python/ Django project, using Git to manage my version control. On the live server, the website currently works as expected, however, I have made a couple of changes to the layout/ presentation of one of the views on my local copy. To do this, when my local master branch was up to date with the live version, I created a new branch from master called pipelineProject, and started working on that branch. While making changes on pipelineProject, I 'broke' the website during the course of making changes, and had to revert that branch to the state of master a couple of times. I have now got my pipelineProject branch to a state where the changes I wanted to make work correctly- I have run git add -A and git commit -m 'message' to ensure that my working pipelineProject branch is backed up. However, after backing up pipelineProject, I then checked out master, as I obviously wanted to merge my changes with master, and before merging my changes, I tried loading my website in the browser while on master branch- but for some reason this is now broken... although the website loads, all of the styling … -
post_save signal isn't called
I've already read all related questions. I have two Django projects, and signals work fine in one, but do not work in second one (I've just copy-pasted code and changed names respectively). I have an orders app with Order model. App is included in INSTALLED_APPS setting. I have app config in apps.py: from django.apps import AppConfig class OrdersConfig(AppConfig): name = 'orders' def ready(self): super(OrdersConfig, self).ready() # noinspection PyUnresolvedReferences import signals __init__.py: default_app_config = 'orders.apps.OrdersConfig' And, finally, signals.py: @receiver(post_save, sender=Order) def order_save(sender, instance, created, **kwargs): print 'Post save' if created: print 'Created' send_email_new_order.delay(settings.MODERATOR_EMAIL, instance.pk) And signal does not getting called. Why? Django 1.10.3. -
Django objects filter by parameter name
My method accepts a string parameter which is basically the name of a db column. can I do something like this: original_message = "Let it go" language = "english" ads = Ad.objects.filter(language=original_message) where language is not a name, but a reference to a string? This will save me many if else rows -
AJAX doesn't work with Django by no reason error 500
jQUERY: $.ajax({ url: '/notify/', type:'GET', dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); urls.py: url(r'^notify/$', views.notify,name='notify'), views.py: from django.http import HttpResponse from django.http import Http404 from django.http import JsonResponse def notify(request): data = { 'is_taken': Notification.objects.all() } return JsonResponse(data) On calling ajax in console: Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR) What may be wrong? Everything is correct and present . Django 1.8 , jQuery 3.1.0 -
Why does Django need to serialize validators
When running: python manage.py makemigrations This will sometimes fail because it can't serialize validators, hence the usage of python @deconstructible. Why do the validators have anything to do with the database, and why are they not just ignored? -
Django: Query self referencing objects with no child elements
I have the following django model: class Category(models.Model): name = models.CharField(maxlength=20) parent = models.ForeignKey('self', null=True) Note that the field parent is self referencing i.e. a category can have a parent. How can I find all Category objects that have no child categories? -
Django-import-export change/remove records absent in uploaded file against db
I'm using Django-import-export module in my admin panel. I import .csv file extracted from our ERM system which updates records in Django myapp database. Everything works like a charm, except that when some records are removed from ERM and are not present in .csv datadump, no updates will be done in the Django database since records do not exist. I want to write a clause when importing .csv file, change or delete (preferably change record name to "deleted") all records not present in mentioned .csv file. Records are identified by "number" column which is a primary key in the database. Closest solution I could find was to add "delete" column and set "1" in uploaded file, however that does not help since those records don't exist in the first place. Here's how my admin.py looks like: from django.contrib import admin from .models import Supplier, SiteServices from import_export import resources, widgets, fields from import_export.admin import ImportExportModelAdmin # Register your models here. class SupplierResource(resources.ModelResource): delete = fields.Field(widget=widgets.BooleanWidget()) def for_delete(self, row, instance): return self.fields['delete'].clean(row) class Meta: model = Supplier import_id_fields = ['number'] class SupplierAdmin(ImportExportModelAdmin, admin.ModelAdmin): resource_class = SupplierResource admin.site.register(Supplier, SupplierAdmin) -
Using session to store form input values in order to uso in another view
I am storing some form values, which is a list filter, from a post method in the request.session in order to use it in another view function to render the filtered results. The problem is any user that I log in keep the results stored, if they access the results page directly they will see other users filter results. I use pagination (digg without AJAX), I am using django-el-pagination. the views.py def search(request): if request.method == 'POST': form = ComprarBuscaForm(request.POST) if form.is_valid(): cidade = form.cleaned_data['cidade'] request.session['cidade'] = form.cleaned_data['cidade'] request.session['quartos'] = form.cleaned_data['quartos'] request.session['tipo_imovel'] = form.cleaned_data['tipo_imovel'] request.session['preco_minimo'] = form.cleaned_data['preco_minimo'] request.session['preco_maximo'] = form.cleaned_data['preco_maximo'] request.session['area_minima'] = form.cleaned_data['area_minima'] request.session['area_maxima'] = form.cleaned_data['area_maxima'] return HttpResponseRedirect(reverse('imoveis:resultado_busca')) else: form = ComprarBuscaForm() return render (request, 'imoveis/busca_comprar.html', {'form':form}) def search_result(request): anuncios = Anuncio.objects.filter(quartos=request.session['quartos'], cidade=request.session['cidade'], tipo_imovel=request.session['tipo_imovel'], preco_venda__gte=request.session['preco_minimo'], preco_venda__lte=request.session['preco_maximo'], area_construida__gte=request.session['area_minima'], area_construida__lte=request.session['area_maxima'], tipo_anuncio='Venda') return render(request, 'imoveis/resultado_busca_comprar.html', {'anuncios': anuncios}) Everything is working fine although the fact I mentioned before. I am wondering if what I am doing is the right approach for this kind of situation. -
Django- how to add 'autonumber' column to tables created by view?
I have a Django project, in which one of my views is displaying a number of tables based on information stored in the database. The view is defined as follows: def pipeline(request): ... tables = [] def make_table(detailed_status, projects, status_view=False, first_table=False): ... table_context_map = { Project.ds2: {'fields': [['date added',1], ['site visit date',1], ['initial exc VAT',1]]}, ... # Similar lines to populate the tables with data from the database ... } table_context = table_context_map[detailed_status] ... ... return render(request, 'abc.html', context) What I'd like to do, is at a column to each table created by this view, and insert an 'autonumber' in that column for every row in the table. The tables will be populated dynamically, based on a database query whenever the view is run and the webpage loaded, I just want to number the list of items in each table as it's created. How would I do this? I am knew to Python Django, so any help or guidance would be much appreciated. -
django render and validate formset in class based-view
I have the following class based view that I want to use to render a formset and validate it when it gets submitted through a post method: The formset renders perfectly. When I submit the form I can read the formset and check it for errors. in the post method of this class -> errors = backorder_formset.errors If I find any errors in the formset I would like to rerender the view, but this time with the formset instance, that I read from POST. When I call ctx = self.get_context_data() frowm within the post method of the class the following error gets raised from the call super(MissingProductsListView, self).get_context_data(*args, **kwargs): 'MissingProductsListView' object has no attribute 'object_list' It seems like the superclass of Listview performs this call:queryset = kwargs.pop('object_list', self.object_list) My question is why am I running in this error? and how could I render this formset with its errors messages to display it in the template after it was posted? I am using Django 1.9.9 class MissingProductsListView(generic.ListView): template_name = 'dashboard/purchaseorder/missing_products.html' context_object_name = 'backorders' model = BackOrder def post(self, request, *args, **kwargs): backorder_formset = BackOrderFormset(request.POST) errors = backorder_formset.errors if backorder_formset.is_valid(): # <process form cleaned data> return HttpResponseRedirect('/success/') else: ctx = self.get_context_data() return … -
Django view doesn't render correctly after location.reload()
I have a DetailView where I render details about object of my models.Auction , including expires parameter (using jquery.countdown to countdown time & fire event after finished). Here is the code for the countdown & finish event: <script> $('#clock').countdown('{{ auction.get_time_left }}', function(event) { $(this).html(event.strftime('%D {% trans "day/days" %} %H:%M:%S')); }).on('finish.countdown', function(){ setTimeout(function(){ location.reload()}, 1500); }); </script> On the view i check if: if datetime.now() >= context['auction'].expires:, and I render a different template; But for some reasons when it does the location.reload() it doesn't check that condition(skips it) and renders the same template (with time expired). P.S. I've also tried priniting something in the terminal ( but it skips the printing as well ) -
ImportError: cannot import name UserSerializer while creating a demo rest api
I am trying to build a rest service on django rest frame work as per the this tutorial. I followed all the steps when I am trying to run python manage.py createsuperuser The following is error seen File "/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/tutorial/tutorial/urls.py", line 24, in <module> from tutorial.quickstart import views File "/tutorial/tutorial/quickstart/views.py", line 6, in <module> from tutorial.quickstart.serializers import UserSerializer, GroupSerializer ImportError: cannot import name UserSerializer -
Django: How can I display StreamingHttpResponse output in my own Template html?
I'm running an external python script inside my views.py and I'd like to display it's output in a template html-file, if possible in realtime. views.py: import os, sys import subprocess import traceback from django.http import StreamingHttpResponse def myView(request): if request.method == "POST" and request.POST != {}: return StreamingHttpResponse(callscript()) def callscript(): try: proc = subprocess.Popen( ['python', 'someScript.py'], stdout=subprocess.PIPE, universal_newlines=True ) for line in iter(proc.stdout.readline, b''): yield ">>> " + line.rstrip() except: traceback.print_exc() What I get is the script's output on an empty html page. Now I'd like to hand that script's output over to a template .html file and display it over there. How can this be achieved? I usually passed variables within a context dictionary like this: render(request, 'testsetcreation/testsetView.html', context) But I don't know how this can be done with usage of StreamingHttpResponse. -
Django admin foreign key dropdown with sorting
I have a model in django admin like class NotificationMapping(models.Model): counterId = models.ForeignKey(CounterDetails) groupId = models.ForeignKey(CounterGroup) class Meta: unique_together = ('counterId', 'groupId',) ModelAdmin: class NotificationMappingAdmin(admin.ModelAdmin): list_display = ('get_counterId', 'get_groupId',) actions = None # if display name is available for the counter display it # if not display counterId def get_counterId(self, obj): if obj.counterId.displayName: return obj.counterId.displayName else: return obj.counterId.counterId get_counterId.admin_order_field = 'counterId' # Allows column order sorting get_counterId.short_description = 'counter' # Renames column head # show groupId on admin page for notification mapping def get_groupId(self, obj): return obj.groupId.groupId get_groupId.admin_order_field = 'groupId' # Allows column order sorting get_groupId.short_description = 'groupId' # Renames column head I need to sort the values in the foreign key dropdown from where we add new entry. Counter Id dropdown image -
Django media storage with Amazon 403 errors
Although I have file uploads working fine in development, I can't get them to work in production with AWS S3. I'm currently getting 403 errors: S3ResponseError: 403 Forbidden I can see in my AWS IAM user access key ID that I get a last access recorded when the django app tried to connect. However when I test the credentials with: >>> import boto >>> s3 = boto.connect_s3('access_key', 'secret_key') >>> bucket = s3.get_bucket('mybucket') then I also get a 403 forbidden access error, but for some reason the last access record doesn't appear in the AWS IAM dahboard, which makes me think that test isn't working for some reason? common.py settings: MEDIA_ROOT = str(APPS_DIR('media')) MEDIA_URL = '/media/' production settings: AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_AUTO_CREATE_BUCKET = True from storages.backends.s3boto import S3BotoStorage MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media') DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3BotoStorage' MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME AWS environment vairables are setup in heroku. upload done via: class Bill(models.Model): service = models.ForeignKey(UserService) fuel_type = models.CharField(max_length=1, choices=FUEL_CHOICES, null=True) bill = models.FileField(upload_to='bills', validators=[validate_file_extension]) -
Django 1.8, How to completely reset migrations? An error appears
I have a problem about migrations. I can't resolve it, so I wanna completely reset migrations and databese. However, I don't know how to delete migration files of "auth" app! How shoud I do? I type any command related to "migrate", the following error happens. django.db.migrations.graph.NodeNotFoundError: Migration auth.0007_user_lend_to dependencies reference nonexistent parent node ('account', '0007_deal_is_completed') -
Query on database
In my project, I faces some situations that I need to query on same model several times in the same view. (django model in this case as I am using django and postgresql). The first approach for this may be filtering several times on the same model. The another approach may be that I query on the model and fetched all the data and then saved that into a local variable. Then I can make filter on that variable several times. which approach is most efficient I mean faster and which approach should I go through. -
ImportError: No module named 'cms.models'
I want to use django-shop library, folowing this tutorial I get below error : PS C:\Users\E40-70-i7\Desktop\projects\django-shop-master\example> ./manage.py initialize_shop_demo Traceback (most recent call last): File "C:\Users\E40-70-i7\Desktop\projects\django-shop-master\example\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\management\__init__.py", line 327, in execute django.setup() File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python35-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Program Files (x86)\Python35-32\lib\site-packages\djangocms_text_ckeditor\models.py", line 5, in <module> from cms.models import CMSPlugin ImportError: No module named 'cms.models' opening related code in this path I see below code: from cms.models import CMSPlugin but there is no modual called cms in that directory, by searching I can't find any modual to install or any hint. -
Django- DateInput field not saving value
I have a view that's defined in a particular form class in my forms.py file. class DepositInfoForm(ValidatedForm): amount_exc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency',}),label="Deposit exc VAT") amount_inc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency', 'readonly':'readonly',}),label="Inc VAT") date_received = MoonDateField(required=False, label="Date deposit received", widget=forms.DateInput(format='%d/%m/%Y', attrs=({'class':'datepicker'}))) class Meta: model = Deposit fields = ('amount_exc_vat', 'amount_inc_vat', 'date_received')#,'received') def __init__(self, *args, **kwargs): instance = kwargs.get('instance', {}) project = instance.project try: amount_exc_vat = int(round(instance.amount_exc_vat)) except TypeError: amount_exc_vat = None try: amount_inc_vat = int(round(project.deposit.amount_inc_vat)) except TypeError: amount_inc_vat = None try: date_received = instance.date_received except TypeError: date_received = None initial = kwargs.get('initial', {}) initial={ 'received': project.deposit_received, 'amount_exc_vat': amount_exc_vat, 'amount_inc_vat': amount_inc_vat, #ERF(21/11/2016 @ 1130) Add 'date received' to the 'initial' values... 'date_received': date_received, #'date_received': date_received #date_received, } kwargs['initial'] = initial super(DepositInfoForm, self).__init__(*args, **kwargs) self.fields['date_received'].widget.attrs.update({'data-original-value': self.initial['date_received'] or ''}) def save(self, commit=True): deposit = self.instance data = self.cleaned_data print "save method being called in DepositInfoForm (projects/forms.py line 1142)" if 'date_received' in self.changed_data: if not data['date_received'] == '': deposit.project.deposit_received = True; self.deposit_r = True deposit.project.upgrade_detailed_status(Project.ds75) else: deposit.project.deposit_received = False; deposit.project.save() if ('amount_exc_vat' in self.changed_data or 'date_received' in self.changed_data or 'received' in self.changed_data) and data['amount_exc_vat'] and data['date_received'] and data['received']: send_message(message_template=2, project=self.instance.project) self.deposit_r = True if hasattr(self, 'deposit_r'): # Make the payment deposit_payment = Payment(project=deposit.project, is_booking_deposit=True, amount_exc_vat=data['amount_exc_vat'], date_paid=data['date_received']) … -
Django-CMS static placeholder not working in site with translations
I have a site with Django/Django-CMS that has 3 languages and I've got a static placeholder for the newsletter form. The problem is that I add the plugin to this placeholder in my pt page and then edit the content in the other pages (en and es) so the text is translated and publish my changes. The problem is that in edit mode the changes appear but in publish mode it always assumes the pt translation. In the other placeholders (not static) this doesn't happen. I can't have static placeholders with translations? -
Django Models comparison
I'm beginning with Django and I have a Civil Status project. I created my first models.py in order to get a Form, but I had some advices in order to normalize my database. I made this process and I would like to know what do you think about this new restructuration. My old models.py : from django.db import models from django.forms import ModelForm from .countries import CHOIX_PAYS # Importation de la liste des pays from .sexe import CHOIX_SEXE # Importation de la liste des sexes # Create my Form model BirthCertificate class BirthCertificate(models.Model) : nom = models.CharField('Nom', max_length=30, null=False) # Lastname prenom = models.CharField('Prénom', max_length=30, null = False) # Firstname sexe = models.CharField('Sexe', max_length=1, choices = CHOIX_SEXE) # Choice between 'M' or 'F' birthday = models.DateField('Date de naissance', null=False) birthhour = models.TimeField('heure de naissance', null=False) birthcity = models.CharField('Ville de naissance', max_length = 30, null=False) birthcountry = models.ForeignKey(Country) nom_pere = models.CharField('Nom père', max_length=30, null=False) prenom_pere = models.CharField('Prénom père', max_length=30, null=False) birthday_pere = models.DateField('Date de naissance du père', null=False) birthcity_pere = models.CharField('Ville de naissance du père', max_length=30, null=False) birthcountry_pere = models.CharField('Pays de naissance du père', max_length=2, choices= CHOIX_PAYS) job_pere = models.CharField('Profession du père', max_length=30, null=False) adress_pere = models.CharField('Adresse du père', max_length=40, null=False) … -
auditlog with Django and DRF
I need to implement auditlog feature in one of my project which is using Django 1.8 and Django-Rest-Framework 3.2.2. I have extended BaseUserManager class to create user model since I had to use email as a username in my application ( if this information matters ). Below is my db design which will hold logs - **fields type desc** id pk ( auto_increment) cust_id FK customer customer_name FK customer user_id FK user user_name FK user module Varchar(100) sales,order,billing,etc action Varchar(10) Create/Update/Delete previous_value varchar(500) current_value varchar(500) Datetime Datetime timestamp of change I have tried https://pypi.python.org/pypi/django-audit-log but it has 2 issues as per my requirement- It does not capture data as per my requirement which I understand is my issue and so I modified it's code and added my fields into it's model. It is not capturing module information. Behaviour is random. I am seeking advice to proceed with this feature. Which package would be best suitable for my task. P.S I have also tried Django-reversion and I have no requirement of data versioning. Thanks -
Django pipeliner: /usr/bin/env: yuicompressor: No such file or directory
I have the following versions of django and django-pipeline: Django==1.10.3 django-pipeline==1.6.9 In /usr/bin/ I see "yui-compresssor" listed. Running collectstatic gives the following error. pipeline.exceptions.CompressorError: /usr/bin/env: yuicompressor: No such file or directory When I run my site with debug set to false it loads OK, but when debug is false I just get a 500 error page so the problem is when it is trying to compress the assets. On my production settings file I have... PIPELINE['CSS_COMPRESSOR'] = 'pipeline.compressors.yui.YUICompressor' PIPELINE['JS_COMPRESSOR'] = 'pipeline.compressors.yui.YUICompressor' Am I missing anything? -
Django 1.10 - how to change front end user authentication from username to email?
In Django default user authentication is integrated through Username and Password. In my project profile page, I have an option to change Username. So, it is necessary to change my authentication system in back end and front end with email and password. Using authentication backend i can change default authentication system through email and password in admin. Here is the code - class EmailBackend(object): def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if getattr(user, 'is_active', False) and user.check_password(password): return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None In settings.py - AUTHENTICATION_BACKENDS = ( 'apps.account.email-auth.EmailBackend', ) I was wondering how could i do the authentication through in front end. Already, I prepared front login page through email and password. But see form.errors and predict must be missing any front authentication like AUTHENTICATION_BACKENDS Thank you very much for your help!