Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to map a patch method over an action with detail=False in Django Rest Framework
I am building an API with Django and Django Rest Framework I have the following endpoint: host/products/ pointing to a ModelViewSet, so I have a CRUD working for the specified model. Also, I define an extra action for a nested model called config with the following code: @action(detail=False, methods=['get', 'post']) def config(self, request, *args, **kwargs): if request.method == 'GET': return super().list(request, *args, **kwargs) elif request.method == 'POST': return super().create(request, *args, **kwargs) The created URL is: host/products/config/ At this URL I can create and list objects in the second specified model The problem is that I want to include PATCH and DELETE methods for the nested URL, I mean: host/products/config/detail/ I try to do something like this: @action(detail=True) @config.mapping.patch def update_config(self, request, *args, **kwargs): return super().update(request, *args, **kwargs) But of course, it does not work... How can I map details action over another action in the same viewset? The complete code is the following: class ProductViewSet(viewsets.ModelViewSet): def get_permissions(self): ''' Assign permissions based on action. ''' if self.action in ['suggestions']: permission_classes = [AllowAny] else: permission_classes = [AllowAny] # [IsAdminUser | IsDevUser] return [permission() for permission in permission_classes] def get_queryset(self): ''' Return queryset based on action. ''' if self.action == 'config': # Return … -
Django - Data import from JSON file URL into Database
I'm trying to import data from a json file URL into my Django Database on a weekly basis to keep my Database up to date. That Data is coming from an Importer which was written in GO and which provides me with that JSON File via a link. I still don't have a way to automate this or to make sure how to check if an item got updated or not and then only update those items. But that is not my main issue right now. My main issue is that i'm receiving the following error every time i try to import the data with the manage.py command: File "\data_import\management\commands\import_from_url.py", line 45, in handle self.import_facility_from_file() File "\data_import\management\commands\import_from_url.py", line 21, in import_facility_from_file Name = data_object.get('Name', None) AttributeError: 'str' object has no attribute 'get' This is my Code: import os import json from data_import.models import Facility from django.core.management.base import BaseCommand from datetime import datetime from jsontest.settings import BASE_DIR, STATIC_URL class Command(BaseCommand): def import_facility_from_file(self): print(BASE_DIR) data_folder = os.path.join(BASE_DIR, 'import_data', 'resources') for data_file in os.listdir(data_folder): with open(os.path.join(data_folder, data_file), encoding='utf-8') as data_file: data = json.loads(data_file.read()) for data_object in data: Name = data_object.get('Name', None) IssuedNumber = data_object.get('IssuedNumber', None) release_year = datetime.now() try: Facility, created = Facility.objects.get_or_create( … -
Chained dropdown + label on Django
I'm trying to add a chained dropdown with disabled label, the dropdown options come from column1 of the database and the label would come from the column2, check examples below. How it should be at the form this is my model.py from django.db import models class Produto(models.Model): codigo = models.CharField('Código', max_length=15) descricao = models.CharField('Descrição', max_length=65) this is my views.py from django.shortcuts import render from .models import Produto def index(request): produtos = Produto.objects.all() context = { 'produtos':produtos } return render(request, 'index.html', context) current html to bring options from select <td> <select class="selectpicker form-control form-control-sm" data-live-search="true"> <option selected>--</option> {% for produto in produtos %} <option value='{{produto.codigo}}'>{{produto.codigo}}</option> {% endfor %} </select> </td> The idea is that, everytime I select one option, the disabled input brings the Produto.descricao from the model based on the Produto.codigo Is that possible? Thanks in advanced for the help!! -
Can not make Detailview render data
Hello guys I'm new with Django class based views, I'm learning. What am I doing wrong ? It suppose to render ids but it does not Url.py path('v/<int:pk>', V.as_view(), name='v'), views.py class V(DetailView): model = Empresa template_name = 'detalle.html' .html {%for x in empresa_list%} {{x.NombreEmpresa}} {%endfor%} -
pagination per carousel page with multiple images in Django
class HomePageView(ListView): template_name = "index.html" model = ServiceModel context_object_name = 'services' def customer_listing(self): customers = CustomerModel.objects.filter(is_active=True) paginator = Paginator(customers, 3) return paginator def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['customers_logos'] = CustomerModel.objects.filter(is_active=True) context['paginations'] = self.customer_listing() return context Every carousel page should have 3 images For example if there are 10 images totally, it should be like that 3 3 3 1 in pages Now paginator is working as expected, it's creating 4 carousel pages but I couldn't get images without duplication. <div class="carousel-inner"> {% for pagination in paginations %} {% with forloop.counter0 as i %} <div class="carousel-item {% if i is 0 %}active{% endif %} "> <div class="row"> <div class="col-12 col-md d-flex align-items-center justify-content-center"> <img src="" alt=""> </div> <div class="col-12 col-md d-flex align-items-center justify-content-center"> <img src="" alt=""> </div> <div class="col-12 col-md d-flex align-items-center justify-content-center"> <img src="" alt=""> </div> </div> </div> {% endwith %} {% endfor %} </div> </div> How can I solve this? -
How can I set foreign key from post request in Django
I have this models class Driver(models.Model): first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) created_at = models.DateTimeField(default=NOW) updated_at = models.DateTimeField(default=NOW) def __str__(self): return self.first_name class Vehicle(models.Model): driver_id = models.ForeignKey(Driver,on_delete=SET_NULL,unique=True,null=True, blank=True) make = models.CharField(max_length=150) model = models.CharField(max_length=150) plate_number = models.CharField(max_length=10,validators = [validate_plate_numberLATIN,validate_plate_numberCYRYLLIC], unique=True) created_at = models.DateTimeField(default=NOW) updated_at = models.DateTimeField(default=NOW) def __str__(self): return self.make I try to set foreign key in my post request into Vehicle model @method_decorator(csrf_exempt, name='dispatch') def post(self,request,*args, **kwargs): body = json.loads(request.body.decode("utf-8")) newCar = Vehicle.objects.create(driver_id=body['driver_id'],make=body['make'],model=body['model'],plate_number=body['plate_number']) data = json.loads(serializers.serialize('json',[newCar])) return JsonResponse({'success':data}) And get this error ValueError: Cannot assign "1": "Vehicle.driver_id" must be a "Driver" instance. How to get rid off this error? How I can create an instance of Driver and 'post' an id? -
Only Django request.body contains data (not request.POST)
I am using forms in Django and trying to get the get the data back using request.POST, but this returns an empty dictionary for me: <QueryDict: {}>. When using request.body, however, I get the raw data back. How can I get the data from request.POST as well, because I do not want to work with raw data. The console output of the print statements are put in comments next to them. forms.py class NameForm(forms.Form): first_name = forms.CharField(label='First name:', max_length=100) last_name = forms.CharField(label='Last name:') views.py @csrf_exempt def blank(request): form = NameForm() print(f"request.body: {request.body}") # request.body: b'first_name=Adam&last_name=Smith' print(f"request.POST: {request.POST}") # request.POST: <QueryDict: {}> return render(request, 'blank.html', {'form': form}) blank.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <form action="" method="post"> {{ form }} <input type="submit" value="Submit"> </form> </body> </html> -
how I can get filter parameter in home page but show the result in products list page
This is my code now def product_list(request): item = Product.objects.all() filters = ProductFilter(request.GET, queryset=item) return render(request, 'filter.html', {'filter': filters}) like this: thanks for helping you guys -
Instance belonging in Django Model Inheritance
What is the simpliest way to check does notification belong to BaseNotification or to ExtendedNotification? class User(models.Model): pass class BaseNotification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='notifications') class ExtendedNotification(BaseNotification): pass # usage for notification in user.notifications: # --> here <-- -
Best approach to send requests in Django
I have Django web project based on REST API. My goal is to make views and send requests to my API. In many queries i should pass auth credentials, and as i use default Django auth system i need to pass token and session id. So now queries are done using requests lib like following: #function to create full url for api def create_api_request_url(request, reverse): return 'http://' + request.get_host() + reverse #getting csrftoken and session id, return cookies and header, need for authorization class CookieManager: @staticmethod def get_auth_credentials(request): ses_id = request.session.session_key token = get_token(request) cookies = {'csrftoken': token, 'sessionid': ses_id} headers = {'X-CSRFToken': token} return {'cookies': cookies, 'headers': headers} def some_view(request, pk): ... #create full api url url = create_api_request_url(request, reverse('Shopping Cart API:Cart')) #collect auth credentials from request object credentials = CookieManager.get_auth_credentials(request) #make request using import requests, provided data and auth credentials requests.post(url, {"amount": product_amount, "product": pk}, **credentials) So i need to go into so many steps and use my own custom functions just to send request. Another problem stands behind get requests, for example to collect data from get request i need to be sure that request was correct, firstly i need to check status code but it is … -
I want to add max value to my model field based on the data of another model which is related to it through one to many relationship
Image of django admin panel This are my two models: class English(models.Model): date = models.DateField() topic = models.CharField(max_length=150) totalMarks = models.IntegerField() def __str__(self): return f"{self.id}. {self.topic}" class Meta: verbose_name_plural = "English" class EnglishMarks(models.Model): student = models.ForeignKey(UserField, on_delete=CASCADE) test = models.ForeignKey(English, on_delete=CASCADE, related_name="marks") marks = models.IntegerField(validators=[MaxValueValidator(English.objects.first().totalMarks),MinValueValidator(0)]) I want the marks field of EnglishMarks Model to not exceed the value of totalMarks field of related data of English Model. Note: I am using Inlines to populate EnglishMarks table while creating new data in English table -
Django request.body returning data but not request.POST using forms
I'm using forms in Django and trying to get the get the data back using request.POST, but this returns an empty dictionary for me: <QueryDict: {}>. When using request.body, however, I get the raw data back. How can I get the data from request.POST as well, because I do not want to work with raw data. The console output of the print statements are put in comments next to them. forms.py class NameForm(forms.Form): first_name = forms.CharField(label='First name:', max_length=100) last_name = forms.CharField(label='Last name:') views.py @csrf_exempt def blank(request): form = NameForm() print(f"request.body: {request.body}") # request.body: b'first_name=Adam&last_name=Smith' print(f"request.POST: {request.POST}") # request.POST: <QueryDict: {}> return render(request, 'blank.html', {'form': form}) blank.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <form action="" method="post"> {{ form }} <input type="submit" value="Submit"> </form> </body> </html> -
How to return Json object not stringified in django view from a request out to openai
I have the following code in a Django view in my API, this line in particular returns stringified in my api view course_title = openai.Completion.create( engine="davinci", prompt=course_title_grab, max_tokens=5) class CreateCourseView(APIView): serializer_class = CreateCourseSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): course_title_grab = serializer.data.get('course_title') course_title = openai.Completion.create( engine="davinci", prompt=course_title_grab, max_tokens=5) course_topic = serializer.data.get('course_topic') course_topic_about = serializer.data.get('course_topic_about') course_question = serializer.data.get('course_question') course_answer = serializer.data.get('course_answer') course = Course(course_title=course_title, course_topic=course_topic, course_topic_about=course_topic_about, course_question=course_question, course_answer=course_answer) course.save() return Response(CourseSerializer(course).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) what the object looks like { "id": 5, "code": "BIWJDL", "course_title": "{\n \"choices\": [\n {\n \"finish_reason\": \"length\",\n \"index\": 0,\n \"logprobs\": null,\n \"text\": \" i lived in a new\"\n }\n ],\n \"created\": 1639249703,\n \"id\": \"fdsf\",\n \"model\": \"davinci:2020-05-03\",\n \"object\": \"text_completion\"\n}", "course_topic": "test", "course_topic_about": "test", "course_question": "test", "course_answer": "test", "created_at": "2021-12-11T19:08:23.476059Z", "updated_at": "2021-12-11T19:08:23.476120Z" } Ideally I would like the course_title to output as a nested object so I can easily traverse it in my front end. Any help would be greatly appreciated. -
Djnago JS Reverse - I can't manage to load reverse.js on my page
I have a django up and I am trying to use this potentially very use-full app called "django-js-reverse" to reverse Django Urls on separate javascript files. I installed the app, pip install django-js-reverse I added it to my settings.py, INSTALLED_APPS = [ ... 'django_js_reverse', ... ] I collected static ...but still I can't manage to load it. ./manage.py collectstatic_js_reverse I added this line to load the script in my template <script type="text/javascript" src="{% static 'action/js/project_dashboard.js' %}"></script> However, when I load my page and check the developer console, I can see that the import of the .js failed. The frustrating thing is that I manage to import other .js files that I made so the overall collectstatic process is working. Ideas? -
Django tutorial: ImportError: attempted relative import with no known parent package
I keep running into an error trying to execute the Django Writing your first Django app tutorial. I am running Windows 10, Python 3.9.6, Django 3.2.9, and Vscode 1.63.0. I'm on the step where I create a URLconf file called urls.py in the polls directory. The polls directory is at the same level as the manage.py script and the mysite folder (see folder structure screenshot below). Prior to this, I copy/pasted the code in the views.py, which runs fine. However, the tutorial then says to copy/paste code into the newly-created urls.py, which is again is in the polls directory. The code is: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] The "from django.urls import path" line runs fine, but the "from . import views" line gives me the following error: ImportError: attempted relative import with no known parent package I have watched YouTube tutorials on relative imports and viewed the related stack overflow pages but no amount of tinkering with the code has yielded results. Does anyone know what I'm possibly doing wrong? I feel like since both views.py and urls.py should be able to reference each other, since are in the same … -
Is it possible to find out why Heroku cannot find Django templates?
I have tried everything that I've found before and nothing helped me. I deployed my project on Heroku and I get this error. My templates in other apps begin with {% extends 'base/base.html' %} This template is located in a base templates folder(you can see it below) But I got this error: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') import django_heroku django_heroku.settings(locals()) I don't know why Heroku cannot find my base template. If I remove extends, it'll render an app template, but without styles. But it'll render and it's the most important. -
У меня есть файл JSON, который я хочу прочитать и сделать с помощью python [closed]
У меня есть файл JSON, который я хочу прочитать и сделать с помощью python. Это все в Django. У меня возникли проблемы с получением данных из timetable.json файла в функции python. Файл json - "timetable.json". def timetable(request): def writer(): group_num = [921732] for n in range(0, len(group_num)): url = f'https://journal.bsuir.by/api/v1/studentGroup/schedule?studentGroup={group_num[n]}' print(url) response = requests.get(url) with open('timetable.json', 'w') as file: for piece in response.iter_content(chunk_size=500000): file.write(piece.decode('utf-8')) def reader(filename): with open(filename, 'r', encoding='utf-8') as file: return json.load(file) return render(request, 'studentapp/index.html') -
Django How to pass variable from a view to a form view
I have two models. One is project and another is todo. The todo model has a foreign key that is the related project's id. I have a template that displays the individual project and generates a link to a form to add a todo list. How do I pass the project id to the todo form? I guess I could simply pass the project id in the URL but is that the best way? My current views.py class CompanyProjectsDetailView(DetailView): model = Project id = Project.objects.only('id') template_name = 'company_accounts/project_detail.html' class TodoCreateView(CreateView): model = ProjectTodo template_name = 'company_accounts/add_todo.html' fields = ['title', 'notes', 'status'] -
raise self.model.DoesNotExist( users.models.Profile.DoesNotExist: Profile matching query does not exist
views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm, Profile def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, "Your account has been created! Your ar now able to login.") return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) # p_form = ProfileUpdateForm( # request.POST, request.FILES, instance=request.user.profile) profile = Profile.objects.get(user = request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance = profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, "Your account has been updated!") return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) profile = Profile.objects.get(user = request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance = profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import CustomUser @receiver(post_save, sender=CustomUser) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(email=instance) @receiver(post_save, sender=CustomUser) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.db import models from django.contrib.auth.models import User from PIL import Image from .managers import CustomUserManager from … -
how to pass value from django to payment gateway
i'm trying to pass the email gotten the email field in django in other to pass it to the payment gateway. when i click pay, it redirects me to the modal payment gateway for with an error saying An invalid email passed then when i used inspect, to check the issue, this is what it says flwpbf-inline.js:232 Uncaught TypeError: Cannot set properties of undefined (setting 'opacity') at Object.message_handlers.modalready (flwpbf-inline.js:232) at flwpbf-inline.js:253 message_handlers.modalready @ flwpbf-inline.js:232 (anonymous) @ flwpbf-inline.js:253 the js <script> function makePayment() { const email = document.getElementById('email').value; FlutterwaveCheckout({ public_key: "xxxxxxxxxxxxxxxxxxX", tx_ref: "RX1", amount: '{{cart.get_total_price}}', currency: "USD", country: "NG", payment_options: "", redirect_url: // specified redirect URL "https://callbacks.piedpiper.com/flutterwave.aspx?ismobile=34", meta: { consumer_id: 23, consumer_mac: "92a3-912ba-1192a", }, customer: { email: "{{address.email}}", name: "Flutterwave Developers", }, callback: function (data) { console.log(data); }, onclose: function() { // close modal }, }); } </script> -
Is it possible to filter django Many-To-Many QuerySet fields by checking if they're intersection is not empty?
Doing an exercise about creating a Django service that given a certain job returns the best candidates. Sure it's a Machine Learning problem, and the scoring algorithm here is very simple. Frankly, this is the first time I'm using Django and I'm having some issues to filter out objects from one of the models. This is my model class: from django.db import models class Skill(models.Model): name = models.CharField(max_length=100) def __str__(self) -> str: return f'Skill name: {self.name}' class Candidate(models.Model): title = models.CharField(max_length=100) name = models.CharField(max_length=100, default='') skills = models.ManyToManyField(Skill) def __str__(self) -> str: return f'Name: {self.name}, title: {self.title}' class Job(models.Model): title = models.CharField(max_length=100) skills = models.ManyToManyField(Skill) def __str__(self) -> str: return f'title: {self.title}' Given a job name, I would first like to filter by the skills i.e., go over the given Candidates and filter out the ones that don't have a mutual skill with the given job. In a more mathematical approach - the job_skills_set and the candidate_skills_set intersection is not empty. Something likes this: (I mixed Python syntax) Candidate.objects.filter(len(set.intersection(set(skills), set(job.skills))) > 0) Is there a way I can do that in Django? Tried multiple ways and did not succeed. Thanks in advance! -
TINYMCE doesn't show codes with commands template
I have installed TINYMCE on Django but when I have add (for example) C++ codes in to the code box in out put of the post everything of text OK like(bold H tags etc..) but commands with C++ language shows like the simple text!!! (Without any template or color Separator and ..) help me plz :( -
failed to create LLB definition: docker.io/nginxinc/nginx-unprivileged:1-alphine: not found
Hello I am following this tutorial and i am facing this issue failed to solve with frontend dockerfile.v0: failed to create LLB definition: docker.io/nginxinc/nginx-unprivileged:1-alphine: not found This is my Dockerfile FROM nginxinc/nginx-unprivileged:1-alphine COPY ./default.conf /etc/nginx/conf.d/default.conf COPY ./uwsgi_params /etc/nginx/uwsgi_params USER root RUN mkdir -p /vol/static RUN chmod 755 /vol/static USER nginx -
Catch-22 when trying to create two-way Django relationship
I want to allow my users to be able to have a selection of avatars and (crucially) force every user to have one which will be used as the main one. With that in mind, I've got the following (slightly cut down) models:- class Avatar(models.Model): user = models.ForeignKey(User, related_name="avatars", on_delete=models.CASCADE) image = models.ImageField() class User(AbstractUser): avatar = models.OneToOneField(Avatar, related_name="+", on_delete=models.CASCADE) The problem is, I now can't create a User without first creating an Avatar for that User. But I can't create an Avatar without a User. Having spent ages looking at it, I can't see how I can do this without allowing one of these relationships to be null, which seems wrong somehow. Is there another way to do it? -
OperationalError, Error 111 connecting to 127.0.0.1:6379. Connection refused. After deploying in heroku
I am getting the below error after I deployed my website on heroku. Error 111 connecting to 127.0.0.1:6379. Connection refused. Request Method: POST Request URL: https://website.herokuapp.com/account/register Django Version: 3.2.8 Exception Type: OperationalError Exception Value: Error 111 connecting to 127.0.0.1:6379. Connection refused. Exception Location: /app/.heroku/python/lib/python3.8/site-packages/kombu/connection.py, line 451, in _reraise_as_library_errors Python Executable: /app/.heroku/python/bin/python Python Version: 3.8.12 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python38.zip', '/app/.heroku/python/lib/python3.8', '/app/.heroku/python/lib/python3.8/lib-dynload', '/app/.heroku/python/lib/python3.8/site-packages'] Server time: Sat, 11 Dec 2021 21:17:12 +0530 So basically my website has to send email regarding otp, after registration and also some contract related emails. These email are neccessary to be sent hence can't be avoided. I posted a question earlier here regardig how to minimize the time that sending emails takes so that the user doesn't have to wait the entire time. I was suggested to use asynchronous code for this. So i decided to use celery for this. I followed the youtube video that taught how to use it. Now after I pushed the code in the website I am getting this error. I am beginner andd have no idea how to rectify it. Please suggest me what shoul I do. Below are the details and configurations. settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' …