Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extract image from Django media video file
I'm trying to store an image from a video file in django in the save method of a model. I've based in on this thread This is my save method for the model def save(self, *args, **kwargs): if not self.slug: orig = self.slug = slugify(unidecode(self.name)) for x in itertools.count(1): if not Project.objects.filter(slug=self.slug).exists() or (Project.objects.filter(slug=self.slug).exists() and self == Project.objects.get(slug=self.slug)): break self.slug = '%s-%d' % (orig, x) super(Project, self).save(*args, **kwargs) if not self.image and self.project_type=='video': vidcap = cv2.VideoCapture(settings.MEDIA_ROOT + self.video.url) success,image = vidcap.read() self.image = image self.image.name = 'video_images/' + self.slug + '.jpg' new_path = settings.MEDIA_ROOT + self.image.name cv2.imwrite(new_path, image) super(Project, self).save(*args, **kwargs) I've taken a look at success and it always comes out False (I've tried looping while not success and it eventually timesout) -
static content picking css files on when binded to gunicorn
this django project ran fine with following: # python manage.py runserver 0.0.0.0:8000 then I ran # python manage.py collectstatic which collected the static data and created it at the root of the project with name static. then I set the static URL in settings.py file like this # tail -2 eccomerceProject/settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') and when I bind the project with gunicorn and view it, all it shows is html & css is missing # gunicorn --bind 0.0.0.0:8000 myproject.wsgi STUCK HERE !!! -
django commands not working on raspberry pi
'import_export' - the app to import or export from excel sheets is working on windows but not on raspberry pi. The error it is showing no module named import_export. Similarly, @admin.site.register is working on windows but not on raspberry pi. Can anyone help how to make this work on a raspberry pi or any other alternatives -
Serving static files via Nginx proxying HTTPS to gunicorn django in docker-compose
I'm deploying my Django/Nginx/Gunicorn webapp to EC2 instance using docker-compose. EC2 instance has static IP where mywebapp.com / www.mywebapp.com points to, and I've completed the certbot verification (site works on port 80 over HTTP) but now trying to get working over SSL. Right now, HTTP (including loading static files) is working for me, but HTTPS is not. I think my nginx configuration is wonky. Here's the final docker-compose.yml: services: certbot: entrypoint: /bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;' image: certbot/certbot volumes: - /home/ec2-user/certbot/conf:/etc/letsencrypt:rw - /home/ec2-user/certbot/www:/var/www/certbot:rw nginx: command: /bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g "daemon off;"' depends_on: - web image: xxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/xxxxxxxx:latest ports: - 80:80/tcp - 443:443/tcp volumes: - /home/ec2-user/certbot/conf:/etc/letsencrypt:rw - static_volume:/usr/src/app/public:rw - /home/ec2-user/certbot/www:/var/www/certbot:rw web: entrypoint: gunicorn mywebapp.wsgi:application --bind 0.0.0.0:7000" image: xxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/xxxxxxxx:latest volumes: - static_volume:/usr/src/app/public:rw version: '3.0' volumes: static_volume: {} nginx.prod.conf: upstream mywebapp { # web is the name of the service in the docker-compose.yml # 7000 is the port that gunicorn listens on server web:7000; } server { listen 80; server_name mywebapp; location / { proxy_pass http://mywebapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /usr/src/app/public/; … -
Having trouble with django.core.exceptions.SuspiciousFileOperation: The joined path
"python manage.py collectstatic" is not working, I think it might not work for any file and this fa-brands-400.eot happened to be the first file. Error: django.core.exceptions.SuspiciousFileOperation: The joined path (/Users/monica/music-emotion/static/webfonts/fa-brands-400.eot) is located outside of the base path component (/Users/monica/music-emotion/staticfiles) Is settings.py supposed to be located in root or can it be in a subdirectory? My settings.py has this at the end- # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATICFILES_DIRS = ( os.path.join('me_main/static'), ) STATIC_URL = '/static/' # Configure Django App for Heroku. import django_heroku django_heroku.settings(locals()) -
Custom CreatView in Django
I have a model timetable_choices =( ('Monday','Monday'), ('Tuesday','Tuesday'), ('Wednesday','Wednesday'), ('Thursday','Thursday'), ('Friday','Friday'), ('Saturday','Saturday'), ) class Timetable(models.Model): day = models.CharField(max_length=9,choices=timetable_choices,blank=True) start = models.TimeField() end = models.TimeField() period = models.CharField(max_length=15) number_of_periods = models.IntegerField(default=8,blank=True) I have a createview for the same model : class Timetablecreate(CreateView): model = Timetable fields = ['day', 'start' ,'end','period','number_of_periods'] success_url = 'timetable-add' I am creating the timetable using the templates below timetable_form.html <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <h3>Add Timetable</h3> <form class="form-material m-t-40 floating-labels" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'add.html' %} <div class="form-group row"> <button type="submit" class="btn waves-effect waves-light btn-rounded btn-success">Submit</button> </div> </form> </div> </div> </div> </div> add.html {% for field in form %} <style> input{ width:400px; } </style> <div class="form-group"> <label class=" control-label col-4 col-form-label">{{field.label_tag}}</label> </input class="form-control" > {{field}} </div> {% endfor %} I want 8 sections like below in such a way that the field day has to be chosen once so that I can add respective periods under the day . -
I make the font end in java scene builder and i want to connect it with Django for back end, how can this be happen some gauidence needs
I want the front end in java and back end in python, for front end I use scene builder in java_F_X library and with its java give me more flexibility for front end and for python i use D_j_a_n_g_o , I not want to use D_J_A_N_G_O for front end or its web development for browser application . How can I connect them? -
How would I go about creating a gui to run a django project?
I have a Django project and I would like to create a simple python GUI to allow users to change the host address and port on the go without having to interact with a command prompt. I already have a simple python user interface but how would I go about coding something in python that would be able to run a command such as python manage.py createsuperuser and fill in the required information without a need to run it in a python script that just calls regular terminal commands such as: subprocess.call(["python","manage.py", "createsuperuser"]) I don't know if this is something one can do without commands but would be amazing if it is since then I can just implement it into my basic python GUI that would allow users to createsuperuser, runserver, makemigrations, migrate and even change the default host and port on the go. -
Cors error when accessing Django Rest API from front end Using Axios
Accessing django Rest API using axios gives following error Access to XMLHttpRequest at 'http://api.localhost:8080/auth/register-shop/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. I added django cors headers as mention in this link https://pypi.org/project/django-cors-headers/ frontend page axios({ method: 'post', url: 'http://api.localhost:8080/auth/register-shop/', //url: 'http://api.yuniq.ml/auth/register-shop/', headers: { "Access-Control-Allow-Origin": "*", "content-type": "application/json" }, data: { "name": Name, "address": Address, "city": City, "postalC ode": PostalCode, "telephone": Telephone, "openTime": Opentime, "closeTime": Closetime, "image_url": Image_url //still not working } }).then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); } settings.py INSTALLED_APPS = ['corsheaders'] MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware' , #add cors middleware 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_hosts.middleware.HostsResponseMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True error not solved after doing this -
How to fix file not found when trying to download a Csv file from django root directory
I just built a web app that converts pdf table to Csv which are stored on django root directory. But when I try to download the Csv file I get file not found error in the browser. Here is the code that trigger the download : <a href="/output.csv"download="output.csv">Download</a> -
HOw to create a URL for templateView
HOw to write A url for form using templateview. I wrote a method to validate and pass the company details through 'form'. and using that 'form' object im trying to access the .html fileds. Form.py class CompanyDetailsForm(forms.Form): class meta: fields = ['company_name','contact_person','employee_count','email','mobile_number'] widgets = { 'comment':Textarea(attrs={'cols':30,'rows':5}), } company_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'company Name'})) contact_person = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Contact Person'})) email = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Email'})) employee_count = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Number Of Employee'})) mobile_number = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Mobile Number'})) View.py class GetCompanyView(TemplateView): template_name = "astra/company_details.html" form = CompanyDetailsForm() def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['form']=self.form return context def company_details(request): if request.method =="POST": form = CompanyDetailsForm(request.POST) if form.is_valid(): company_name = form.cleaned_data['company_name'] contact_person = form.cleaned_data['contact_person'] email = form.cleaned_data['email'] employee_count = form.cleaned_data['employee_count'] mobile_number = form.cleaned_data['mobile_number'] try: form.save() send_mail(company_name,contact_person,email,employee_count,mobile_number,['salesastra500@gmail.com']) except BadHeaderError: return BadHeaderError return render(request,'astra/company_details.html',{'form':form}) else: return render(request,'astra/company_details.html') I want to run my company_details.html file using templateview .i'm not able to write the url for same.Plz suggest -
Django selenium webdriver can't find a table
I have a django code that uses a standalone selenium chrome driver. I'm trying to get attributes of a table from a url but it does not find the table. I've tried both find_element_by_xpath and WebDriverWait with EC.visibility_of_element_located methods. These two failed to find the table. from selenium import webdriver def setup_driver(self): logging.info("Setup driver...") chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument('--disable-extensions') chrome_options.add_argument("--incognito") chrome_options.add_argument("--disable-plugins-discovery") chrome_options.add_argument('--user-data-dir=/tmp') chrome_options.add_argument('--profile-directory=Default') chrome_options.add_argument('--headless') self.driver = webdriver.Chrome(chrome_options=chrome_options) self.driver.implicitly_wait(15) ---- This is another py file ---- from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import pandas as pd def __init__(self, remote=False, rental=False): info = { "url": "https://login.fmls.com/SAML/login.aspx?ReturnUrl=%2fsaml%2fSAML%2fSSOService.aspx%3fSAMLRequest%3djZLNTsMwEIRfJfKBWxLHrWhrmqCKCilSEagBDlyQ62waS7EdvE7VxydJy98BxMXyrnY934y8RKGblq86X5stvHWAPsjXKXlNaLUDyapwBxULp7tJFQo6KcOFhHkypwDsckaCZ3CorEkJiygJcsQOcoNeGN%252B3aLII6TRk88ck4RPK2Sxi08ULCda9ijLCj5u19y3yOG7sXpmo0g1G0up44IqL1d0mLor7AtxBSYgEtkcS3FonYSROSSUahEH5QSCqA3x2VojgBoUba7DT4M5v5KaEY0ro7xNP280XlRbeqeOIVUb9ca4HwtP1zD2QXbc9g6%252Bd7fZ1yi6Ebq%252BMdVAqB9KnCQmOujHIx8RT0jnDrUCF3AgNyL3kg13eJ8lbZ72VtiHZcpjmY7Du2%252F7f6%252BLDGcn%252B7WMZf1PKTtXPf5G9Aw%253D%253D%26RelayState%3dMatrix%2bSAML%2bLogin", "login_info": { "username": "your_username", "passwd": "your_passwd", "username_input_xpath": "//input[@id = 'PblcID']", "passwd_input_xpath": "//input[@id = 'passwordTextBox']", }, "search_info": { "residential_url": "https://matrix.fmlsd.mlsmatrix.com/Matrix/Search/Residential", "rental_url": "https://matrix.fmlsd.mlsmatrix.com/Matrix/Search/ResidentialIncome", "status_table_xpath": "//table[@class='S_MultiStatus']" }, "table_info": { "page_size_id": "m_ucDisplayPicker_m_ddlPageSize", "page_format_id": "m_ucDisplayPicker_m_ddlDisplayFormats", "next_button_xpath": "//span[@class='pagingLinks']/a[2]", "table_xpath": "//*[@id='m_pnlDisplay']/table" } } vars_range = range(0, 7) # super().__init__(info, vars_range, remote, rental) def login_mls(self): # # Login self.driver.get(self.info['url']) form = self.driver.find_element_by_xpath("//form") user = form.find_element_by_xpath(self.info["login_info"]["username_input_xpath"]) password = form.find_element_by_xpath(self.info["login_info"]["passwd_input_xpath"]) user.send_keys(self.info["login_info"]["username"]) password.send_keys(self.info["login_info"]["passwd"]) button = form.find_element_by_xpath("//input[@id = 'loginButton']") button.click() date_string ="2019-05-09" rental = False def search(self, date_string: str): # Get url if self.rental: self.driver.get(self.info["search_info"]["rental_url"]) else: self.driver.get(self.info["search_info"]["residential_url"]) inputs = self.driver.find_elements_by_xpath(self.info["search_info"]["status_table_xpath"] + "//input") … -
how to run django app binded with gunicorn?
I'm trying to run a pre-built django project binded with gunicorn & nginx, following the tutorial publishded over this link. enter link description here The tree command on the project folder gives this output. when I publish the project with # python manage.py runserver, I can view its contents. But when I try to bind it using unicorn with following command, it shows following errors. # gunicorn --bind 0.0.0.0:8000 DjangoWebsiteSample.eccomerceProject.wsgi.py [2019-05-10 05:25:11 +0000] [1912] [INFO] Starting gunicorn 19.7.1 [2019-05-10 05:25:11 +0000] [1912] [INFO] Listening at: http://0.0.0.0:8000 (1912) [2019-05-10 05:25:11 +0000] [1912] [INFO] Using worker: sync [2019-05-10 05:25:11 +0000] [1916] [INFO] Booting worker with pid: 1916 [2019-05-10 05:25:11 +0000] [1916] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 377, in import_app __import__(module) ImportError: No module named DjangoWebsiteSample.eccomerceProject.wsgi.py [2019-05-10 05:25:11 +0000] [1916] [INFO] Worker exiting (pid: 1916) [2019-05-10 05:25:11 +0000] [1912] [INFO] Shutting down: Master [2019-05-10 05:25:11 +0000] [1912] … -
'user' not available in template django
I am using a custom user model with builtin and custom authentication backends. the default for username-password login and the custom one for uid based login The login is working fine but the 'user' (Other than superuser) is not available in the template.Nor is the last_login getting updated in database. Here is my code backend.py from support.models import CustomUser class UsernameIdModelBackend(object): def authenticate(self, request, uid=None): try: user= CustomUser.objects.get(uid=uid) return user except CustomUser.DoesNotExist: return None def get_user(self, user_id): try: return CustomUser.objects.get(pk=user_id) except CustomUser.DoesNotExist: return None models.py from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): uid = models.CharField(max_length=50) Where did i go wrong.. -
Setup of static files in Heroku not working locally for Django
I am setting up a web app with Django 2.2 in Heroku and I was able to deploy it successfully in production but the app doesn't load the css files locally every time I try to run heroku local web. This is how I setup the configuration of my files in my Django app. - src - live-static - media-root - static-root - main_app - urls.py - wsgi.py - __init__.py - settings - __init__.py - base.py - local.py - production.py - pages - __init__.py - admin.py - apps.py - models.py - tests.py - views.py - templates - main_app - home.html - templates - base.html - static - main_app - css -cover.css - img -myimage.jpg - admin - css - img - js The following code is a snippet of the configurations from the production and local files: production.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' local.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root') My css and jpg files are not rendered locally but they are rendered in production. base.html {% load static %} <link href="{% static 'main_app/css/cover.css' %}" rel="stylesheet"> <img src="{% static 'main_app/img/myimage.jpg' %}" > I expect that when … -
Django + python-requests error "name 'response' is not defined"
I've been trying to write simple view that fetch data from Google Books Api from url https://www.googleapis.com/books/v1/volumes?q= search keyword, but so far unsuccessful. I'm getting response for example when I try to search for book "frodo" book 'frodo' reponse request url 'https://www.googleapis.com/books/v1/volumes?q=frodo' but also I'm getting error name 'response' is not defined All what I'm trying to do is only to GET data like title, authors and siplay them on view. Tried with https://jsoneditoronline.org/ to do something and what I've achevied is the format of data for example title of book looks like this object►items►0►volumeInfo►title But I'm trying to get all results not single ones so I'm not sure why there is error views.py import requests import json def api(request): book = {} if 'book' in request.GET: book = request.GET['book'] url = 'https://www.googleapis.com/books/v1/volumes?q=%s' % book reponse = requests.get(url) book = response.json() return render(request, 'books/api.html', {'book': book}) api.html {% block content %} <h2>Google API</h2> <form method="get"> <input type="text" name="book"> <button type="submit">search on google books api</button> </form> {% if book %} <p> <strong>{{ book.title }} {{ book.authors }} </p> {% endif %} {% endblock %} -
Django rest framework filter numbers less than list
I am using DRF and package Django-Filter version 1.1. In get call I am passing more than one values like 10,20,30, 40 in query parameter as below, http://websiteapi.comp/searchFilter?persona=name&age=10,20,30 so based on the value sent in age parameter, in this case 10,20,30, I want get all the records which are less than 10,20,30 values. Below is the my code snippet class ListFilter(Filter): def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class SqureFeetFilter(Filter): def filter(self, qs, value): value_list = value.split(u',') return super(SqureFeetFilter, self).filter(qs, Lookup(value_list, 'range')) class ProfileFiltter(django_filters.FilterSet): person = ListFilter(name='person') sf = SqureFeetFilter(name='age',lookup_expr='range') class Meta: model = Profile fields = [ 'person','age'] class ProfileSearchVieset(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = [IsAuthenticated] filter_backends = (DjangoFilterBackend,) filter_class =ProfileFiltter Current by using range look_up expression I am able to get value between two number, but when there are more than 2 values, not able to get less than value between passed number. Please guide me Thanks all -
Django ORM to find if a string contains column value
I'd like to know how to write ORM code of the following SQL: select * from t1 where 'ABCDEFG' LIKE CONCAT('%',column1,'%'); It seems that Django supports only the following code: XYZ.objects.filter(column1__contains='ABCDEFG') What I want is something like that: XYZ.objects.filter('ABCDEFG'__contains=column1) I'd like to know the correct way of Python/Django. Thank you. -
In Django ORM, is their an equivalent of the EntityFramework command EnsureCreated and EnsureDeleted?
In EntityFramework, in addition to migrations, you have a command that will drop a database and/or create a database: _dbContext.Database.EnsureDeleted(); _dbContext.Database.EnsureCreated(); There is very useful for initial development, experiments, demos and integration testing. Is there a command in Django that does the equivalent? -
I make a register api and i use it return a authentication credentials were not provided
i have this code to register but when i register return this. {detail: "authentication credentials were not provided"} and this my code please need help to deal with my whole app class RegisterApi(GenericAPIView): serializer_class = RegisterSerializer queryset = User.objects.all() def post(self, request, format=None, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save(request=self.request) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) }) and here the two serializers class # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("id", "username", "email") # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("id", "username", "email") extra_kwargs = {"password": {"write_only": True}} def create(self, data): user = User.objects.create( data["username"], data["email"] ) user.set_password(data["password"]) user.save() return user -
makemigration causing error "TypeError: expected str, bytes or os.PathLike object, not NoneType"
Running makemigration command inside docker container caused this error, can anyone please help me figure out what the problem is ? python3.7 manage.py makemigrations Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/reportlab/lib/utils.py", line 667, in open_for_read return open_for_read_by_name(name,mode) File "/usr/local/lib/python3.7/site-packages/reportlab/lib/utils.py", line 611, in open_for_read_by_name return open(name,mode) TypeError: expected str, bytes or os.PathLike object, not NoneType -
Is there a Django function for converting RawQuerySet to dataframe
I need to run a query like this - historic_data.objects.raw("select * from company_historic_data") This return a RawQuerySet. I have to convert values from this to a dataframe. the usual .values() method does not work with raw query. Can someone suggest a solution. -
Django annotate to foreign key model
Given the following models: class Alarm(models.Model): name = models.CharField(max_length=256, unique=True) value = models.BooleanField() name_translations = JSONField(null=True, blank=True, default={}) created_at = models.DateTimeField(editable=False) class HistoryAlarm(models.Model): alarm = models.ForeignKey(Alarm, on_delete=models.CASCADE) value = models.BooleanField() created_at = models.DateTimeField(editable=False) I can do the following: alarm_list = Alarm.objects.all().annotate( translated_name=KeyTextTransform('en-US', 'name_translations') ) alarm_list[0].translated_name > "Translation alarm 0" alarm_list = Alarm.objects.all().annotate( translated_name=KeyTextTransform('it-IT', 'name_translations') ) alarm_list[0].translated_name > "Traduzione allarme 0" How would I write the queryset so that I could do this? history_alarm_list = ??? history_alarm_list[0].alarm.translated_name > "Traduzione allarme 0" What I got so far is this, but it binds translated_name to history_alarm, not alarm: history_alarm_list = HistoryAlarm.objects.annotate( translated_name=KeyTextTransform('it-IT', 'alarm__name_translations') ) history_alarm_list[0].translated_name > "Traduzione allarme 0" -
Django Template Doesn't Render
I'm trying to use Django's templates to render a basic website based of a dictionary I have, but to no avail. I believe I'm doing it exactly like the docs, so it's probably a small problem. I've reviewed it many times but it seems to be perfect syntax. A huge thanks in advance The dictionary: posts= [ { 'author':'Theroumag', 'title':'Blog post 1', 'content':'First post content', 'date_posted':'January 27, 2019' }, { 'author':'Corey', 'title':'Blog post 2', 'content':'Second post content', 'date_posted':'May 13, 2019' } ] The faulty code <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for post in post %} <h1>{{ post.title }}</h1> <p>By {{ post.author }} on {{ post.date_posted }} </p> <p>{{ post.content }}</p> {% endfor %} </body> </html> -
Tabulating Django data in Pandas
I'm trying to make a reporting / analysis app. I want to move data from a simple Django 'polls' application into a DataFrame for analysis (basic stats initially). The expected volume of information is low so I am not optimising for performance. frame = pd.DataFrame.from_records([row for row in answer_set.values(col_names)], **kwargs) I can then 'join' subsequent frames(for different questions) on the 'user_id' column, provided I make it an index of the dataframe. My problem is that an answer is also indexed (but orthogonally) by 'question' and as a result I have only been able to get to a table like this (this is transposed because it was impractically wide): answer_fields User1 User2 questionpk 1 1 question__text 'How?' 'How?' answerfield1 'x' 'x' answerfield2 'y' 'z' questionpk 2 2 etc... I want to get a table more like this: table User User question question_text 1 2 1 'How?' field1 'x' 'x' field2 'y' 'z' But as far as I can see that requires a MultiIndex on the question dimension, making 'users' the columns, and if I cared about organising Users by demographics, I don't think I can have a multiIndex on that dimension too. I prefer this condensed format because I want to …