Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create field in Django model that refers to another field in the same model
I want to create field in my Model that refers to another field (in the same model) and modifies it. My code: class Result(models.Model): score = models.IntegerField(default=10) rank = models.IntegerField(score/2) // how to point to score from the same model (Result)? -
Best and simplest way of deploying django app?
I would like to ask few questions. I finally got to deploying my app, but it's even bigger headache than building the app itself.. Apparently, I would need virtual server, so my first question is does the location of provider matter for SEO? Should I find a local provider? Also, do you maybe have any step by step tutorial on how to deploy django app? I have searched and they are all just different and too complicated for my current skill level. Thanks -
How to automaticly flag stings for makemessage translation file in django
I'm creating a signal that sends messages to multiple users, and each message should be translated to the receiver's language. this is a simplified example of that the alert handler does: def alert_handler(**kwargs): t_message = kwargs.pop("message", None) context = kwargs.pop("context", None) for recipient in recipients: activate(recipient.language) message = _(t_message, context) new_alert = Alert(recipient=recipient, message=message) This works as intended but the makemessages command doesn't recognize the sting passed in the kwargs as a translatable string. Is it possible to flag a string to be picked up by the makemessages command? -
Django UpdateView
I am using the generic Django Views for creating CreateViews and UpdateViews in my views.py - where the field 'Author' is a ForeignKeyField in the model: class BookCreate(CreateView): model = Book fields = ['title', 'author'] The generically rendered Creation-Form supplies a DropDown-List where I can choose the Author - so far so good. My question: How can I sort that dropdown alphabetically? Thanks in advance for your help!! -
django object has no id, or is at least not passing any id
I'm trying to get my template to pass an object's id to the relevant url, but I'm having no luck. In my template, I'm trying to pass "player.id". The template's name is "show.html" Like this... <tr> <td>{{ QB }} <a href="{% url 'delete_player' player.id %}">Delete</a> </td> </tr> The url I'm trying it pass it to is this... path('show/<int:id>',views.show, name="show") The url needs an id but isn't getting one. The problem seems to be coming from the relevant views.py function that I'm trying to link to "delete_player" def delete_player(request, id): player = Player.objects.get(id=id) player.delete() return redirect('show') show.html is being rendered by show() def show(request, id): player = Player.objects.all(id=Player.id) print(player) user = request.user if user.is_authenticated: try: QB = Quarterback.objects.values_list('name', flat="True")[0] except IndexError: QB = 'empty' try: RB = Runningback.objects.values_list('name', flat="True")[0] except IndexError: RB = 'empty' try: WR = Widereceiver.objects.values_list('name', flat="True")[0] except IndexError: WR = 'empty' try: TE = Tightend.objects.values_list('name', flat="True")[0] except IndexError: TE = 'empty' try: K = Kicker.objects.values_list('name', flat="True")[0] except IndexError: K = 'empty' print(player) context = { 'QB': QB[0:], 'RB': RB[0:], 'WR': WR[0:], 'TE': TE[0:], 'K': K[0:], 'player': player } return render(request,"game/show.html", context) when I try to access http://127.0.0.1:8000/game/show, I keep getting a 404 because there is no id to … -
Django Queryset: sum of interval field converted to seconds with group by (annotate)
in the contact table I keep the contact logs between some devices. # select * from contact; node | contact | start_time | end_time | duration | alert | id -----------+-----------+---------------------+---------------------+----------+-------+---- DEVI-C533 | DEVI-DEC2 | 2020-11-19 16:44:34 | 2020-11-19 16:44:34 | 00:00:00 | f | 1 DEVI-DEC2 | DEVI-E720 | 2020-11-20 08:57:26 | 2020-11-20 08:57:26 | 00:00:00 | f | 2 DEVI-D1BC | DEVI-F382 | 2020-11-20 09:06:15 | 2020-11-20 09:07:51 | 00:01:36 | f | 3 DEVI-E720 | DEVI-F382 | 2020-11-20 08:57:27 | 2020-11-20 08:57:27 | 00:00:00 | f | 4 DEVI-D1BC | DEVI-E720 | 2020-11-20 09:07:26 | 2020-11-20 09:07:32 | 00:00:06 | f | 5 DEVI-E720 | DEVI-F35E | 2020-11-13 12:19:33 | 2020-11-13 14:51:06 | 02:31:33 | f | 9 DEVI-DEC2 | DEVI-E44F | 2020-11-19 16:45:10 | 2020-11-19 16:45:10 | 00:00:00 | f | 11 DEVI-D1BC | DEVI-DF5C | 2020-11-19 16:44:44 | 2020-11-19 16:46:13 | 00:01:29 | f | 12 DEVI-D1BC | DEVI-DEC2 | 2020-11-19 16:40:36 | 2020-11-19 16:46:13 | 00:05:37 | f | 13 DEVI-D1BC | DEVI-F35E | 2020-11-19 16:44:07 | 2020-11-19 16:44:19 | 00:00:12 | f | 14 ... I need to return the grouped values as in the following query QUERY select node, contact, sum(duration) as … -
request.POST.getlist() returns empty list
I am not able to access my inputs thorugh request.POST.getlist() method, and when I run my program, all other fields are okay and I can see the result but when it comes to choices it return empty list. views.py if request.method == 'POST': teacher_get = request.POST.get('teacher') department_get = request.POST.get('department') subject_get = request.POST.get('subject') answer_list = [] print(teacher_get) print(department_get) print(subject_get) answer = request.POST.getlist("question_{{question.id}}") print(answer) OUTPUT: Ahmad Software Engineering Programming [] [26/Nov/2020 15:48:12] "POST / HTTP/1.1" 200 2353 INDEX.HTML <form action="{% url 'index'%}" method="POST"> {% csrf_token %} <select name="teacher"> {% for question in question %} <ol>{{ question.question }}</ol> {% for choice in rating_choices %} <input type="radio" name="question_{{question.id}}" value="{{choice.0}}">{{choice.1}} {% endfor %} {% endfor %} <br> <input type="submit" value="Vote"> -
How to fix Python Django TypeError
I have a simple model class which I want to return the the value for a field in my Django Admin. Error Logs from terminal TypeError: __str__ returned non-string (type NoneType) models.py class Solution(models.Model): description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) error = models.ForeignKey(Error, on_delete=models.CASCADE) def __str__(self): return self.error + " fixed by " + self.user -
Make soap request with certificate
I'm facing problem with making soap request. I've got three certificates .key, .csr and .pfx. With openssl i've changed .pfx to .pem certificate and try to add in session. This is the code: session = Session() session.cert = BASE_DIR + '/cert.pem' transport = Transport(session=session) transport.session.headers = self.headers client = Client(WSDL, transport=transport) self.service = client.create_service('{http://tempuri.org/}', self.endpoint) What i'm facing is error (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)'))) The .pfx certificate is protected by password, but I've tried making .pem file without password, so what I'm doing wrong? I've tested .pfx file with ReadyAPI and after adding certificate everything is working perfectly. -
How to make form bound inside Django UpdateView?
I have a view deriving from UpdateView like this: views.py class MyView(UpdateView): model = MyModel form_class = MyForm def get_object(self, queryset=None): pk = self.kwargs.get('pk') return get_object_or_404(self.model, pk=pk) urls.py url(r'^edit/(?P<pk>\d+)/3/$', views.MyView.as_view(), name='...'), For some reason, my form is unbound. As far as understand, the respective instance to be updated is not passed to the form. Any hints what could the reason be for this ? -
Django Rest Framework gives error: You do not have permission to perform this action
I am following this tutorial to check whether api_key header exist or not. The example seems for authentication purpose and I am unable to figure out how to fix it. When I access the API endpoint I get an error: { "detail": "You do not have permission to perform this action." } permisson.py from rest_framework.permissions import BasePermission class Check_API_KEY_Auth(BasePermission): def has_permission(self, request, view): # API_KEY should be in request headers to authenticate requests api_key_secret = request.META.get('API_KEY') if 'api_key' in request.headers: api_key_secret = request.headers['api_key'] if api_key_secret == 'adnan': print('FOUND') return api_key_secret == 'you' views.py from rest_framework import viewsets from .models import App from .serializers import AppSerializer from rest_framework.decorators import action from rest_framework.response import Response from .permissions import Check_API_KEY_Auth class AppView(viewsets.ModelViewSet): queryset = App.objects.all() permission_classes = (Check_API_KEY_Auth,) serializer_class = AppSerializer def show(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) I do not need user auth, all I ned to check API_KEY exist or not, if yes then query against db in a table and return results. -
How to Change the Django 3.1.3 Admin View
I am currently working on the Django==3.1.3 version but would like to change the interface like that of the django==3.1 Admin view. The current view looks something like this: I would like to remove the red part and keep the remaining part of the page. -
How to make a django rest api which takes two inputs multiplies it and sends the result in database
API which takes two numeric inputs (for example 30 and 50) and then multiplies it and then stores the result (1500) onto Mongo Db. HINT: Use Django Rest Framework and use POST method for the API -
Understanding of `is None` in django (python)
I have a function to create a new page buy getting the POST data from the user: def add_entry(request): if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] if util.get_entry(title) is None: util.save_entry(title, content) return redirect('entry', title) else: return render(request, "encyclopedia/add_entry.html", { "form": form }) return render(request, "encyclopedia/add_entry.html", { "form": AddForm() }) And I have 2 questions: Is there any alternative for "is None" in if util.get_entry(title) is None:? (For example, can I use like if title not in util.get_entry()) What is None is doing here, can't understand its functionality? -
Django rest framework nested serializers partial updating
I have this nested serializer models. class ApplicantSerializer(serializers.ModelSerializer): work_experience = WorkExperienceSerializer(many=True, required=False) class Meta: model = Applicant fields = 'id','auid','completed','work_experience', 'insert_date','last_update' read_only_fields = ('id','insert_date', 'last_update') def create(self, validated_data): print('############################3creating data######################3') print(validated_data) work_experience = validated_data.pop('work_experience') applicant = Applicant.objects.create(**validated_data) for i in range(len(work_experience)): WorkExperience.objects.create( applicant=applicant, **work_experience[i] ) return applicant this is my output data of nested models when I create some of data [ { "id": 46, "auid": "5fd2c6e2-7eaa-472e-b4b1-beb23e3e5072", "completed": false, "work_experience": [ { "id": 36, "from_date": "2020-11-23", "to_date": "2020-11-25", "event_type": "self-employment", "employer_name": null, "employment_type": null, "self_employment_name": null, "position": null, "business_activity": null, "profession": null, "job_title": null, "position_level": null, "roles_and_responsibilities": null, "top_achievement_1": null, "top_achievement_2": null, "top_achievement_3": null, "reason_for_change": null, "reason_for_leaving": null, "company_name": null, "address_line_1": null, "address_line_2": null, "address_line_3": null, "postcode": null, "city": null, "county": null, "country": null, "insert_date": "2020-11-26T20:18:36.277720Z", "last_update": "2020-11-26T20:18:36.277720Z" } ], "insert_date": "2020-11-26T20:18:36.209758Z", "last_update": "2020-11-26T20:18:36.209758Z" } ] I have two models and using ForiegnKey for nested to them. In first time in the ApplicantSerializer Iam just creating part of data and for that data I want to do update as partial update an exist empty field. and data Iam sending is work_experience. 1.so using this serialazer or views how I shall do the the parial update through the Applicant to the … -
Django forms foreign key field read only gives value error during Update form
models.py class MyModel(models.Model): company = models.ForeignKey(Company, db_column="company", default=None, on_delete=models.DO_NOTHING, null=True) forms.py class myform(forms.ModelForm): company = forms.CharField(label="company", widget=forms.TextInput(attrs={'hidden':True}), required=True) admin.py class MymodelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): url = request.get_full_path() if obj: self.form = MyModelUpdateForm else: self.form = MyModelCreateForm ModelForm = super(MyModeladmin, self).get_form(request, obj, **kwargs) class ModelFormMetaClass(ModelForm): def __new__(cls, *args, **kwargs): kwargs['request'] = request return ModelForm(*args, **kwargs) return ModelFormMetaClass ValueError: Cannot assign "'pgEmlMkkkCWnJ1I'": "Mymodel.company" must be a "Company" instance. -
Django Fieldsets Error when customizing the Django Admin
I was trying to customize a model in my Django Application but was getting this error. <class 'core.admin.DemoAdmin'>: (admin.E008) The value of 'fieldsets[0][1]['fields']' must be a list or tuple. models.py class DemoAdmin(admin.ModelAdmin): list_display = ('name', 'city') fieldsets = ( ('standard info', { 'fields': ('name') }), ('Adress info', { 'fields': ('address', ('city', 'zipp')) }), ) admin.site.register(Demo, DemoAdmin) -
Select rows with multiple duplicate field values
I want to select rows in Django which have multiple rows with duplicated values. For example I have a model which looks like this class User: first_name = models.CharField(...) last_name = models.CharField(...) ... and a database looking like this first_name | last_name | ... ---------- | --------- | ... Paul | Adams | ... John | Smith | ... Tom | Mueller | ... John | Smith | ... John | Adams | ... Paul | Adams | ... and I want to get the first_name and last_name values which exist multiple times in the database. The other values must not be equal of the rows. In this example I want to get "John Smith" and "Paul Adams". -
configure nginx to use django and wordpress under sudirectory
I'm trying to set up nginx configuration file to use django app and wordpress blog in a subdirectory, ie. mywebsite.pl/blog The django app is in directory /webapps/mywebsite/django My wordpress blog is in directory /webapps/mywebiste/blog The configuration is as following: upstream mywebsite_app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/webapps/mywebsite/run/gunicorn.sock fail_timeout=0; } server { server_name mywebsite.com www.mywebsite.com; client_max_body_size 4G; access_log /webapps/mywebsite/logs/nginx-access.log; error_log /webapps/mywebsite/logs/nginx-error.log; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://mywebsite_app_server; break; } } location /blog/ { alias /webapps/mywebsite/blog/; index index.php index.html index.htm index.nginx-debian.html; try_files $uri =404; } location ~ \.php$ { alias /webapps/mywebsite/blog/; try_files $uri =404; fastcgi_pass unix:/run/php/php7.2-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem; # managed by Certbot } When I access mywebsite.com/blog url I receive nginx 404 Not Found Error. Would be grateful for your help. -
How can i connect Django amazon lightsail and codecommit?
I would like to create a Django project using Amazon Lightsail, not AWS Elastic beanstalk. However, to my knowledge, I don't know how to integrate Codecommit with Django project like Elastic beanstalk. How can i connect Django amazon lightsail and codecommit? -
Django theme with pip
I have a Django project but with no css, js etc. To respect the dependencies with the pipfile, I can't import the theme by moving the theme files into the project. I need to use the theme with a pip install, I wanted this theme https://pypi.org/project/django-admin-vali/ I follow the documentation, but, I have no change, and I don't have any folder with css, js... Is there a step I forgot? Thank you -
Can't use python-pdfkit and wkhtmltopdf on ubuntu 16.04 LTS
I am having a problem using python-pdfkit and wkhtmltopdf with Ubuntu 16.04 LTS server. Installed python-pdfkit with pip and wkhtmltopdf from this bash script https://github.com/JazzCore/python-pdfkit/blob/master/travis/before-script.sh Locally on mac setup I did it with brew and I get pdfs printed, but on Linux server, I am getting an error: [2020-11-26 09:18:10,698] urllib3.connectionpool WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:847)'),)': /api/1895361/store/ (connectionpool 14509 140240592238336) [2020-11-26 09:23:57,209] django.request ERROR Internal Server Error: /pdf-doc (log 14986 140683311347584) Traceback (most recent call last): File "/home/uptree/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/uptree/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/uptree/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 73, in view return self.dispatch(request, *args, **kwargs) File "/home/uptree/src/uptree/apps/common/mixins.py", line 30, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/uptree/src/uptree/apps/common/mixins.py", line 43, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/uptree/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "/home/uptree/src/uptree/apps/courses/views.py", line 153, in get content = pdfkit.from_string(html, False, options) File "/home/uptree/venv/lib/python3.6/site-packages/pdfkit/api.py", line 72, in from_string return r.to_pdf(output_path) File "/home/uptree/venv/lib/python3.6/site-packages/pdfkit/pdfkit.py", line 156, in to_pdf raise IOError('wkhtmltopdf reported an error:\n' + stderr) OSError: wkhtmltopdf reported an error: Error: Authentication Required Error: Authentication Required Can someone help me solve this, any … -
Django sending GET request instead of POST request [closed]
from django.forms import ModelForm from .models import Order class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' This is forms.py from .forms import OrderForm def createOrder(request): form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # form.save() print('Data is :', request.POST) return redirect('home') else: form = OrderForm() context = {'form': form} return render(request, 'accounts/crud/create.html', context) This is views.py <form action="" type="POST" role="form"> {% csrf_token %} {{ form }} <button type="submit">Create</button> </form> This is create.html I tried many things but still no luck. P.S Django (v) 3.1.3 -
How to setup Django with mysql on Docker?
I am new to DevOps and I am trying to Dockerize my Django-Mysql connection.My Docker file looks like this:- FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /docker_dir WORKDIR /docker_dir ADD . /docker_dir/ RUN pip install -r requirements.txt My docker-compose.yml file looks like this:- version: '3' services: db: image: mysql restart: always command: --default-authentication-plugin=mysql_native_password --mysqlx=0 environment: - MYSQL_HOST=127.0.0.1 - MYSQL_PORT=3306 # cannot change this port to other number - MYSQL_DATABASE=cgi_assignments # name you want for the database - MYSQL_USER="root" # change to whatever username you want - MYSQL_PASSWORD="root" #change to the password you want for user - MYSQL_ROOT_PASSWORD="root" #change to good root password ports: - "3307:3306" volumes: - .setup.sql:/docker-entrypoint-initbd.d/setup.sql web: build: . # command: python manage.py runserver 0.0.0.0:8000 command: python manage.py runserver 0.0.0.0:8000 container_name: docker_dir volumes: - .:/docker_dir ports: - "8000:8000" depends_on: - db links: - db and my database on Django settings file looks like this:- DATABASES = { 'default': { 'NAME': 'cgi_assignments', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'db', 'PORT': 3306, }, } If I use ports:-"3307:3306" it gives me the following error:- django.db.utils.OperationalError: (1130, "Host '172.18.0.3' is not allowed to connect to this MySQL server") and I use ports:-"3306:3306" it gives me the following error:- listen tcp … -
Django admin show fields from json object
I have a user watch history model which store the movie id from the TMDB database. In the django's admin page I want to show the name of that movie and some other information which will be fetch from TMDB's api in a json from. Something like this. { "backdrop_path": "/yzouMVR7udoScaPDIERkYW5a3vI.jpg", "genres": [ { "id": 12, "name": "Adventure" }, { "id": 35, "name": "Comedy" }, { "id": 18, "name": "Drama" }, { "id": 14, "name": "Fantasy" } ], "id": 116745, "imdb_id": "tt0359950", "original_language": "en", "original_title": "The Secret Life of Walter Mitty", "overview": "A timid magazine photo manager who lives life vicariously through daydreams embarks on a true-life adventure when a negative goes missing.", "popularity": 16.09, "poster_path": "/tY6ypjKOOtujhxiSwTmvA4OZ5IE.jpg", "release_date": "2013-12-18", "runtime": 114, "status": "Released", "title": "The Secret Life of Walter Mitty", "vote_average": 7.1, "vote_count": 5793 } and I am currently showing it like this. @admin.register(History) class HistoryAdmin(admin.ModelAdmin): def movie_details(self, obj): tmdb_obj = TMDB() movie_json = tmdb_obj.fetchMovieById(obj.tmdb_id) return movie_json list_display = ['user', 'tmdb_id', 'created_at'] model = History ordering = ("created_at",) fieldsets = ( ("Data", {"fields": ("user", "tmdb_id", "seedr_folder_id")}), ("Important dates", {"fields": ("created_at", "modified_at")}), ("Movie details", {"fields": ("movie_details",)}), ) readonly_fields = ("created_at", "modified_at", "movie_details") Is there a way by which I can take …