Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to invoke a method call within a model on save and update
I have the below Django Model and I would like to create a method (called create) that dynamically populates and change the status field within the TransactionDateTime model class based on the number of False values in the is_taskcomplete within the child TransactionTask class model. I took a stab at creating the create method below, but I'm lost. Any help would be greatly appreciated. Thanks in advance. @python_2_unicode_compatible # only if you need to support Python 2 class TransactionDateTime(models.Model): room = models.ForeignKey(Room, on_delete = models.CASCADE) start_dy = models.DateField() end_dy = models.DateField(blank=True, null=True) def create(self): t1 = TransactionDateTime.objects.get(pk=self.pk) qy = t1.transactiontask_set.all() value = qy.filter(is_taskcomplete = False).count() if value > 0: return "Complete" else: return "Incomplete" status = TransactionDateTime.create(self) def __str__(self): return str(self.start_dt) @python_2_unicode_compatible # only if you need to support Python 2 class TransactionTask(models.Model): transactiondatetime = models.ForeignKey(TransactionDateTime, on_delete = models.CASCADE) is_taskcomplete = models.BooleanField(default = False) def __str__(self): return str(self.transtaskname) -
Recursive delete foreign keys for Django object
Suppose I have an object called Person that has a foreign key that links to CLothes which links to class Person(models.Model): clothes = models.ForeignKey('Clothes', on_delete=models.PROTECT) jokes = models.ManyToManyField(to='Jokes') class Clothes(models.Model): fabric = models.ForeignKey('Material', on_delete=models.PROTECT) class Material(models.Model): plant = models.ForeignKey('Plant', on_delete=models.PROTECT) And if I wanted to delete person, I would have to delete Clothes, Jokes, Materials attached to it. Is there a way to recursively detect all the foreign keys so that I can delete them? -
Custom validation Django admin unknown field
I am trying to make a custom validation for the imageField in the admin panel, but I get the following error. There is nog field with the namen banner_image in the Event model class, but when I change field = ('banner_image',) to something else I get instead of "specified for Event" specified for EventBanner. most solutions I find for making a custom validation are for older versions of Django. django.core.exceptions.FieldError: Unknown field(s) (banner_image) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin. app admin.py: class BannerImageForm(forms.ModelForm): class Meta: model = EventBanner fields = ['banner_image',] def clean_banner_image(self): banner_image = self.cleaned_data['banner_image'] if not banner_image: raise forms.ValidationError("No image!") else: w, h = get_image_dimensions(banner_image) if w != 1200: raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 1200px" % w) if h != 200: raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h) return banner_image class EventAdmin(admin.ModelAdmin): form = BannerImageForm list_display = ('event_name', 'event_start_date') formfield_overrides={ models.TextField:{'widget':Textarea(attrs={'rows':15, 'cols':80})} } admin.site.register(Event, EventAdmin) app models.py: class EventBanner(models.Model): event = models.OneToOneField(Event, unique=True) banner_image = models.ImageField(upload_to=get_image_path, blank=True, null=True) def clean(self): validate_only_one_instance(self) TraceBack: Environment: Request Method: GET Request URL: http://localhost:8000/admin/events/event/1/change/ Django Version: 1.10.4 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Django REST API doint filter and on the same field
I'm all new to django REST API and trying to understand something. when using a URI like this: http://example.com/api/products?category=clothing&category=shoes I would have wanted to recieve back all the category that are clothing and shoes but at the ened the only thing that I get is all the shoes what is the correct way to make it act as needed by me? Thank you in advance!!! -
Django Rest Framework. Check difference between fields value for two POSTs
Dont know how to do this: I have program, that create data with POST and have some fields, like: create_data: id: value: Need check field "value" between current and previous POST, and if previous "value" more then current "value" - prevent create current POST with error. -
How to override queryset count() method in Django's admin list
In order to avoid time consuming and costly exact database count queries, I'd like to override the count() method inside a Django admin class like so: from django.contrib import admin from django.db import connection class CountProxy: def __call__(self): # how to access the queryset `query` here? query = ... try: if not query.where: cursor = connection.cursor() cursor.execute("SELECT reltuples FROM pg_class WHERE relname = %s", [query.model._meta.db_table]) n = int(cursor.fetchone()[0]) if n >= 1000: return n # exact count for small tables return object_list.count() except: # exception for lists return len(object_list) return estimated_count class MyAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(MyAdmin, self).get_queryset(request) qs.count = CountProxy() return qs But I don#t know how to access the original queryset within my CountProxy class. Any idea? I know I can overwrite the whole changelist view through get_changelist. But that involves a lot of duplicating code from Django's repo. -
Precompile jsx for React in django-compressor
Using Cygwin on Windows 10 (64 bits) Installed babel-cli, react and babel-preset-react on top of Node.js, which was installed via Windows Installer (since there is no support for Cygwin.) I installed those Node packages using yarn, in the global modules folder. In the django-compressor documentation (https://django-compressor.readthedocs.io/en/latest/reactjs/) they say that a precompiler setting does the trick: COMPRESS_PRECOMPILERS = ( ('text/jsx', 'cat {infile} | babel > {outfile}'), ) However, babel is not recognizing jsx (throwing errors when encountering virtual dom elements.) It's obvious because I am not passing the react preset to the command. But there is no way I can use that preset because I installed in the global module folder and now I am unable to make babel find and use it. I need one of these possible solutions: How can I make babel use a preset globally installed (how should I use babel --presets react in a way that works)? How do I use a .babelrc file in a Django project? If I were to install the preset locally (which I seem to dislike a lot) how do I make it live with my Django project without making mess out of my project directory structure? -
Run Djnago with python as daemon
We have web application which is running with django ,python and PostgreSQL. we are also using virtualenv. To start the web service, we first activate the vitrualenv and then start python as service on 8080 with nohup. But after sometime nohup process dies. is there any way to launch service as demon like apache, or use some thing like monit. I am new to this, pl excuse my mistakes -
How to make a port live in windows using command line?
I am running my django-python server on localhost and it gives following status while running: System check identified 1 issue (0 silenced). January 04, 2017 - 19:58:23 Django version 1.9, using settings 'goldbrex.settings' Starting development server at http://127.0.0.1:9000/ Quit the server with CTRL-BREAK. I want my fellow(windows user to hit an API running on localhost at my PC, How to make it possible using command line? -
How to make an inner join with geodjango on st_covers
I'm trying to create a queryset to match this query: select * from users u inner join area z on ST_Covers(z.multi_poly, ST_SetSRID(ST_Point(u.lng, u.lat), 4326)) Is it possible with geodjango? -
Why do i get undefined value in the following jquery code?
I am trying to query the database about username and email, trying to find if it already exists and storing the returned boolean values in 'usernameAlreadyTaken' and 'emailidAlreadyTaken' and i am also disabling the submit button if username and email already exist in database.Its working as it should be and when i type the username that is already stored in database it displays message and sets the value of usernameAlreadyTaken to true but the movement i hit 'Tab' or click on the next inputbox the value of usernameAlreadyTaken automatically turns to false and it also displays 'undefined' instead of displaying the id of the input box. please help :'( here is the snapshot: undefined error jquery code: function validateForm() { var password = $('#password').val() ; var username = $('#username').val() ; var emailid = $('#emailid').val() ; var retrypassword = $('#retrypassword').val() ; var index = $('#' + this.id).index() ; function allGood(that, usernameAlreadyTaken, emailidAlreadyTaken){ console.log(that.id,usernameAlreadyTaken) ; if ( username == '' || emailid == '' || password == '' || retrypassword == '' || password != retrypassword ) return false ; else if (usernameAlreadyTaken == true || emailidAlreadyTaken == true) return false ; return true ; } if ( allGood(this, usernameAlreadyTaken, emailidAlreadyTaken ) … -
Django Limiting Choices in a form after a selection
I want to limit the choices given in a form after a selection of a previous field. This is my models.py file: class Course(models.Model): name = models.CharField(max_length=70) course_id = models.CharField(max_length=10, default="") major = models.CharField( max_length=45, choices= ( ('bachelorcollege', 'Bachelor College'), ('appliedmathematics', 'Applied Mathematics'), ('appliedphysics', 'Applied Physics'), ('architecture', 'Architecture, Urbanism and Building Sciences'), ('automotive', 'Automotive'), ('biomedicalengineering', 'Biomedical Engineering'), ('chemicalengineering', 'Chemical Engineering'), ('computerscience', 'Computer Science'), ('electricalengineering', 'Electrical Engineering'), ('industrialdesign', 'Industrial Design'), ('industrialengineering', 'Industrial Engineering'), ('mechanicalengineering', 'Mechanical Engineering'), ('psychologyandtechnology', 'Psychology and Technology'), ('sustainableinnovation', 'Sustainable Innovation'), ), default='computerscience', ) def __str__(self): return self.name def __major__(self): return self.major class Resource(models.Model): uploadedBy = models.ForeignKey('auth.User') title = models.CharField(max_length=200) resourcefile = models.FileField(blank=False, default="") major = models.CharField( max_length=45, choices= ( ('bachelorcollege', 'Bachelor College'), ('appliedmathematics', 'Applied Mathematics'), ('appliedphysics', 'Applied Physics'), ('architecture', 'Architecture, Urbanism and Building Sciences'), ('automotive', 'Automotive'), ('biomedicalengineering', 'Biomedical Engineering'), ('chemicalengineering', 'Chemical Engineering'), ('computerscience', 'Computer Science'), ('electricalengineering', 'Electrical Engineering'), ('industrialdesign', 'Industrial Design'), ('industrialengineering', 'Industrial Engineering'), ('mechanicalengineering', 'Mechanical Engineering'), ('psychologyandtechnology', 'Psychology and Technology'), ('sustainableinnovation', 'Sustainable Innovation'), ), #default='computerscience', ) course = models.ForeignKey(Course) resourcetype = models.CharField( max_length=45, choices= ( ('Summary', 'Summary'), ('Exam', 'Exam'), ), default='Summary', ) upload_date = models.DateTimeField( blank=True, null=True) def __str__(self): return self.title And this is my forms.py file: class UploadForm(forms.ModelForm): class Meta: model = Resource fields = ('title', … -
How to filter queryset by ForeignKey and ManyToMany using Q properly?
I got an error message that says: 'User' object does not support indexing I try to filter queryset using Q to get a query that contains objects where self.request.user (which is an User model object) is an owner (ForeignKey) or one of the participants (ManyToMany). Here is my code: if self.request.user.has_perm('permissions'): queryset = self.model.objects.filter(parent=None) else: queryset = self.model.objects.filter( Q(parent=None), Q(owner=self.request.user) | Q(participants__in=self.request.user)) I think the problem is Q(participants__in=self.request.user) but I have no idea how to fix it. -
Running Nodejs' Lessc from Cygwin throws error with absolute path
I have Windows 10 (64 bits), Cygwin, Nodejs installed via Windows Installer and lessc installed on top of Nodejs. I am trying to make django-compressor work with precompilers as suggested in documentation: COMPRESS_PRECOMPILERS = ( #... ('text/less', 'lessc {infile} {outfile}'), #... ) It throws lessc: ENOENT: no such file or directory, open 'C:\awkwardly\converted\cygwin\path\to\my\file.less' (Notice the drive letter added) I tested the command lessc from the Cygwin console. It works fine as long as I use relative paths, but when I use an absolute path it converts it to Windows path, even prepending a drive letter, something like C:\cygdrive\d\projects\my\path\to\file.less How can I fix/workaround this? -
How can I refresh the token with social-auth-app-django?
I use Python Social Auth - Django to log in my users. My backend is Microsoft, so I can use Microsoft Graph but I don't think that it is relevant. Python Social Auth deals with authentication but now I want to call the API and for that, I need a valid access token. Following the use cases I can get to this: social = request.user.social_auth.get(provider='azuread-oauth2') response = self.get_json('https://graph.microsoft.com/v1.0/me', headers={'Authorization': social.extra_data['token_type'] + ' ' + social.extra_data['access_token']}) But the access token is only valid for 3600 seconds and so I need to refresh, I guess I can do it manually but there must be a better solution. How can I get an access_token refreshed? -
Application on Production server gives ImportError at / No module named forms
I am getting an error on production server: ImportError at / No module named forms on this line: from app.forms import BootstrapAuthenticationForm -
Application on production server giving a model error
RuntimeError at / Model class models.Category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Why am I getting this error and what needs to be done to solve this error -
Django images not loading even after using --insecure
I tried to make custom 404 error page. I changed debug=True to debug=False and run local django server as >python manage.py runserver --insecure. Doing so website is loading css but didn't load images. All the images didn't load even after using --insecure. With debug=True all of css and images were loading. I have removed some extra portion of settings.py hope below covers important ones. settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', 'upload', 'ckeditor', 'ckeditor_uploader', 'django_bootstrap_carousel' ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'MySite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'TorrentSite.wsgi.application' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '-' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False EMAIL_PORT = 1025 MEDIA_ROOT = 'D:/projects/PyCharm projects/TorrentSite/media/' MEDIA_URL = '/media/' STATIC_ROOT = 'D:/projects/PyCharm projects/TorrentSite/upload/static/' STATIC_URL = '/static/' -
How to access template block from plugin within Django CMS Placeholder
I have the following code: base.html <html> ... {% block test_block %} {# Some stuff to render #} {% endblock %} ... </html> main_template.html {% extends "base.html" %} ... {% block content %} {% placeholder "content" %} {% endblock %} ... plugin.html ... If I add my plugin to the page it renders in the placeholder block, as expected. If I amend plugin.html to add the following: plugin.html ... {% block test_block %} {{ block.super }} {# Some more stuff to render #} {% endblock %} ... Then I receive an error: 'BlockNode' object has no attribute 'context'. Did you use {{ block.super }} in a base template? If I try and extend either main_template.html or CMS_TEMPLATE (they seem to be the same?) from within plugins.html I get the following error: maximum recursion depth exceeded while calling a Python object How can I access and append to test_block from within my plugin? -
Get table as two parts in django
I have a question about data filtering. For example we have a model Shop with name, which is FK to to model Names (name, active). What if I need to filter Shop names which are active, and not active in 1 view? Using 2 two queries is an only option? If not, can someone please show effective way to this? Question is, can I get table as two parts, divided by simple condition without running two queries? -
How to properly configure ROOT_URLCONF
I'm going through django tutorial and I have an issue with ROOT_URLCONF line in settings.py. If it's set to 'mysite.urls' index page isn't being found. If I set it to 'polls.urls' it's working but admin page isn't found now. What's the issue? Here's my file hierarchy: -
Django : ValueError: invalid literal for int() with base 10:
I am trying out some stuff in django. Just a simple form which would add every attempt to login in a database. It results in ValueError: invalid literal for int() with base 10: I had checked out a lot of questions but wasn't able to get past this error. I have a view like this. class LoginView(TemplateView): template_name = 'dashboard/login.html' def post(self,request): #firstname,email=request.POST['firstname'],request.POST['email'] #currLogin = LoginForm(firstname,email) currLogin= LoginForm(request.POST) if currLogin.is_valid(): firstname=currLogin.cleaned_data['firstname'] email =currLogin.cleaned_data['email'] print firstname,email users=LoginModel.objects.filter(email=email) if not users: login = LoginModel(firstname,email) login.save() else : return users[0].id return 0 My models.py file contains : class LoginModel(models.Model): firstname = models.CharField(max_length=100) email = models.CharField(max_length=100) My form.py contains this : class LoginForm(forms.Form): firstname=forms.CharField(label="firstname",max_length=100) email = forms.CharField(label="email",max_length=100) class Meta: model = LoginModel Stack Trace : Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/akshay/Downloads/mindwave/dashboard/views.py", line 27, in post login.save() File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, … -
JavaScript function not retaining changed value of HTML form field
I have a form on one of the webpages for my Django project which consists of two text boxes (incVat & excVat) & a 'date' field. The form has the following definition: 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 = mDateField(required=False, label="Date deposit received", projectInstance = None class Meta: model = Deposit fields = ('amount_exc_vat', 'amount_inc_vat', 'date_received')#,'received') def __init__(self, *args, **kwargs): print "__init__ method being called in DepositInfoForm" instance = kwargs.get('instance', {}) project = instance.project try: amount_exc_vat = int(round(instance.amount_exc_vat)) except TypeError: amount_exc_vat = None print "amount_exc_vat has been set: ", amount_exc_vat try: amount_inc_vat = int(round(project.deposit.amount_inc_vat)) except TypeError: amount_inc_vat = None print "amount_inc_vat has been set: ", amount_inc_vat try: date_received = instance.date_received except TypeError: date_received = None print "date_received has been set: ", date_received initial = kwargs.get('initial', {}) initial={ 'received': project.deposit_received, 'amount_exc_vat': amount_exc_vat, 'amount_inc_vat': amount_inc_vat, 'date_received': date_received, } kwargs['initial'] = initial #Set projectInstance to 'project' self.projectInstance = project print "projectInstance has been set to project in __init__" super(DepositInfoForm, self).__init__(*args, **kwargs) self.fields['date_received'].widget.attrs.update({'data-original-value': 'date_received' or ''}) print "date_received field has been updated. New value: ", date_received def save(self, commit=True): print "Save method being called in DepositInfoForm" deposit = self.instance data = self.cleaned_data print … -
Webpack 2 + Vue 2: Invalid token only when building inside vagrant environment
Problem: While moving the dev environment to Vagrant (centos7-x64) I encountered a weird outcome with Webpack. The application runs fine locally (Mac OS), but when building with webpack I get this console error on screen for the same code Uncaught SyntaxError: Invalid or unexpected token I have compared the two compiled .js files and I can't find any clues. The errors occur only sometimes like when I add trivial things code such as console.log Worth mentioning is that environment was served by Express and inside Vagrant its served by Nginx + Gunicorn (Django). Relevant files: Package.json Javascript Any clues? -
How to use decorators to validate request and proceed else throw error
I wanted to know how can I use decorator to validate JSON request in django. Currently I have validations.py file with the function validate which returns True if request is valid else returns False. My current implementation is like: validations.py: def validate(request): flag = True .... # Actual logic for validating request and # sets flag to True/False return flag views.py from validations import validate def authenticate_user(request): if validate(request): ....... # executes further logic based on request # This checks if right access is present in Database # for the user or not. And hence I want to access request variable as it is else: return "Bad Request" I wanted to know how exactly I can use decorator here and do something like this: @validate def authenticate_user(request): ....... # executes further logic based on request # This checks if right access is present in Database # for the user or not. And hence I want to access request variable as it is validate function should directly return "Bad Request" to the client if validations fails for any reason else normal code execution should happen.