Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i encryption database username and password which in the django settings file?
Database setting like this, any encryption methods: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*&^%$#', 'USER': '*&^%$#@', 'PASSWORD': '*&^%$#', 'HOST': '*&^%$#', 'PORT': '3306', # 'OPTIONS': {'threaded': True} this is used in production env and suit for oracle db } } -
Django - Do different queries depending on value of field
I'm stuck on a seemingly simple issue. I want to do a different queryset if sold_data is empty. Is there an effective way to do this? Or do I need to use a for loop and loop over all the listing objects and check each one? class Listing(models.Model): list_price = models.IntegerField() sold_price = models.IntegerField(null=True, blank=True) ... other fields data = Listing.objects.filter(...) # Note: I had already made other queries if sold_price == None: data = data.filter(list_price__gte=1) else: data = data.filter(sold_price__gte=1) -
Annotate QuerySet with first value of ordered related model
I have a QuerySet of some objects. For each one, I wish to annotate with the minimum value of a related model (joined on a few conditions, ordered by date). I can express my desired results neatly in SQL, but am curious how to translate to Django's ORM. Background Let's say that I have two related models: Book, and BlogPost, each with a foreign key to an Author: class Book(models.Model): title = models.CharField(max_length=255) genre = models.CharField(max_length=63) author = models.ForeignKey(Author) date_published = models.DateField() class BlogPost(models.Model): author = models.ForeignKey(Author) date_published = models.DateField() I'm trying to find the first mystery book that a given author published after each blog post that they write. In SQL, this can be achieved nicely with windowing. Working solution in PostgreSQL WITH ordered AS ( SELECT blog_post.id, book.title, ROW_NUMBER() OVER ( PARTITION BY blog_post.id ORDER BY book.date_published ) AS rn FROM blog_post LEFT JOIN book ON book.author_id = blog_post.author_id AND book.genre = 'mystery' AND book.date_published >= blog_post.date_published ) SELECT id, title FROM ordered WHERE rn = 1; Translating to Django's ORM While the above SQL suits my needs well (and I could use raw SQL if needed), I'm curious as to how one would do this in QuerySet. … -
how to add the annotate query in fetching the data in django
the problem is that i want to count total number of address in same area on my searching views.py if query: family = family.filter( Q(head__name__icontains=query) | Q(address__icontains=query) | Q(head__birth_date__icontains=query) | Q(head__gender__icontains=query) | Q(spouse__name__icontains=query) | Q(tribe_type__icontains=query) | Q(head__religion__icontains=query) | Q(head__highest_educational_attainment__icontains=query) ).annotate( total_address=Sum( Case( When(address__icontains=query, then=Value(1)), default=Value(0) ) ) ) # distinct() page = self.paginate_queryset(family) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(family, many=True) return Response(serializer.data) and i want to return as well the total_address in my return page i am using restful api to fetch the data`s any help is highly appreciated -
Unable to login to the admin panel in Django
The site is working fine but when I switch to http://127.0.0.1:8000/admin/ it shows AttributeError at /admin/ .I tried to include MIDDLEWARE_CLASSES in the mysite/settings.py but to no avail . Here are some details : Django mysite.settings INSTALLED_APPS = [ 'personal', 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] http://127.0.0.1:8000/admin/ page :: Django mysite.urls :: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), ] Am I missing something? Ask for more info if required . Thanks! -
django utf-8 metatag not extending to inheriting templates
I have template inheritance set up with utf-8 metatag: layout.html would work fine with ä in it. <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>{{ title }}</title> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'app/css/theme-default.css' %}" /> </head> <body> ääää {% block content %}{% endblock %} </body> I can use unicode charset in the layout.html with no problems. ä ü õ etc. But not in the inheriting templates. events.html like this would give a error: {% extends "app/layout.html" %} {% block content %} ä {% endblock %} UnicodeDecodeError at /events.html 'utf-8' codec can't decode byte 0xe4 in position 54: invalid continuation byte -
django removes image on update save
I have the following clean method by which I reduce an image if it is too large: class CompanyForm(forms.ModelForm): class Meta: model = Company exclude = ('limited') def clean_image(self): image_field = self.cleaned_data.get('image') if image_field: reduced_image = reduce_image(image_field, 550) return reduced_image else: raise forms.ValidationError('You must upload a square logo image') return image_field My reduce image looks like the following: def reduce_image(image_field, height_max): if image_field: try: image_file2 = BytesIO(image_field.read()) image = Image.open(image_file2).convert('RGB') print(image) except: #raise ValidationError('There was a problem with the image, please try another.') print('returning from image errror') return image_field w, h = image.size print('image width:'+str(w)) print('image height:'+str(h)) if h > height_max: print('height toolarge') ratio = h/float(w) new_height = ratio * height_max image = image.resize((int(height_max), int(new_height)), Image.ANTIALIAS) image_file = BytesIO() image.save(image_file, 'JPEG', quality=90) image_field.file = image_file print(image_file) return image_field The first time I save, it saves no problem. When I save a second time to update the model, it removes the image. Why might this be happening? -
Django aggregate avg price by product category
I have this view: def MainStatsView(request): leads = Leads.objects.all() university = University.objects.all() price = Leads.objects.aggregate(Avg('price')) context = { 'leads':leads, 'university':university, 'price':price, } return render(request,'stats/stats_main.html',context) I am trying to get the average price of properties (the product) that generated leads at each university (the category). I am having trouble finding the avg price based on university. I tried using a for loop but that doesn't seem to do the trick. Also here is my loop: {% for uni in university %} <tr> <td>{{ uni.u_name }}</td> <td>{{ price }}</td> <td>{{ lead.school }}</td> <td>{{ lead.featured }}</td> <td>{{ lead.price }}</td> </tr> {% endfor %} I'm a little all over the place here so that is why it looks overly messy. Here is an image of the result. It's giving me the avg on the price of all properties that have generated leads rather than for one school specifically (which is what I want). -
Static folder is not working on Django
I'm beginning at Django and I don't know why but it seems like Django can't find my static folder. Here's how I did it : # IN MY SETTINGS FILE STATIC_URL = '/static/' # IN MY APP "accounts", IN base.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'accounts/basic.css' %}"> # (MAIN FOLDER) -> (accounts (APP)) -> (static) -> (accounts) -> basic.css I tried to put some red color on my h2 but it's not working, and I see no mistakes. Sorry if this is a dupe but it seems like it has no mistakes for me and I'm lost.. Thanks ! -
python, django code doesn't work in html
This is my html file code part product.html <aside> <div id="news"> <h2 class="heading">News</h2> <div style="clear: both"><br></div> {% for articles in news_articles %} <div id="articles"> <div class="article"> <a href="{{ articles.article.get_absolute_url }}"> <img src="{{ articles.image }}"> <div style="clear: both"></div> <span></span><div style="clear: both"></div> </a> <em>{{ articles.article.created }}</em> <div style="clear: both"><br></div> </div> {% endfor %} </div> <a href="" title="View More Articles"> <div id="btn"> <span>View More</span> </div> </a> </div> </aside> This is my views.py file code part views.py def product(request, product_id): product_images = ProductImage.objects.filter(is_active=True, is_main=False, product=product_id) product = Product.objects.get(id=product_id) links = ProductDownload.objects.filter(is_active=True, product=product_id) return render(request, 'products/product.html', locals()) def new(request, product_id): news_articles = NewsImage.objects.filter(is_active=True, is_main=True) article = Article.objects.get(id=product_id) return render(request, 'news/article.html', locals()) This is my models.py file code part models.py class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) description = models.TextField(default=None) processor = models.CharField(max_length=300, blank=True, null=True, default=None) video = models.CharField(max_length=300, blank=True, null=True, default=None) ram = models.CharField(max_length=300, blank=True, null=True, default=None) disk_space = models.CharField(max_length=300, blank=True, null=True, default=None) oS = models.CharField(max_length=300, blank=True, null=True, default=None) video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None) img = models.CharField(max_length=10000, blank=True, null=True, default=None) category = models.ManyToManyField(ProductCategory, blank=True, default=None) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('product', args=[str(self.slug)]) class ProductImage(models.Model): product = models.ForeignKey(Product, … -
Getting a url to read the HTML output from a .fcgi file and not the contents of the .fcgi file (shared server using fastcgi)
My question is how do I get a browser to read the HTML output from a .fcgi file and not the contents of the .fcgi file. I am using a shared server, linux, Django 2.0, Python 3.6.4, flup6. Because fastcgi is deprecated post Django 1.8 and Bluehost doesn't use WSGI and only FastCGI (mod_fastcgi) I am using what NetAngels made available: https://github.com/NetAngels/django-fastcgi My .htaccess file is the project folder with my .fcgi file as is commonly recommended. My .htaccess reads: AddHandler fastcgi-script.fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)% app.fcgi/$1 [QSA, L] My .fcgi file reads: #!/homeX/user/python3.6/bin/python36 import sys, os project_name = "app" sys.path.insert(0, "homeX/user/python3.6/bin/python36") sys.path.append("directory/of/my/project/app") sys.path.append("directory/of/my/project/app/app") sys.path.append("directory/of/my/project/app/app/app") sys.path.append("directory/of/site-packages") sys.path.append("directory/of/site-packages/flup") sys.path.append("directory/of/site-packages/django") os.chdir("directory/of/my/project/app/app/app") os.environ['DJANGO_SETTINGS_MODULE'] = "settings" from django_fastcgi.servers.fastcgi import runfastcgi from django.core.servers.basehttp import get_internal_wsgi_application wsgi_application = get_internal_wsgi_application() runfastcgi(wsgi_application, method="prefork", daemonize="false", minspare=1, maxspare=1), maxchildren=1) I have made sure to: chmod 0755 app.fcgi I am able to type into the linux SSH: app.fcgi This is what comes up in the SSH terminal: WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Not Found: / Status: 404 Not Found Content-Type: text/html … -
django-taggit - display existing tags on the django-admin add record page
I have created a test vlog application using django/python and django-taggit. The vlog and tags are working as they should. However, I want to list all the existing tags in the django-admin interface for new and updated vlog entries - similar to displaying the tags as a filter on the django-admin list page. This will make the selection of new or existing tags for each new or updating vlog entry that much easier. Here is what I mean by adding the tags as help-text on the tags input field: My models.py code: class VlogDetails(models.Model): .... vlog_video_image_url = models.URLField(null=False, blank=False, max_length=250, unique=True, help_text='http://img.youtube.com/vi/You_Tube_URL/0.jpg') .... tags = TaggableManager(help_text='List all the available tags here.') Here is the django-admin input form interface: Is it possible to display the existing tags in another manner on the new / edit django-admin page? I have already listed the existing / existing tags on the django-admin list page as a filter as shown below. This filter display does not display on the new / update input forms. django-admin filter code: class VlogDetailsAdmin(BaseDetailsAdmin): .... list_filter = [ 'vlog_date_published', 'tags', 'vlog_timestamp_added', 'vlog_timestamp_updated' ] I have tried several things but none work and I cannot find any related ideas in the … -
Detecting if my page is being loaded in an iFrame in a Django view
How can I detect in a view function that the page is being loaded in an iFrame? I want to change the page slightly if that is the case. Is there any way to do this? Note, Im not looking for click jacking protection. I want to make changes to my view if the page is being loaded in an iframe. -
Django ORM - How to perform complex GROUP BY with values().annotate().values()
I'm trying to convert as much raw SQL to use the Django ORM as I can, and I've run into a snag. I'm trying to perform a query similar to this one: SELECT table.x, MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY table.group_category, table.group_number So far, what I've been trying has been some permutation of this: q = MyModel.objects\ .filter(**filter_kwargs)\ .values('group_category', 'group_number')\ .annotate(y=Max('y'))\ .values('x','y','group_category','group_number') However, this doesn't seem to work. If I exclude the last values(), it produces the following (roughly): SELECT MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY table.group_category, table.group_number It doesn't select table.x. But if I include the last values()... SELECT table.x, MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY x, y, table.group_category, table.group_number It groups by x, y. So what clearly seems to be happening is that the all of the values are replaced and annotate uses whatever values the QuerySet is given (because it's evaluated lazily?). The docs on aggregation and values seem to suggest that doing the two values functions in this order would have the desired effect, and I found a writeup (from 2013) that also suggests this. Am I doing something wrong? Is this still possible in the Django … -
Django conn= connet(dsn, connetion_factory, async=async) django.db.utils.OperationalError psycopg2
I am working on the connection of postgresql 9.5 and Django 1.11 in wimdows 7, but it throws me an error install python 3.4.2, add path install postgresql 9.5.10, add path install virtualenv version 15.1.0 create virtualenv myenv run Scripts\myenv\activate install psycopg2-2.6.2.win32-py3.4-pg9.5.3-release.exe, add folder psycopg2 in C:\proyectos\myenv\Lib\site-packages install Django 1.11 create project Django => django-admin.py startproject redsocial in the folder redsocial => django-admin.py startapp goodpeople in Sublime text3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'goodpeople', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'goodpeople', 'USER': 'postgresql', 'PASSWORD': 'postgresl', 'HOST': 'localhost', 'PORT': '5432', } } #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "redsocial.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) python manage.py migrate, python manage.py test, python manage.py runserver enter image description here enter image description here enter … -
What is the correct way to catch model object deleted time in django?
signal CODE : @receiver(post_save, sender=TestModel) def update_log(sender, instance, **kwargs): TestModelLog.objects.create(description=instance.description, datetime=instance.updated) @receiver(post_delete, sender=TestModel) def delete_log(sender, instance, **kwargs): TestModelLog.objects.create(description=instance.description, datetime=now()) model CODE: class TestModel(models.Model): description = models.CharField(max_length=34) updated = models.DateTimeField(auto_now=True) I made signal code like above one and which is to catch log of TestModel. As you can see, I can get update time using instance as datetime=instance.updated. And it is correctly the same as TestModel's updated time. When I want to get deleted time, datetime=instance.updated is not working. So I tried to catch deleted time using datetime=now(). But I'm curious about that there is other good way except datetime=now(). Would you let me know other good way of catching object's deleted time? -
Persisted data with Django and Algolia search model indexing
This is a curious one for Django+Algolia. I'm using the Algolia specific Django package: $ pip install algoliasearch-django I have the following model schema: import os import datetime from channels import Group from django.db import models from django.conf import settings from django.utils.six import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.core.files.storage import FileSystemStorage from django.contrib.humanize.templatetags.humanize import naturaltime BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SITE_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/site')) USER_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/user')) @python_2_unicode_compatible class Room(models.Model): """ This model class sets up the room that people can chat within - much like a forum topic. """ title = models.CharField(max_length=255) staff = models.BooleanField(default=False) slug = models.SlugField(max_length=250, default='') banner = models.ImageField(storage=USER_UPLOAD_LOC, null=True, blank=True) def last_activity(self): """ For date and time values show how many seconds, minutes, or hours ago a message was sent (i.e., persised to the database) compared to current timestamp return representing string. """ last_persisted_message = Messages.objects.filter(where=self.slug).order_by('-sent_at').first() if last_persisted_message is not None: # First we can store "last persisted message" time in ISO format (could be useful for sitemap.xml generation; SEO tasks etc) last_persisted_message_iso = last_persisted_message.sent_at.isoformat() # Use the natural time package form contrib.humanize to convert our datetime to a string. last_persisted_message = naturaltime(last_persisted_message.sent_at) return last_persisted_message else: return "No activity to report" Which is … -
Autofill database column after form submission in django
Using Django 2.0 I have a model class named Book that asks for title, author, year but I have another column in that row that requires for a unique id based on the authors name, book title, and random numbers. This is my model class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=50) year = models.PositiveSmallIntegerField() identification = models.CharField(max_length=50, blank=True) holder = models.ForeignKey('Person', related_name='book_holder', on_delete=models.PROTECT(), null=True, blank=True) available = models.BooleanField(default=True, blank=True) overdue = models.BooleanField(default=False, blank=True) and it will be used in a form that only asks for the title, author, and year but what im looking for is how can i fill the identification column after the user submits the form. So for example if the user enters Harry Potter for the title and J. K. Rowling for the author, I want identification to have a value of a combination of both plus an eight digit random number at the end something like JH28194637 but I also need this column to be unique for every book so if i had to of the same Harry Potter books, I would need both to be different so one could be JH28194637 while the other one could be JH39287104. I will be using ajax … -
Django admin shows dates in UTC time zone instead of TIME_ZONE
I run django 11 with the following timezone settings: USE_I18N = True USE_L10N = True USE_TZ = True TIME_ZONE = 'Europe/Kiev' The admin app shows all the dates using UTC timezone and doesn't use TIME_ZONE settings. What should I do to show the dates in admin using the settings.TIME_ZONE instead of UTC? -
Conditional validation depending on POST parameter Django
I have a form that I am trying to have some "conditional" validation on, depending on the button the user clicks. The fields should all be required if the user clicks "Submit", and none should be required if the user clicks "Draft". My models specify that no fields are required, to accomdate the draft. Then I tried to override it to require the validation only when a certain button is clicked, but I can't figure out for the life of me how to do it. I've simplified the code below. The form: class MOCForm(forms.ModelForm): facility = forms.CharField(required=False) def fields_required(self, fields): """Used for conditionally marking fields as required.""" for field in fields: if not self.cleaned_data.get(field, ''): msg = forms.ValidationError(" This field is required.") self.add_error(field, msg) def clean(self): self.fields_required(['facility']) return self.cleaned_data The view method: def post(self, request): if request.POST.get('_start') == '' or request.POST.get('_draft') == '': MOC_form = forms.MOCForm(request.POST, prefix="MOC_form", instance=MOC) if request.POST.get('_draft') == '' or MOC_form.is_valid(): MOC_form.save() if request.POST.get('_start') == '': MOC.submitted_date = timezone.now() if request.POST.get('_draft') == '': MOC.status = C.moc_status_draft() if request.POST.get('_start') == '' or request.POST.get('_draft') == '': MOC.creator = request.user MOC.save() if request.POST.get('_start') == '' or request.POST.get('_draft') == '': # If there is an activation (i.e. it is part of … -
django getting error about views.py
This is my views.py from django.shortcuts import render from . models import Houses def houses_list(request): house = Houses.objects.all().order_by('owner') return render('Houses.html',{'houses':house}) this my models.py from django.db import models class Houses(models.Model): owner = models.CharField(max_length=250) house_name = models.CharField(max_length=500) country = models.CharField(max_length=500) genre = models.CharField(max_length=100) def __str__(self): return self.house_name class house(models.Model): houses = models.ForeignKey(Houses, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) house_title = models.CharField(max_length=250) this my url.py from django.urls import path from . import views urlpatterns= [ path('', views.Houses, name='Houses'), ] this my html file {% load static %} <html> <head> <meta charset = "utf-8"> <title>Houses</title> </head> <body> <h1>House list</h1> <div class="house"> {% for house in houses %} <div class="house"> <h2><a href="#">{{Houses.house_name}}</a></h2> <p>{{Houses.owner}}</p> <p>{{Houses.genre}}</p> </div> {% endfor %} </div> </body> </html> I'm tring to get the data from my database but on the web getting attribute no object error.But I can see the all objects on the admin page do you have any idea what I'm doing wrong? -
Django Rest Framework - Authentication credentials were not provided when using renderer
I have a small company web service written in DRF. It uses basic authentication so I have this in my settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication' ), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), } When I browse any pages there is a basic popup window provided by default that asks for username/password. It suits my needs as I don't have to deal with login forms ans so on and I only need very basic authentication anyway. It all worked great until I started creating my renderer: class MyRenderer(BaseRenderer): def render(self, data, media_type=None, renderer_context=None): logging.debug(data) return data At this point it prints in logs: {u'detail': u'Authentication credentials were not provided.'} If I browse any other page with a web browser it just asks for a username/password in popup window and remembers it for some time. So after authorising on another page if I come back to my page with renderer and it works. Why it doesn't behave like other pages? How can I make to ask for username/password like all the other pages? -
Django with AJAX - security concern
Sorry for not providing any code, but this is purely theoretical, so picture, for example, an application that sends Like/Dislike asynchronous requests with AJAX in Django. I got to a point with Django, where I can send requests containing cookies (sessionid, and csrftoken). My ajax functions aren't form based - they send a request without a form. I logged the requests I'm sending with chrome, copied the entire request body, and put it into Restlet Client to send them again. What I found is that when I change the sessionid, the request is completely broken for obvious reasons. I can change the csrf token all I want and it produces no complications. What that means is that csrf token is unused. How do I validate that token in a view (without a form), or should I not worry about it? By the way, is sessionid all that is required to make any requests on someone's behalf without knowing their passsword? Logging out doesn't kill the session and sessions have a long lifetime (default 2 weeks). -
missing 1 required positional argument 'request'
I would like to know why I have it wrong that is what I lack def user(request): User = User.objects.filter(empresa_area_id=request.user.empresa_area_id) return HttpResponse(User) -
Django crashign when using validator on model field
Why is django crashing (without error) when setting validators=[...] on my Image and File fields in my model? When I uncomment my import / validators settings everything works fine. It seems the validator is being hit and even setting the attributes on __init__ but then it just crashes after initializing all of the validators. My validator is: import magic from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.utils.translation import ugettext_lazy as _ @deconstructible class MimeTypeValidator(object): def __init__(self, valid_mime_types): self.valid_mime_types = valid_mime_types def __call__(self, value): try: mime_type = magic.from_buffer(value.read(1024), mime=True) if not mime_type in self.valid_mime_types: raise ValidationError(_('%s is not an acceptable file type.' % value)) except AttributeError as e: raise ValidationError(_('This file type of %s could not be validated.' % value)) I'm setting it on my fields by doing: field = models.ImageField(....., validators=[MimeTypeValidator(settings.VALID_IMAGE_MIME_TYPES)] and similarly for file fields.