Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to use query string query of elasticsearch directly?
I am trying to write a django app and use elasticsearch in it with elasticsearch-dsl library of python. I don't want to create all switch-case statements and then pass search queries and filters accordingly. I want a way in which i can just pass the query string query described at https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-query-string-query.html and just get the corresponding query. Can anyone help me out? -
Related object reference does not work without importing the related model itself
I have 2 models in my app - In models/parent.py I have - class Parent: class Meta: db_table = "parent_table" start_date = models.DateField() end_date = models.DateField() In models/child.py I have - from models.parent import Parent class Child: class Meta: db_table = "child_table" some_ref = models.ForeignField(Parent) Now in models/parent.py I am defining a property as - @property def referred_values(self): return self.child_set.all() It gives me error - AttributeError: 'Parent' object has no attribute 'child_set' But if I import Child class in any file in my app, it works fine. Is this an expected behaviour or am I missing something here? Thanks in advance. -
Bootstrap Modal with django
here my views.py def delete_company(request): id = request.GET.get('id') company = models.Company.objects.get(id=id) return render(request, 'ajax/ajax_delete.html', {'company': company}) I have template_listview.html like this .... <button id="delete" data-id="{{company.id}}" data-url="{% url 'system:ajax_delete' %}" type="button" class="delete-company"> delete </button> .... $(document).on('click','.delete-company',function(){ var url = $("#delete").attr("data-url"); var id = $(this).data('id'); $.ajax({ url:url, data:{ 'id':id, }, success:function(data){ $('#modal-default .modal-dialog').html($('#modal-default .modal-dialog',data)); $('#modal-default').modal('show'); }, error:function(){ console.log('error') }, }); }); here my ajax_delete.html <div class="modal fade" id="modal-default{{ company.pk }}"> ... </div> iam trying access directly to url ajax/del-com/?id=15 its work well. but if i do with my button on templaye_listview.html its not showing anything. i know its because error on this code: success:function(data){ $('#modal-default .modal-dialog').html($('#modal-default .modal-dialog',data)); $('#modal-default').modal('show'); }, what should I write on success:function(data){ ? I dont have ide right now what should I do, to make it work. -
Django image:this field is required
I am trying to send a form with an image, I select the image but I always get: "this field is required" when I send the form. here is my code: models.py: from django.db import models from django.contrib.auth.models import User class Picture(models.Model): created_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) image = models.ImageField() caption = models.CharField(max_length=50) author = models.ForeignKey('auth.user', on_delete=models.CASCADE, related_name='pictures') forms.py: from django import forms class PictureForm(forms.Form): image = forms.ImageField() caption = forms.CharField(max_length=50) views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Picture from .forms import PictureForm from django.contrib.auth.models import User def pictures_view(request): pictures = Picture.objects.all() context = {'pictures': pictures} return render(request, 'pictures/pictures.html', context) def picture_form_view(request): if request.method == 'POST': form = PictureForm(request.POST, request.FILES) if form.is_valid(): clean_data = form.cleaned_data() Picture.objects.create(clean_data) return HttpResponseRedirect('/') else: form = PictureForm() return render(request, 'pictures/picture_form.html', {'form': form}) HTML: {% extends 'pictures/base.html' %} {% block title %}publish{% endblock %} {% block content %} <form class="form" action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} And a Little question, how can I complete the field author automaticly with the actual user? -
Django: list_display is not callable
I have a few models: ModelA, ModelB, ModelC each with identical attributes say x,y,z. I am trying to get them displayed in Django admin. I have registered each as @admin.register(ModelA): class ModelAAdmin(admin.ModelAdmin): list_display = ['x', 'y' , 'z'] However when I runserver, I get error which says The value of list_display[0] refers to 'x' which is not callable, an attribute of modelA, or an attribute or method on 'database.modelA' I am guessing this has got something to do with each model having identical names but I am not sure. How do I resolve this? -
Can Rsyslogd impact application performance
So our Django application logs to syslog server (Rsyslogd) using class logging.handlers.SysLogHandler. We configured remote forwarding action and it was working fine. Recently we introduced a second remote forwarding and it is behaving weird. 1) We see some logs being missed and inconsistent between two remotes. I even tried running rsyslogd in debug mode (-rn) but couldn't figure out anything. 2) when we enabled second forwarding rule, our Django application Web response time is like 10X slower than usual. Disabling second rule made it normal. Q1) So what could go wrong here, Is django waiting on Rsyslog socket. But i assume logging should be asynchronous. Q2) Do i need to use two different queues as mentioned in https://serverfault.com/questions/522341/how-do-i-setup-rsyslog-to-send-all-logs-to-multiple-remote-servers. Let me know what could possibly go wrong. -
malformed string when trying to send a post
i have a slight issued with my code, first there is a config function which allows me easily to change the value of my variable. So i have INVOICE=True which is set up in my settings.py and in my create function i'm checking if this INVOICE is having the value True then proceed. However, this is throwing an exception when i'm trying to check when the value of invoice is in this specific field.Here is the function which set up the conf. class ConfigurationOptions(models.Model): INT = '0' FLOAT = '1' STR = '2' LIST = '3' DICT = '4' BOOL = '5' CHOICES = ( (INT, 'int'), (FLOAT, 'float'), (STR, 'str'), (LIST, 'list'), (DICT, 'dict'), (BOOL, 'bool'), ) configuration = models.ForeignKey('configurable.Configuration', related_name='options', verbose_name='Configuration', db_index=True, null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=64, db_index=True,verbose_name='Option Name') value = models.TextField(verbose_name='Option Value') python_type = models.CharField(max_length=64, choices=CHOICES, verbose_name='Option Python Type') serialize = models.NullBooleanField(blank=True, null=True, verbose_name='Expose to front-ends') class Meta: unique_together = (("configuration", "name"),) verbose_name = "Configuration Option" verbose_name_plural = "Configuration Options" def __str__(self): return '%s' % self.name @classmethod def get_option(cls, fld, group=None, *args, **kwargs): query = { 'name': fld } if group is not None: query['configuration__name'] = group try: setting_value, value_type = cls.objects.filter(**query).values_list('value', 'python_type')[0] except IndexError: return … -
Django/django-taggit -- How to access filtered tag name in template
I'm looking for the right syntax to access my tag name. Here's my view: def tag_filter(request, tag): now = datetime.datetime.now() concerts = Concert.objects.filter(tags__name__in=[tag])\ .filter(date__gte=now).order_by('date') return render(request, 'concerts/calendar.html', {'concerts': concerts}) This is indeed getting the data I want. I'd like to display the name of the tag in the header of my template, but this is where I'm running into a snag. I'm trying this: {% elif request.resolver_match.url_name == "tag_filter" %} <h1>Upcoming Events with "{{ concerts.0.tags.name }}" Tag</h1> {% endif %} But {{ concerts.0.tags.name }} is returning nothing. I've tried a few variations but nothing so far. Any ideas? Thank you! Editing to add my urlconf, just in case that's relevant: url(r'^tag/(?P<tag>[\w-]+)/$', views.tag_filter, name="tag_filter"), -
When do you need to use --no-cache with docker-compose build for django
I'm using Docker to deploy a cookiecutter-django app to production. My question is when do I need to use --no-cache with docker-compose -f production.yml build? In particular, if I make a change to one of the settings.py files, will that change get picked up without using --no-cache. And what about changes to requirments.txt files? -
Error: Can't import Pinax
i'm trying to set upping local server with python and virtual enviroment. i have installed dependencis, pinax inclued, and when i start running local server appears Error: Can't import Pinax. Make sure you are in a virtual environment that has Pinax installed or create one with pinax-boot.py. enter image description here -
Pycharm & Django: ImportError: No module named 'local_settings'
I'm using jupyter notebook.I can run my script when I start jupyter notebook from this command. python manage.py shell_plus --notebook Now I want to use jupyter in Pycharm. import os, sys import dateutil.parser import django MYPROJECT = 'django/project/path' sys.path.insert(0, MYPROJECT) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "local_settings.py") django.setup() I got this error. Why I got "ImportError: No module named 'local_settings'"? Pycharm interpreter is same with pyenv. If you know how to solve this problem. Please help me!! --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-6-15bdc7d5902c> in <module>() 7 sys.path.insert(0, MYPROJECT) 8 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.py") ----> 9 django.setup() 10 from django.conf import settings 11 import main.management.commands.mws as mws /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/site-packages/django/__init__.py in setup(set_prefix) 17 from django.utils.log import configure_logging 18 ---> 19 configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 20 if set_prefix: 21 set_script_prefix( /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/site-packages/django/conf/__init__.py in __getattr__(self, name) 54 """Return the value of a setting and cache it in self.__dict__.""" 55 if self._wrapped is empty: ---> 56 self._setup(name) 57 val = getattr(self._wrapped, name) 58 self.__dict__[name] = val /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/site-packages/django/conf/__init__.py in _setup(self, name) 41 % (desc, ENVIRONMENT_VARIABLE)) 42 ---> 43 self._wrapped = Settings(settings_module) 44 45 def __repr__(self): /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/site-packages/django/conf/__init__.py in __init__(self, settings_module) 104 self.SETTINGS_MODULE = settings_module 105 --> 106 mod = importlib.import_module(self.SETTINGS_MODULE) 107 108 tuple_settings = ( /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/importlib/__init__.py in import_module(name, package) 124 break 125 level += 1 --> … -
Django: Can't filter spanned relationships
I have a few models and I'd like to filter out specific fields, but I keep getting the error: Cannot resolve keyword 'Unique' into field. Choices are:Parent, id, unique. Here are my model and my filter lookup: #models class Parent(models.Model): Parent = models.CharField(max_length = 30) objects = models.Manager() class Unique(models.Model): Unique = models.CharField(max_length = 10) Parent = models.ForeignKey(Parent, on_delete = models.CASCADE) objects = models.Manager() class Name(models.Model): Name = models.CharField(max_length = 20) Unique = models.ForeignKey(Unique, on_delete = models.CASCADE) objects = models.Manager() class Item(models.Model): Item = models.CharField(max_length = 30) Name = models.ForeignKey(Name, on_delete = models.CASCADE) objects = models.Manager() Here is the query I've been trying: if Parent.objects.filter(Parent__iexact = New_Parent.Parent).filter(unique__Unique__iexact = New_Unique.Unique).filter(unique__name__Name__iexact = New_Name.Name).filter(unique__name__item__Item__iexact = New_Item.Item).exists(): I want to ensure that certain models spanning through a ForeignKey relationship exist within the database. The New_ variables are form inputs. -
Populate postgres db with python script django docker
I want to populate postgres db using python script with docker-compose, but when i'm trying to add python prepopulate_db.py in my entrypoint.sh and run by docker-compose up, it fails with error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. How i can do this correct? Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ ENTRYPOINT ["sh", "./entrypoint.sh"] entrypoint.sh: #!/bin/bash # Collect static files echo "Collect static files" python manage.py collectstatic --noinput # Populate db python prepopulate_db.py # Apply database migrations echo "Apply database migrations" python manage.py migrate ## Start server python manage.py runserver 0.0.0.0:8000 docker-compose.yml version: '3' services: db: image: postgres web: image: crztssr/tasktracker:app_up depends_on: - db prepopulate_db.py import os import django from tasks.tests.factories import ( TaskFactory, CommentFactory, DescriptionFactory, create_user ) def populate(): for idx in range(100): user = create_user() task = TaskFactory.create() for x in range(10): CommentFactory.create(task=task, user=user) DescriptionFactory.create(task=task) def main(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "_project_.settings") django.setup() if __name__ == '__main__': main() populate() -
Different sets of fields for each object
I'm looking for a way to have Model each object of which contains different sets of fields for for another Model. The task is create an IntegrationType. Each object of this model should contain sets of fields needed to create an Integration object. For example we have an Facebook integration type which should define fields like app_id, key etc. And then we would have an ability to create Integration with Facebook integration type which should store values for these preconfigured fields. I'm using mysql database -
Django,self.context['request']
I am studying JWT authentication.This example is not clear to me. from django.contrib.auth import authenticate, user_logged_in from rest_framework import serializers from rest_framework_jwt.serializers import JSONWebTokenSerializer, jwt_payload_handler, jwt_encode_handler class JWTSerializer(JSONWebTokenSerializer): def validate(self, attrs): credentials = { self.username_field: attrs.get(self.username_field), 'password': attrs.get('password') } if all(credentials.values()): user = authenticate(request=self.context['request'], **credentials) Where does self.context['request'] comes from? -
Django with MS SQL Backend and Testing
Working on a project that ties into 2 databases that are based on MS SQL Server. These other DB's are the backbones to 2 other applications that I did not create and are not Django based. My application reads from those databases to get information for my application. I'm writing tests for my application - but the database user for my application does not have create rights for these MS SQL databases - so it cannot create any kind of test_ tables when running tests. What is the best way to handle that? My Thoughts: Idea 1: My initial thoughts were create a staging_ version of both MS SQL db's and create a user that has create rights to those databases so it can create the test_ tables, but I don't want to go bugging the DB admins to do that stuff if it doesn't work that way. I figured this route we could run tests and dev with --settings="staging_settings" and production with --settings="production_settings" Idea 2: Figure out how to dumpdata from those 2 db's into 2 large fixtures and try to recreate them in a local SQLite db for testing purposes only. The problems with this method is that … -
Django 1.11 IndentationError: unindent does not match any outer indentation level
I am using Dajngo 1.11. When I compile my code below, this is what I get: File "C:\Users\admin\mysite\blog\admin.py", line 14 list_filter = ('status', 'created', 'publish', 'author') ^ IndentationError: unindent does not match any outer indentation level Below is my code: from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') prepopulated_fields = {'slug': ('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ['status', 'publish'] admin.site.register(Post, PostAdmin) How can I solve it? -
Django2.0 “remove hardcoded urls in templates” not working
I'm checking out django for the first time following the tutorial [https://docs.djangoproject.com/en/2.0/intro/tutorial03/] When I change the hardcoded url from: <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> to: <li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li> I get a error as follow: My urls.py files are: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), # ex:/polls/5/ path('<int:question_id>/', views.detail, name='datail'), # ex: /polls/5/results/ path('<int:question_id>/vote/', views.vote, name='vote'), # ex: /polls/vote/ path('<int:question_id>/results/', views.results, name='results'), ] My views.py files are: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from .models import Question,Choice def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question':question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question':question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form return render(request, 'polls/detail.html',{ 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes +=1 selected_choice.save() # Always return an HttpRespinsedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list':latest_question_list} return render(request, 'polls/index.html', … -
Edit file in pre_save signal
I have a pre_save signal set up in the following way: class Snippet(models.Model): name = models.CharField(max_length=256, unique=True) audio_file = models.FileField(upload_to=generate_file_name, blank=True, null=True) @receiver(models.signals.pre_save, sender=Snippet) def prepare_save(sender, instance, **kwargs): if instance.audio_file: remove_headers(instance) Now I have had problems implementing the remove_headers function in a way that I can edit the file while it is still in memory and have it stored. I tried among others the following: def remove_headers(instance): byte_sequence = b'bytestoremove' f = instance.audio_file.read() file_in_hex = f.hex() file_in_hex = re.sub(byte_sequence.hex(), '', file_in_hex) x = b'' x = x.fromhex(file_in_hex) tmp_file = TemporaryFile() tmp_file.write(x) tmp_file.flush() tmp_file.seek(0) instance.audio_file.save(instance.audio_file.name, tmp_file, save=True) This first of all would result in an infinite loop. But this can be mitigated by e.g. only calling the remove_headers method on create or so. It did however not work, the file was unchanged. I also tried replacing the last line with: instance.audio_file = File(tmp_file, name=instance.audio_file.name) This however resulted in an empty file to be written/saved. What am I missing here? -
Add number field to Django model
I have a django movie model class Film(models.Model): title = models.CharField(max_length=200) movie_id = models.CharField(max_length=8, unique=True, primary_key=True) director = models.ForeignKey('Director', on_delete=models.SET_NULL, null=True) year = models.IntegerField(null=True) genres = models.ManyToManyField(Genre) I need to use movie_id as primary key, but also i need a field, which represents number of item's row in table. It must increment automatically, just like standard "id" field. How can i add it? -
How to change protocol to https on wagtail sitemaps?
I have a django sitemap and wagtail sitemap for my site. The django sitemap is using https by simply setting the protocol variable in the class, but I can't figure out a way to do this for the wagtail sitemap without overriding many internal methods. Is there a simple way to use https for my wagtail sitemaps? -
Line "host all all 0.0.0.0/0 md5" deleted from the pg_hba.conf file at the same time every day
I have added this line "host all all 0.0.0.0/0 md5" to my pg_hba.conf file to allow connections to my database. Problem is that this line gets deleted around 13:07GMT everyday resulting in this error "no pg_hba.conf entry for host "127.0.0.1", user "****", database "****db", SSL off". I don't know how and why the line gets deleted(looks the the pg_hba.conf is been re-configured to default) I re-add the line to pg_hba.conf, restart postgres and the application works again. How do i resolve this problem to keep that line in the file permanently? I use (PostgreSQL) 8.4.20, Centos 6.8 I have also checked and can't find any cron job running around that time. Please your help is very much appreciated. Thank you. -
Tastypie sending POST to update Foreign Key
I've recently got started with Django (and python generally!), and I was looking to use Tastypie in order to automate additions to my database. For my current problem I have two tables in my database, one which displays the Company Name and Company ID, and the other which holds all the licence key information, as below: models.py class Company(models.Model): company_name = models.CharField(max_length=200, verbose_name= "Company Name") company_id = models.CharField(max_length=15, verbose_name= "Company ID") def __str__(self): return self.company_name class Licence(models.Model): company_id = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name= "Company ID") licence_key = models.CharField(max_length=100, verbose_name= "Licence Key") lpars = models.CharField(max_length=100, default = "", verbose_name= "List of Systems") rss = models.BooleanField(default = None, verbose_name= "RSS") gui = models.BooleanField(default = None, verbose_name= "RACFGui") exr = models.BooleanField(default = None, verbose_name= "Exception Reporter") zdt = models.BooleanField(default = None, verbose_name= "zDetect") bg = models.BooleanField(default = None, verbose_name= "BreakGlass") sspr = models.BooleanField(default = None, verbose_name= "Self Service Password Reset") rss_custom = models.BooleanField(default = None, verbose_name= "RSS Custom") expiry = models.DateField(auto_now=False, auto_now_add=False) trial = models.BooleanField(default = False, verbose_name= "Trial?") def __str__(self): return self.licence_key I've then defined all of the api stuff here: resources.py class CompanyResource(ModelResource): class Meta: queryset = Company.objects.all() resource_name = 'company' class LicenceResource(ModelResource): class Meta: queryset = Licence.objects.all() include_resource_uri = True resource_name … -
Django Ajax Returning full html
Facing an issue in Django! When trying to run jquery ajax, the response i get is complete HTML rather than what i have specified. Things work perfectly on my localhost but the above problem occurs when i am trying to deploy it. Has someone faced similar issues , or can help! -
funky behavior when hovering
I have menu icons spread over my html page, i've set an hover attribute but when hovering it behaves weird - sometimes it colors just part of the icon, in other cases it colors also other icons. hovering over the certificate(star) icon here is my css: .menu li a { color: #214761; cursor: default; } .menu li a:hover { text-decoration: none; color: #4cae4c; } .menu-icon{ font-size: 2.5em; text-align: center; } .menu-text{ text-align: center; } .menu{ margin-top: 10px; float: right; width: 100%; } .menu li{ list-style-type: none; float: right; margin: 0 15px; } .right-menu{ float: left !important; } and here is the html(template of django): <div class="menu"> <ul> <li> <a onclick="window.history.back(); return false;" > <div class="menu-icon"><i class="fas fa-arrow-right"></i></div> <div class="menu-text">back</div> </a> </li> {% if order %} <li class="right-menu"> <a href="{% url 'clients:info' order.clientID.id %}"> <div class="menu-icon"><i class="fa fa-user"></i></div> <div class="menu-text">watch {{ order.clientID.name }}</div> </a> </li> {% if order.coc %} <li class="right-menu"> <a href="{% url 'reports:coc' order.id %}" target="_blank"> <div class="menu-icon"><i class="fa fa-certificate"></i></div> <div class="menu-text">C.O.C</div> </a> </li> {% endif %} <li> <a href="{% url 'orders:edit' order.id %}" > <div class="menu-icon"><i class="fas fa-pencil-alt"></i></div> <div class="menu-text">edit</div> </a> </li> <li> <a id="delete" > <div class="menu-icon"><i class="fas fa-trash-alt"></i></div> <div class="menu-text">delete</div> </a> </li> {% endif %} </ul> …