Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I cast a function parameter to a model to access values from it?
I have a Django model like this, class User(models.Model): user_name = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) user_id = models.CharField(primary_key=True, max_length=255) user_department = models.CharField(max_length=100) email = models.CharField(max_length=70) I have a file named UserModelOperation.py and have imported the User model, userData receives an instance of User class. UserModelOperation.py def create_user(userData): if isinstance(userData, User): if validate_create_user(userData) I am passing the userData to a function validate_create_user like this, commondatavalid.py def validate_create_user(userData_param): How do I cast the userData_param to User model so that I can read values from it ? -
Django many-to-many: Get a list of categories from a list of articles
For the sake of simplicity let's say I only have 3 models: Articles, Categories, Author. class Author(models.Model): name = models.CharField(max_length='100') ... class Categories(models.Model): name = models.CharField(max_length='100) ... class Articles(models.Model): name = models.CharField(max_length='100') author_id = models.ForeignKey(Author) categories = models.ManyToManyField(Categories) ... I filter a list of articles by author_id list_article = Articles.objects.filter(author_id=author_id) My question is, how do I retrieve a list of 'Categories' from that 'list_article'? Thank you. -
Play a midifile in javascript
I'm finishing a musical project based on Django, HTML and JavaScript, and I need a MIDI player based on JavaScript. I've been trying with two players: MIDIjs and midi-player-js. The second one doesn't work really well because the sound gets really weird when the song goes on. The first one needs to load some soundfonts and a base64 format, so it is not what I need. I need some player where you can load your MIDI file and it plays it correctly. Do anybody know a good MIDI player? I'd be really gratefull. I'm open to any advice about the way to do this. -
Heroku App Crashed After pushing and releasing by gitlab-ci
I have deployed a Django application on Heroku server. I have pushed my project without migrations and database manually by Heroku CLI. Then, pushing by Gitlab ci (which does the migrations before push) gives me app crashed error on Heroku side. I have encountered many "app crashed" errors before and could solve them by inspecting the logs. But this time I cannot understand what is the issue. I am sure that files are completely pushed and the application is released. Here is my Procfile: web: gunicorn --pythonpath Code Code.wsgi --log-file - My project is in the "Code" folder and my Django project name is Code. Error part of the heroku logs: 2019-06-08T08:02:50.549319+00:00 app[api]: Deployed web (c1f5c903bedb) by user arminbehnamnia@gmail.com 2019-06-08T08:02:50.549319+00:00 app[api]: Release v6 created by user arminbehnamnia@gmail.com 2019-06-08T08:02:51.268875+00:00 heroku[web.1]: Restarting 2019-06-08T08:02:51.277247+00:00 heroku[web.1]: State changed from up to starting 2019-06-08T08:02:52.494158+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2019-06-08T08:02:52.517991+00:00 app[web.1]: [2019-06-08 08:02:52 +0000] [4] [INFO] Handling signal: term 2019-06-08T08:02:52.519983+00:00 app[web.1]: [2019-06-08 08:02:52 +0000] [11] [INFO] Worker exiting (pid: 11) 2019-06-08T08:02:52.529529+00:00 app[web.1]: [2019-06-08 08:02:52 +0000] [10] [INFO] Worker exiting (pid: 10) 2019-06-08T08:02:52.823141+00:00 app[web.1]: [2019-06-08 08:02:52 +0000] [4] [INFO] Shutting down: Master 2019-06-08T08:02:52.958760+00:00 heroku[web.1]: Process exited with status 0 2019-06-08T08:03:09.777009+00:00 heroku[web.1]: Starting process with command … -
Python/Django remove text in variable
at my views.py i have the following line encrypted_token_message = encryption_key.encrypt(PGPMessage.new(token_message), cipher=SymmetricKeyAlgorithm.AES256) which creates a PGP message with a version information like this -----BEGIN PGP MESSAGE----- Version: XYZ xxxblabla How can i remove this version line? Thanks and regards -
D3 gauge charts with sub value indicators and labels
I need to have a sub-value indicator and text in my d3 gauge chart. Also if I specify the number of sections the color palettes are assigned equally. For example, if I specify the number of sections as 3 the colors are equally divided into 3 equal percents(33.333% each). I need to have my custom ranges as 20% red,50% yellow and 30% green. How can I achieve this? Codepen link Javascript percent = .65 barWidth = 60 numSections = 3 # / 2 for HALF circle sectionPerc = 1 / numSections / 2 padRad = 0 chartInset = 10 # start at 270deg totalPercent = .75 el = d3.select('.chart-gauge') margin = { top: 20, right: 20, bottom: 30, left: 20 } width = el[0][0].offsetWidth - margin.left - margin.right height = width radius = Math.min(width, height) / 2 percToDeg = (perc) -> perc * 360 percToRad = (perc) -> degToRad percToDeg perc degToRad = (deg) -> deg * Math.PI / 180 svg = el.append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) chart = svg.append('g') .attr('transform', "translate(#{(width + margin.left) / 2}, #{(height + margin.top) / 2})") # build gauge bg for sectionIndx in [1..numSections] arcStartRad = percToRad … -
How to serve Angular images in Django app?
I have an Angular app and placed images in assets/img. I am loading them as such: src="/assets/img/img_name.png" Now I also serve my Angular app from a Django app. After running ng build and placing all static files in my_app/static/. I can't seem to serve the images from the Django app however. If I add /static/ in front of assets and build the it will work. However this is cumbersome and means I can't view the Angular during development. -
How to change database schema in Celery task?
I have a middleware that changes database schema depending on subdomain: def tenant_schema_from_request(request): hostname = hostname_from_request(request) tenants_map = get_tenants_map() return tenants_map.get(hostname) def set_tenant_schema_for_request(request): schema = tenant_schema_from_request(request) with connection.cursor() as cursor: cursor.execute("SET search_path to {}".format(schema)) class TenantMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): set_tenant_schema_for_request(request) response = self.get_response(request) return response but how to change database schema in Celery task? tasks.py @shared_task def send_notification_task(user_id): user = User.objects.get(pk=user_id) ... -
django fetching data from form and validating the data without using inbuilt django forms
I have a requirement of validation of forms before processing further through django views. However i dont want to use django inbuilt forms functionality. I have a code written in HTML and i wanted to validate in my django views? Which approach is best for validation? I am thinking of using django inbuilt forms for validation purpose, so i will define forms fields and other required attribute in forms.py and will call that class for validation using form.is_valid() function. Should i go through this approach or any other recommended solution? Thanks!! -
How to change Django database value in a template?
I am making a blog site which allows users to like or dislike a blog. I want to make like/dislike buttons, when clicked increase likes of blog by 1. How can I achieve this? -
The view mysite.views.Attendancecreate didn't return an HttpResponse object. It returned None instead
I am trying to create an attendance system for a list of employees , Models attendance_choices = ( ('absent', 'Absent'), ('present', 'Present') ) class Head_of_department(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=30) def __str__(self): return self.first_name class Employee(models.Model): first_name = models.CharField(max_length=200, unique=True) last_name = models.CharField(max_length=200, unique=True) head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True) email = models.EmailField(max_length=100) def __str__(self): return self.first_name + ' ' + self.last_name class Attendance(models.Model): head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True) employee = models.ForeignKey('Employee', on_delete=models.CASCADE, ) attendance = models.CharField(max_length=8, choices=attendance_choices, blank=True) Views class Attendancecreate(CreateView): model = Attendance fields = ['employee'] success_url = '/dashboard/' def get_context_data(self,** kwargs): context = super(Attendancecreate, self).get_context_data(**kwargs) context['formset'] = AttendanceFormset(queryset=Attendance.objects.none(), instance=Head_of_department.objects.get(email=email), initial=[{'employee': employee} for employee inself.get_initial()['employee']]) context['attendance_form'] = Attendanceform() email = self.request.user.email hod = Head_of_department.objects.get(email=email) context["employees"] = Employee.objects.filter(head_of_department =hod) return context def get_initial(self): email = self.request.user.email hod = Head_of_department.objects.get(email=email) initial = super(Attendancecreate , self).get_initial() initial['employee'] = Employee.objects.filter(head_of_department=hod) return initial def post(self, request, *args, **kwargs): formset = AttendanceFormset(queryset=Attendance.objects.none(), instance=Head_of_department.objects.get(email=email), initial=[{'employee': employee} for employee inself.get_initial()['employee'])) if formset.is_valid(): return self.form_valid(formset) def form_valid(self, formset): instances = formset.save(commit=False) for instance in instances: instance.head_of_department = get_object_or_404(Head_of_department, email=self.request.user.email) instance.save() return HttpResponseRedirect('/dashboard/') def form_invalid(self, formset): print ('errors') print (formset.errors) Forms class Attendanceform(ModelForm): class Meta: model = Attendance fields = ('employee','attendance','hod') AttendanceFormset = … -
How to pass objects from django modelsobjects to javascript code?
I want to send data from my django views file to a javascript function in a seperate file(script.js).The javascript function does not accept any arguments and generates the html template by taking data from another javascript file (data.js).I need a way to send data to any of the javascript file. -
django.db.utils.ProgrammingError: relation "django_session" does not exist
I made a migrate in local for my local model change but had to revert for some reason. After taking the latest pull from git I got some conflict and was not able to solve it. In order to overcome it, I have created a new workspace and a new database and also took a fresh checkout. Since there was some duplicate issue I used python manage.py migrate --fake. That helped me to migrate the database to Postgres without error. but when I tried to access Django admin after creating superuser I am getting, django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 Why am I getting this? How can I overcome it -
django nested query filtering
I have nested models. like these: class Items_Relation_Income_Statement(models.Model): statement = models.ForeignKey('Items_Income_Statement', related_name="items" ,on_delete = models.CASCADE ) item = models.ForeignKey('Income_Statement' ,on_delete = models.CASCADE ) amount = models.BigIntegerField() class Items_Income_Statement(models.Model): statement_id = models.BigIntegerField(primary_key=True) com_id = models.IntegerField() bourse_symbol = models.CharField(max_length= 100, null=True, blank=True) full_title = models.CharField(max_length= 100, null=True, blank=True) period_type = models.IntegerField() fiscal_year_end = models.CharField(max_length= 100, null=True, blank=True) jalali_fiscal_year_end = models.CharField(max_length= 100, null=True, blank=True) period_end = models.CharField(max_length= 100, null=True, blank=True) jalali_period_end = models.CharField(max_length= 100, null=True, blank=True) anouncement_date = models.CharField(max_length= 100, null=True, blank=True) jalali_anouncement_date = models.CharField(max_length= 100, null=True, blank=True) audited = models.BooleanField() represented = models.BooleanField() consolidated = models.BooleanField() and the result of the query string is something like this: { "statement_id": 129928, "com_id": 1, "bourse_symbol": "rrr", "full_title": "ghg", "period_type": 12, "fiscal_year_end": "2012-03-19T00:00:00", "jalali_fiscal_year_end": "1390/12/29", "period_end": "2012-03-19T00:00:00", "jalali_period_end": "1390/12/29", "anouncement_date": "2013-06-11T00:00:00", "jalali_anouncement_date": "1392/03/21", "audited": true, "represented": true, "consolidated": false, "items": [ { "id": 73, "amount": -272087, "statement": 129928, "item": 1 }, { "id": 74, "amount": -8075, "statement": 129928, "item": 5 }, ] } I just want to have some items with special item_id, not all of them. what should I do? is there any way for getting special items in the items list not all of them -
How to install markdown package in Django
I want to install Markdown in My Django files. How and where can i add this Markdown Package? Thanks in advance. -
Django REST Framework as backend for tracking user history
I'm trying to track user history using a DRF backend. For that, I've created a history table that will get a new timestamped row with each update. This model is a many-to-one and has a reference to the user model by a foreign key. Here comes the confusing part. Every time I pull up the user profile, I would like to also pull the last entry into the history table. Thus, I am considering adding a couple of columns in the table which get updated with every insert into the history table since this is probably less expensive than performing a secondary lookup each time. I'd like some feedback on this approach. Additionally, I'm slightly confused by how to perform this update/insert combination via a single API endpoint as DRF seems to only support one-to-one CRUD. For illustrative purposes, I'd like to achieve the following: User hits API endpoint with access token and update values --> Insert history table --> update user table for user's row with inserted details Thanks! -
Django safe filter on textfield is effecting button tag
I am using the safe filter to allow an embedded html tag to work but it is effecting the button underneath it. I tried to use the escape filter in combination with safe but nothing seems to work. <p class="card-text"> {{ post.text | truncatewords:200 | safe | escape}} </p> <a href="{% url 'detail_post' post.id %}" class="btn btn-primary"> Read More &rarr; </a> This is the result: when it should be: -
Error : [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version
I have been battling with this issue and will need help. So I am using django-cookiecutter + docker for the project. The app runs ok after deploying the docker container to the server. But when trying to push changes through cirlceci, I get this error at the deploy phase Checking connection to Docker... Docker is up and running! To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: docker-machine env production Building postgres ERROR: SSL error: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) Exited with code 1 My circle config.xml jobs: build: machine: true working_directory: ~/app_api steps: - checkout - run: name: Run tests command: | docker-compose -f local.yml up -d docker-compose -f local.yml run django python manage.py help docker-compose -f local.yml run django pytest deploy: machine: true working_directory: ~/app_api steps: - checkout - add_ssh_keys: fingerprints: **:**:**:**:**:**:**:**:**:**:**:**:**:**:**:** - run: name: Deploy Master to Digital Ocean command: | cp ./id_rsa.pub ~/.ssh ls -al ~/.ssh base=https://github.com/docker/machine/releases/download/v0.14.0 && curl -L $base/docker-machine-$(uname -s)-$(uname -m) >/tmp/docker-machine && sudo install /tmp/docker-machine /usr/local/bin/docker-machine mkdir -p .envs/.production echo POSTGRES_HOST=$POSTGRES_HOST >> .envs/.production/.postgres echo REDIS_URL=$REDIS_URL >> .envs/.production/.django ... docker-machine create --driver generic --generic-ip-address 1**.2**.1**.**7 --generic-ssh-key ~/.ssh/id_rsa production eval "$(docker-machine env production)" docker-compose … -
Service 'web' failed to build with Protocol error
I am trying to use postgresql in the docker container. However, i get an error Service 'web' failed to build: The command '/bin/sh -c apk add --update --no-cache --virtual .tmp-build-deps gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev' returned a non-zero code: 4 I get other related issue like ERROR: mpfr3-3.1.5-r1: Protocol error. Here is the screenshot of an issue as well as this might be related to each other here is the code Dockerfile FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 # set working directory which will be inside ubuntu WORKDIR /code #### Install a dependency #### # Copies new files and resources to the image's filesystems RUN pip3 install pipenv COPY Pipfile Pipfile.lock /code/ RUN apk add --update --no-cache postgresql-client jpeg-dev RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev RUN pipenv install --system RUN apk del .tmp-build-deps COPY . /code/ RUN adduser -D user USER user docker-compose.yml version: "3.7" services: db: image: postgres:12-alpine environment: - POSTGRES_DB=database - POSTGRES_USER=admin - POSTGRES_PASSWORD=admin123 web: build: . command: > sh -c "python /code/manage.py wait_for_db && python /code/manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=database - DB_USER=admin - DB_PASS=admin123 volumes: - .:/code # lets us map … -
giving two choices in django without creating another class and foreignkey
let's say I want each post to have category but I know there will be only two categories. I don't want to create another model named class category and foreignkey it. is there a different way to do it? each post have either category1 or category2. I want to put this choice in post model field. -
Django: How to add users from group view in django admin?
How can i add users to a group using django admin just like adding permission ? A found an answer for older version of django https://stackoverflow.com/a/39648244/11616789 How can i implement it in django 2 and above -
Adding a Question functionality in Polls App - Django
I have created a polls app from Django Documentation but I want to add few more features to it like - Not only admin but every user without signup should get functionality to add a question - While adding a question there should be a valid date upto which one can vote otherwise it should be displayed "Polls are closed" and should be redirected to resuls page. This is my project Poll: poll |_ __init__.py |_ settings.py |_ urls.py |_ wsgi.py polls |_ static |_ templates |_ polls |_ contains base.html, index.html, detail.html, results.html |_ __init__.py |_ admin.py |_ models.py |_ apps.py |_ views.py |_ urls.py |_ tests.py admin.py file: from django.contrib import admin from .models import Question, Choice class ChoiceInline(admin.TabularInline): model = Choice extra = 4 class QuestionAdmin(admin.ModelAdmin): list_display = ('topic', 'question_text', 'pub_date', 'date_valid') list_filter = ['pub_date'] search_fields = ['topic'] fieldsets = [ (None, {'fields': ['topic', 'question_text']}), ('Date Information', {'fields': ['pub_date', 'date_valid'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) models.py file: from django.db import models import datetime from django.utils import timezone from django.urls import reverse class Question(models.Model): topic = models.CharField(max_length=200) question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') date_valid = models.DateField('validity date') def __str__(self): return self.topic def was_published_recently(self): now … -
Django DB Server time Now() - what is it?
I've been using from django.db.models.functions import Now to set timestamps in my PostgreSQL database for consistency. Thus far it's been completely swappable with a normal datetime object. However, now that I'm trying to put the result into a JSON field, it's made me realize that I have no idea how it works. Is there a way to do what I'm trying to do? from django.db.models.functions import Now from users.models import AnonymousUserTracking user, created = AnonymousUserTracking.objects.get_or_create(anon_id=id) user.actions.append( (action, Now()) ); user.save() Error Object of type 'Now' is not JSON serializable -
How to display a image when selected and before saving it in the database with django bootstrap
as i said i am trying to create an image when selected it shows me a preview image, before press the save button. Something like this: <div class="row align-items-center my-5"> <div class="col-lg-7"> <img class="img-fluid rounded mb-4 mb-lg-0" src=" HERE WILL BE THE IMAGE SELECTED " alt=""> </div> <!-- /.col-lg-8 --> <div class="col-lg-5"> <a class="btn btn-primary" href="#">Seleccionar!</a> </div> </div> <!-- /.row --> <div class="row"> <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title">IMAGEN 1</h2> <p class="card-text">Descripcion......</p> </div> <div class="card-footer"> <a href="#" class="SELECCIONAR">More Info</a> //When i press this button, i want to show a preview image in the field up beofore i press "Seleccionar!"... </div> </div> Anyone can help me with this? thank you! -
How to correctly use class attributes and inheritance in Django models?
I have the models: class Parent(models.Model): ... some_field = None def use_some_field(self): if not self.some_field == None: print(self.some_field) class Meta: abstract = True class ChildOne(models.Model): pass class ChildTwo(models.Model): some_field = models.CharField(max_length=255) class ChildThree(models.Model): some_field = models.URLField() The parent class has an attribute called some_field, and this attribute is used in a method. By keeping this method in the parent class, I reuse a lot of code. Some classes don't really over-ride the some_field attribute such as ChildOne, and the ones that do, change the field types. The method still works as expected because it always checks for null. However, I recently realized that I am using class attributes, and these are shared between instances. This could lead to quite a lot of issues in the future. So my question is this, how do I do this correctly?