Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Cannot resolve keyword "is_active'' on /accounts/password_reset/
I am trying to implement Django's built-in password reset functionality using my custom User model but I am running into this error when I try to submit an email address at /accounts/password_reset/: FieldError at /accounts/password_reset/ Cannot resolve keyword 'is_active' into field. Choices are: ... Exception location: Exception Location: C:\Users\...\.virtualenvs\my_project-IsNTW6sC\lib\site-packages\django\db\models\sql\query.py in names_to_path, line 1378 I can provide the full traceback if someone wants to see it but it's reallllly long and it all points to back-end Django files. Here is models.py: def create_user(self, email, password=None, is_staff=False, is_admin=False, is_active=True): if not email: raise ValueError('Users must have an email address.') if not password: raise ValueError('Users must have a password.') user = self.model( email = self.normalize_email(email) ) user.staff = is_staff user.admin = is_admin user.active = is_active user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=254, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # USERNAME_field (email) and pw required by default objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def … -
django-filter didn´t filter
I use django-filters and django-tables2. The table worked great and display records on screen. But when I clicked on Filter button nothing happens. See code bellow and the image. tables.py class servicotable(tables.Table): class Meta: model = servico fields = ( 'id', 'dat_servico', 'tiposervico', 'num_protocolo', ) class filteredservicolistview(SingleTableMixin, FilterView): table_class = servicotable model = servico filterset_class = servicofilter filters.py class servicofilter(django_filters.FilterSet): dat_servico = django_filters.DateFromToRangeFilter() class Meta: model = servico fields = ['num_protocolo', 'dat_servico', 'statusservico', 'tiposervico', 'usuario'] views.py def consulta_create(request, id=None): queryset = servico.objects.all() f = servicofilter(request.GET, queryset=queryset) table = servicotable(f.queryset) table.paginate(page=request.GET.get('page', 1), per_page=25) RequestConfig(request).configure(table) context = { "filter": f, "lista": table, } return render(request, 'consulta/consultateste.html', context) consultateste.html {% load render_table from django_tables2 %} {% load bootstrap3 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% render_table lista 'django_tables2/bootstrap.html' %} </body> </html> -
django redis cache compression not working
I am using django-redis-cache library to compress data of the order of 1.5 MB. Some of it does have repetitive data and it should definitely be compressed by any compressing algo. Using zlib option with the following settings. CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/0', 'OPTIONS': { 'COMPRESS_MIN_LEN': 1 }, 'TIMEOUT': 3*24*60*60 }, 'compress': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/0', 'OPTIONS': { 'COMPRESS_MIN_LEN' : 1, "CLIENT_CLASS": "django_redis.client.DefaultClient", "COMPRESSOR_CLASS": "django_redis.compressors.zlib.ZlibCompressor", 'COMPRESSOR_CLASS_KWARGS': { 'level': 9 } }, 'TIMEOUT': 3*24*60*60 } } When I check on redis-cli before and after, I hardly find any difference in the serializedlength of the data. Before adding compression 127.0.0.1:6379> debug object "samplekey1" Value at:0x7f7d8ebb55c0 refcount:1 encoding:raw serializedlength:1669709 lru:954824 lru_seconds_idle:7 after adding compression level 9 127.0.0.1:6379> debug object "level9" Value at:0x7f7d8d362180 refcount:1 encoding:raw serializedlength:1669708 lru:955431 lru_seconds_idle:38 Using django-redis-cache==1.1.0 Can someone help me here with what I am doing wrongly? -
How to ensure file exists in Django project?
Hello Awesome People! My question is simple as the title clearly describes it. I have FileField in some models , I added a property method to check the existance of file: @property def file_exists(self): # Because sometimes, the field may contain the string path # but the file doesn't exist at all in the server if file: # if the string path exists return os.path.exists(self.file.path) # If the file exists in server This works perfectly in development, but when I migrate all my files on AWS, it raises an Error such I don't have permission to do that. I wonder what's wrong or Is there another way to test whether a file exists? Thank you in advance! -
Django Admin : Display pictures from Admin Form
Unfortunately I didn't handle Django since several months. I would like to know How I can display Django object from my Admin form to my template. I'm making a personal website and all forms (add pictures, add extra-info, ...) should be from admin panel. I have a model.py file : from __future__ import unicode_literals from django.db import models class ImageUpload(models.Model) : Nom = models.CharField(max_length=50, verbose_name="Nom de l'objet", blank=False) Instrument = models.CharField(max_length=50, verbose_name="Instrument", blank=False) Imageur = models.CharField(max_length=50, verbose_name="Imageur", blank=False) Monture = models.CharField(max_length=50, verbose_name="Monture", blank=False) Instrument_Guidage = models.CharField(max_length=50, verbose_name="Instrument de Guidage", blank=False) Imageur_Guidage = models.CharField(max_length=50, verbose_name="Imageur de Guidage", blank=False) Reducteur = models.CharField(max_length=50, verbose_name="Reducteur/Correcteur de Focale", blank=False) Logiciels = models.CharField(max_length=60, verbose_name="Logiciels", blank=False) Date = models.DateField() Nombre_Pose = models.IntegerField(verbose_name="Nombre de pose total") Temps_Pose = models.IntegerField(verbose_name="Temps de pose unitaire") Integration = models.FloatField(verbose_name="Temps de pose total") Darks = models.IntegerField(verbose_name="Nombre de Darks") Flats = models.IntegerField(verbose_name="Nombre de Flats") Bias = models.IntegerField(verbose_name="Nombre de Bias") Lunaison = models.FloatField(verbose_name="Pourcentage de Lune") FWHM = models.FloatField(verbose_name="FWHM moyenne") Temperature = models.IntegerField(verbose_name="Température") Lieu = models.CharField(max_length=60, verbose_name="Lieu de Photo", blank=False) Image_upload = models.ImageField(upload_to='Media/', verbose_name="Image") def __unicode__(self): return unicode (self.id, self.Nom, self.Instrument, self.Imageur, self.Monture, self.Instrument_Guidage, self.Imageur_Guidage, self.Reducteur, self.Logiciels, self.Date, self.Nombre_Pose, self.Temps_Pose, self.Integration, self.Darks, self.Flats, self.Bias, self.Lunaison, self.FWHM, self.Temperature, self.Lieu, self.Image_upload) I have my admin.py file : from … -
Django JSON format error
I am getting this error when I manually entered the data into POST request. But when I do it in the admin page, there is no error. Error at "contact_number" field This is the correct format when adding in admin: { "name": "Santos", "email": "san", "address": "san", "note": "san", "contact_number": [ "123455", "1231231", "23123123" ] } Error at "contact_number" field. This is the result when adding via postman in POST request: { "name": "3123", "email": "qwe@gmail.com", "address": "Col", "note": "noting", "contact_number": [ "['3123', '123123']" ] } views.py @method_decorator(csrf_exempt) def phonebook_list(request): if request.method == 'GET': phonebooklist = PhoneBook.objects.all() serialized_data = [pb.to_json() for pb in phonebooklist] return JsonResponse(serialized_data, safe=False) elif request.method == 'POST': data= request.body.decode('utf8') data= json.loads(data) try: new_contact = PhoneBook.objects.create(name=data["name"],address=data["address"],email=data["email"],note=data["note"]) ContactNumber.objects.create(contact_number=data["contact_number"],number=new_contact) serialized_data = [new_contact.to_json()] return JsonResponse({"created": serialized_data}, safe=False) except: return JsonResponse({"error":"not valid data"}, safe=False) models.py class PhoneBook(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100, default='address') email = models.CharField(max_length=50, default='email') note = models.CharField(max_length=100, default='note') def to_json(self): contact_numbers = [c.contact_number for c in self.contact_numbers.all()] return { 'name': self.name, 'email': self.email, 'address': self.address, 'note': self.note, 'contact_number': contact_numbers } def __str__(self): return self.name class ContactNumber(models.Model): number = models.ForeignKey(PhoneBook, related_name="contact_numbers") contact_number= models.CharField(max_length=30) def __str__(self): return self.contact_number -
Visual Studio 2015 PTVS, what's special for the project type of Django Web Project
I'm using Visual Studio 2015 with PTVS 2.2.6, and trying to debug my Django code inside VS IDE. The experiment is successful, but I'm really curious about one thing: From New Project wizard, If I create a project of type Django Web Project, I can set break point in my django code and do source-level debugging. For example, set a breakpoint on first line of a view function, the breakpoint hits when a client visits the web root-URL. If I create a project of type of the "plain" Web Project and add those same manange.py, settings.py, views.py etc into the project and then start debugging(F5), the django web server runs without error, but I will not be able to set breakpoints on my django code. My question is: What kind of project settings makes this difference? Can I manually change my "plain" Web Project to enable django source code debugging? -
Django, Best way to add data to Foreignkey field with ModelForm
I am playing around with django, ModelForms and i created PostModel and CommentModel with a foreign key. That is all post have a comment box which allow users to comment,here is my view which works perfectly i just want to know the best way i could have added the data to comment field def comment(request, id): try: post = PostModel.objects.get(pk=id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form['comment'].value() post.postcomment_set.create(comment=comment) return redirect('all_post') else: form = CommentForm() context['form2'] = form return render(request, 'prac/comment.html', context) except Exception as e: return HttpResponse(f'Error {e}') form in templates <form action="{% url 'comment' post.id %}" method="post"> {% csrf_token %} <p>{{form2.comment.label}}<br>{{form2.comment}} <input type="submit" value="Comment"></p> </form> everything works fine i just want to know the best way i could have handle data processing in my view -
`AbstractBaseUser` placed to a separate module
I'm enthusiastic in learning Django's source to establish my skills from bottom. In User model, it has password attribute. The model is import with command from django.contrib.auth.models import User, I checked the module django/models.py,failed to find password = models.CharField(), but eventually found it in django/base_user.py class AbstractBaseUser(models.Model): password = models.CharField(_('password'), max_length=128) last_login = models.DateTimeField(_('last login'), blank=True, null=True) It's interesting that AbstractBaseUser and BaseUserManager are encapsulated as a separate module rather than incorporated to models.py even though the codes are just 139 lines long. In base_user.py, it claims that """ This module allows importing AbstractBaseUser even when django.contrib.auth is not in INSTALLED_APPS.""" It's beyond my knowledge to grasp its idea. What's the benefit to design modules this way? -
Django signals not fired when saving from admin interface
I have configured some django signals on the pre_delete, post_save and pre_delete receivers for some models which are stored in a signals.py file in the same package as the models. Saving from an API call or directly in the terminal triggers the signals but when saving from the Admin dashboard they are not fired. I have imported the signals in the ready() method of the AppConfig which changes nothing. Any help on this issue? PS: Using django-oscar if that helps. -
Onclick show form input text, and once submitted load it in the table
Im using Django and trying to create a new html page, which onclick of Add New Name and Subject , should give me 2 input box , (both with drop down to select new old subjects/name or add new Name/Subjects) On Submit it should update the DB (i'm uisng MongoDB) and load it in the same page. My page list.html page currently is listing all the Names and Subjects as of now as shown below {% block content %} <!DOCTYPE html> <html> <head> <title>Subject List </title> <button onclick="myFunction()">Add New Name and Subject</button> {% load render_table from django_tables2 %} {% load static %} <link rel="stylesheet" href="{% static 'django_tables2/themes/paleblue/css/screen.css' %}" /> </head> <body> {% render_table table %} </body> </html> {% endblock %} -
Donwload file and redirect in a response
I want to make a response that both redirect to certain url and donwload a file. To download a file I use: content = "Example content" filename = "example-file-name". response = HttpResponse(content=content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response To redirect to url: response = HttpResponseRedirect(redirect_to=example_url) There is a way to make both things in a single response? -
Django ORM exclude fails
I have some problems with my query - with filter() it's ok but with exclude() doesn't work. My models: class Dictionary(DateTimeModel): base_word = models.ForeignKey(BaseDictionary, related_name=_('dict_words')) word = models.CharField(max_length=64) version = models.ForeignKey(Version) class FrequencyData(DateTimeModel): word = models.ForeignKey(Dictionary, related_name=_('frequency_data')) count = models.BigIntegerField(null=True, blank=True) source = models.ForeignKey(Source, related_name=_('frequency_data'), null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=_('frequency_data')) user_ip_address = models.GenericIPAddressField(null=True, blank=True) date_of_checking = models.DateTimeField(null=True, blank=True) is_checked = models.BooleanField(default=False) And I want to get some words from Dictionary where whose frequencies are not from some user Dictionary.objects.prefetch_related('frequency_data').filter(frequency_data__user=1)[:100] - OK Dictionary.objects.prefetch_related('frequency_data').exclude(frequency_data__user=1)[:100] - processor up to 100% and loading Without prefetch_related the same. What is wrong with exclude? -
Django selection form from model
Okay, so I've been stuck for a couple of weeks now working on this label system for work. I've created a django website that enables customers to translate labels for us. But I have now reached the end of my capabilities. I'm creating a form in which a customer chooses the item code that they wish to create a corresponding translation to. This means the form get's it's choice data from the model. When an item code is selected, I want to be able to grab the selected item code and reverse the user into the url matching that item code. Currently I am using a modelmultiplechoicefield to get the data from the model. This works and I am able to display the data in the HTML form. However I am not able to grab the data with cleaned_data as it just returns the entire queryset request. Which means I am getting the error NoReverseMatch at /labelcreator/ Reverse for 'create_label' with keyword arguments '{'pk': ]>}' not found. 1 pattern(s) tried: ['labelcreator\/(?P[0-9]+)\/create_label\/$'] Please see the code below. forms.py class LabelListForm(forms.Form): item = forms.ModelMultipleChoiceField(queryset=Label.objects.all(), label="") models.py class Label(models.Model): class Meta: verbose_name = "label" verbose_name_plural = "labels" item_code = models.IntegerField(unique=True, primary_key=True) item_description = … -
Specific queryset in SlugRelatedField for DRF serializer
I want to serialize multiple Objects. The have a SlugRelatedField to "Descriptors", which have unique names within one Project, but the same name can occure in different projects. Using this line in my serializer: row = serializers.SlugRelatedField(slug_field="name", queryset=Descriptor.objects.all() ) causes an error, because multiple Descriptors are returned. I need something like this: row = serializers.SlugRelatedField(slug_field="name", queryset=Descriptor.objects.filter(project=projectid)) Upon validation this causes NameError: name 'projectid' is not defined. Can i pass the projectid variable when calling the is_valid method so i can specifie the queryset? -
Why DateTimeField with auto_now_add can not get in form fields
Following is my model: class TestRule(models.Model): code = models.CharField(_('Code'), max_length=56, null=False, blank=False, db_column='code') name = models.CharField(_('Name'), max_length=128, null=False, db_index=True, db_column='name', blank=False) created_at = models.DateTimeField(_('Created At'), null=False, db_column='created_at', blank=False, auto_now_add=True) Form: class TestRuleForm(forms.Form): class Meta: model = TestRule fields = '__all__' view class TestRuleAdd(View): def get(self, request): form = TestRuleForm(request=request) content = {'form': form, 'edit': True} if request.GET.get('is_exam_wizard'): content.update({'iframe':True, 'is_popup': True}) return render(request, 'test_manager/testrule_form.html', content) When I display this form, I am able to see all fields excluding created_at. Does anyone know how do I get created_at field while updating certain object? -
Debugging what uWSGI worker is doing
I have a Django application (API) running in production served by uWSGI, which has 8 processes (workers) running. To monitor them I use uwsgitop. Every day from time to time one worker falls into the BUSY state and stays for like five minutes and consumes all of the memory and kills the whole instance. The problem is, I do not know how to debug what the worker is doing at the particular moment or what function is it executing. Is there a fast and a proper way to find out the function and the request that it is handling? -
Django: How can I add/delete fields in sqlite3 database?
I've started learning Django from a YouTube course. In the models.py file, there are two classes. class Album(models.Model): artist = models.CharField(max_length = 250) album_title = models.CharField(max_length = 250) album_logo = models.CharField(max_length = 1000) def __str__(self): return self.album_title + ' - ' + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) genre = models.CharField(max_length=250) def __str__(self): return self.song_title I added the genre in the Song after the migration. That's why I'm having problem while adding data. In the interactive shell, if I try to save() , it shows there's no 'genre' field. If I try to migrate again, it shows something like this: You are trying to add a non-nullable field 'genre' to song without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: What's the proper way of adding or deleting fields? -
Django: create charts using database query
I need to create charts using a database query, I've searched and found fusionCharts , I'm wondering if there is any other way to do so. Thank You in Advance -
Django+nginx try_files $uri @proxy_to_app not serving staticfiles
I'm using latest https://github.com/pydanny/cookiecutter-django template for my app and I want to use nginx instead of caddy webserver for production. So my docker compose is the same as default: https://github.com/pydanny/cookiecutter-django/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/production.yml except I switch caddy to nginx: nginx: build: context: . dockerfile: ./compose/production/nginx/Dockerfile image: abs_production_nginx depends_on: - django ports: - "0.0.0.0:80:80" env_file: - ./.envs/.production/.nginx My nginx docker file: FROM nginx:latest ADD ./compose/production/nginx/nginx.conf /etc/nginx/nginx.conf And configuration: user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; upstream app { server django:5000; } server { listen 80; charset utf-8; location / { try_files $uri @proxy_to_app; } # cookiecutter-django app location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app; } } } This config works, but I can't serve static files. I tried to add location /media { autoindex on; alias /app/media; } location /static { autoindex on; alias /app/staticfiles; } And in docker compose add: volumes_from: - django Tried to copy whole project to nginx container, that didn't work, because I do collectstatic command … -
Django orm to_char date column proble
I need to group by rows with formatted date column in django orm. Is there any way to get year and month as string in a date value? I expect this output in results.query SELECT to_char(u.created_at,'yyyy-MM-dd') as timeValue, SUM(CASE WHEN u.operation = 0 THEN 1 ELSE 0 END) AS blocked, SUM(CASE WHEN u.operation = 1 THEN 1 ELSE 0 END) AS unBlocked FROM um_url u WHERE (created_at <= 'sdate' AND created_at >= 'edate')GROUP BY to_char(u.created_at,'yyyy-MM-dd') ORDER BY to_char(u.created_at,'yyyy-MM-dd') ASC; but I get this output SELECT created_at, SUM(CASE WHEN operation = 0 THEN 1 ELSE 0 END) AS blocked, SUM(CASE WHEN operation = 1 THEN 1 ELSE 0 END) AS unBlocked FROM um_url WHERE (created_at <= 'sdate' AND created_at >= 'edate') GROUP BY created_at ORDER BY created_at ASC I try it with this query results = UmUrl.objects \ .filter(created_at__gte=sdate, created_at__lte=edate) \ .values('created_at') \ .order_by('created_at') \ .annotate(blocked=Sum(Case(When(operation=0, then=1), default=0, output_field=models.IntegerField()))) \ .annotate(unBlocked=Sum(Case(When(operation=1, then=1), default=0, output_field=models.IntegerField()))) -
What is different between `request.data['param-name'] ` or `request.data.get('param-name')` in Django
I am new in Django, I tried to get data from API 1 request.data['param-name'] output -:'9121009000' 2 request.data.get('param-name') output -:'9121009000' Both are giving the same result. So Which one is the best to use get data and Why. Thanks in advance -
Django bakery static url is 404
My django website loads urls ok. In settings.py I have STATIC_URL = '/static/' And then in templates: {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> Which loads fine in the page like this: <link rel="stylesheet" href="/static/css/style.css"> But this doesn't work if I try to export my site with django-bakery: /static/css/style.css:1 Failed to load resource: net::ERR_FILE_NOT_FOUND It works however if I change the variable to remove the trailing "/" to STATIC_URL = 'static/' and then it loads correctly: <link rel="stylesheet" href="static/css/style.css"> But if I remove the trailing "/" then the django website doesn't work anymore: GET http://127.0.0.1:8000/static/css/style.css 404 (Not Found) How can I make both work? -
Disable one of languages for non admin users
I am working with django 1.11 and I want to make one of languages, accessible only for logged admins - I mean French version. For normal users: http://www.example.com/en For admin users: http://www.example.com/en http://www.example.com/fr settings.py LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ) I had idea with: from django.contrib.auth.models import User in settings file, for example: if User.is_staff: LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ) else: LANGUAGES = ( ('en', _('English')), ) but I got an error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. during import: from django.contrib.auth.models import User -
Which field type for GeoJson in Django model and MongoDB?
I'm setting up Django with MongoDB using Djongo connector. In models.py, which is the correct field type for a MongoDB GeoJSON field (2D)? In MongoDB I have this field: "location" : [ 13.611847, 37.276262 ] In Django models.py: class Strutture(models.Model): name: models.CharField(max_length=255) location: ???