Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Pagiantor on a search function
I tried to add a Paginator of 5 posts to the current function but I always have developed with the ListView functions, in which is way easier to implement a pagiantor. Any suggestion? def search(request): query = request.GET.get("q", None) qs = DeathAd.objects.all() if query is not None: qs = qs.annotate( full_name = Concat('nome', Value(' '), 'cognome'), full_cognome = Concat('cognome', Value(' '), 'nome') ).filter( Q(nome__icontains=query) | Q(cognome__icontains=query) | Q(full_name__icontains=query) | Q(full_cognome__icontains=query) ) context = { "object_list": qs, } template = "search.html" return render(request, template, context) -
How do I use placeholders with Class-based password reset views?
There are four such view : PasswordResetView sends the mail # - PasswordResetDoneView shows a success message for the above # - PasswordResetConfirmView checks the link the user clicked and # prompts for a new password # - PasswordResetCompleteView shows a success message for the above. I want to use placeholders for them but there doesn't seem to be an option. Overwriting the class seems kinda overkill. -
Django - login with facebook fails
I'm currently building a website and i'm trying to implement Login with Facebook functionality to users. I have configured social-auth-app-django the following way: seetings.py file: INSTALLED_APPS = [ 'social_django', TEMPLATES = [ 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', AUTHENTICATION_BACKENDS = [ 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_FACEBOOK_KEY = '******************' SOCIAL_AUTH_FACEBOOK_SECRET = '***************************' Template login: <div class="col-lg"> <a href="{% url 'social:begin' 'facebook' %}"><button type="submit" class="btn btn-block color-white bgc-fb mb0"<i class="fa fa-facebook float-left mt5"></i> Facebook</button></a> </div> I have uploaded project to Heroku, when i click Facebook button i get error Username OR password is incorrect from views.py. def loginPage(request): if request.user.is_authenticated: return redirect('index') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') remember_me = request.POST.get('remember_me') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) if not remember_me: request.session.set_expiry(0) return redirect('index') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'members/login.html', context) However when i inspect the page and click on the link <a href="/members/social-auth/login/facebook/"> inside the template it works meaning Facebook requests to use my Facebook profile. I suppose the problem is on my view but how can i configure it to not have this problem? Thank you for your effort! -
Creating model instance in django
please help me with the Django question. I am new here, have searched Stackoverflow and documentation, but still can't understand how to solve the following problem. The general task: there is a list of the events which are displayed in a table view, the user clicks on the event and gets redirected to a single event page, which displays extra information about an event. There is a button on this template that should give functionality to record some data of the Event in the user-selected events list. And I really don't get how to pass the event data into the form to create the user_event... of maybe I chose the wrong way to create the instance of the model? Models.py class Event(models.Model): LANGUAGE_CHOICES = [ ('EN', 'English'), ('IT', 'Italian'), ('FR', 'French'), ('DE', 'German'), ('RU', 'Russian'), ] STATUS_CHOICES = [('draft', 'Draft'), ('confirmed', 'Confirmed'), ] FORMAT_CHOICES = [('live', 'Live'), ('online', 'Online'), ] TOPIC_CHOICES = [('cataract', 'Cataract'), ('vitreo', 'Vitreoretinal'), ('optometry', 'Optometry'), ('multi', 'Multidisciplinary'), ('plastic', 'Plastic and Reconstructive surgery'), ('onco', 'Ocular oncology'), ('glaucoma', 'Glaucoma'), ('pediatrics', 'Pediatrics'), ] title = models.CharField( max_length=250, verbose_name='Event', db_index=True, default="Event") slug = models.SlugField(max_length=250, unique_for_date='publish') kol = models.ManyToManyField( Kol, verbose_name='Presenter', db_index=True, blank=True) body = models.TextField(verbose_name='Description', blank=True) publish = models.DateTimeField(default=timezone.now) created = … -
My site shows menus based on a users privs. I have a function that returns the privs as a dictionary as below:
i need to show my sidebar dynamically by using 6 privilages which giving by admin to users. this is my views.py which i set in my django function.i used checkbox to select 6 privilages here.privilages are ecom,service,career,course,blog.offline def SIDEMENU(request): # ii=request.session['sid'] a=db_coslogin.objects.all().filter(ecom=1,status=2) b=db_coslogin.objects.all().filter(blog=1,status=2) c=db_coslogin.objects.all().filter(servive=1,status=2) d=db_coslogin.objects.all().filter(offline=1,status=2) e=db_coslogin.objects.all().filter(career=1,status=2) f=db_coslogin.objects.all().filter(course=1,status=2) return render(request, "sidebar.html",{'ecomr':a,'blog':b,'servive':c,'offline':d,'career':e,'course':f}) -
How do I display my products by certain category
So I am making an ecom site, and I am using Django. I am quite new and I am using a tutorial but have stepped off touch with it as I want to have 2 categories and maybe more on my website in the future. I want to be able to display them by their category, and I asked for help around my discord server and some people have tried to help and it does go through all my products however I have an if statement and that if statement gets ignored So can anyone show me a way to display products with their category set as Specials only? Or hatbox only? Store.Html {% extends 'store/main.html' %} {% load static %} {% block content %} <title>Store</title> <h2>Our Stylish Hat Boxes - from the smallest to the largest.</h2> <div class="row" style="padding-bottom: 5%;"> {% if products.category == Hatbox %} {% for product in products %} <div class="col-sm-4-fluid" style="margin-right: 5%;"> <div class="card" style="width:300px;"> <img class="card-img-top" src="{{product.imageURL}}" alt="Card image"> <div class="card-body"> <h5 style="display: inline-block; float:right;"><strong> £ {{product.price|floatformat:2}}</strong></h5> <h6 class="card-title">{{product.name}}</h6> <a href="#" class="btn btn-primary">View</a> </div> </div> </div> {% endfor %} {% endif %} </div> <h2>Something Special...</h2> <div class="row" style="padding-bottom: 5%;"> {% for product in products … -
The easiest way for Latin -> Cyrilic transliteration in Django
I need to allow user to freely choose whether he/she wants to display Latin or Cyrilic version of website. So, my question is - what is the easiest way to transliterate every single character in a Django web site? I do not need translation nor localization, just simple character replacement, let's say "Bravo" should be rendered as "Браво" Issue is that this need to be done for each static html page and data in database as well. Is there some package for python or django that makes this possible like in Wordpress? Ideally, this should be done somehow in Template (Model -> View -> Template) context. Duplicating templates (and adding new urls for each) would solve problem for static html pages but it would be time consuming and I want to avoid it, and besides it would left text from database unsolved. -
Can I use Mysql for building a video streaming site like Youtube?
I want to build a video streaming site like youtube. and I'll be using Django to build the site. So i was wondering which DB will be more suited for streaming videos? Is Mysql and Amazon S3 a good choice? -
Im trying to deploy my django/python app to heroku but my status is crashing
when i bring up the logs for heroku i get this message 2020-11-26T07:32:19.145443+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=peaceful-plains-05024.herokuapp.com request_id=7a6628ea-1d1d-49fa-bade-209878fd54f4 fwd="73.229.185.56" dyno= connect= service= status=503 bytes= protocol=https if i try > heroku ps I get this message: (ll_env) C:\Users\kenne\learning_log>heroku ps Free dyno hours quota remaining this month: 550h 0m (100%) Free dyno usage for this app: 0h 0m (0%) For more information on dyno sleeping and how to upgrade, see: https://devcenter.heroku.com/articles/dyno-sleeping === web (Free): gunicorn learning_log.wsgi --log-file - (1) web.1: crashed 2020/11/26 00:28:42 -0700 (~ 8m ago)