Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cant add math/science equation in the django-ckeditor outside django admin
Good day everyone! I'm hopping anyone has idea why its not working. Basically I used Django ckeditor as my WYSIWYG for my project. I tried it inside django admin and it is working fine. However, when I used it outside Django admin(in my template) I cant insert any equations. Its seems the textbox is disable. I cant put any value on it. It display only the placeholder equation(quadratic equation) This is the template This is my urls.py This is the models.py and forms.py This is in the base.html This is where I used the editor in my create_activity.html I tried to search for this issue but I found none.I hope anyone can help. -
Anonymous user after successful login
so i am getting AnonymousUser when printing request.user after successful login,de-serializing process is done successfully too. Here is my login view class in views.py file: class LoginView(views.APIView): def post(self, request): data = serializers.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) print(f" HEEERE::: {data}") if self.request.method == 'POST': if data.is_valid(): auth = authenticate( username=data.validated_data['email'], password=data.validated_data['password']) print(f" email check : {data.validated_data['email']}") print(f"auth:: {auth}") if auth is not None: login(request, auth) return redirect("/ticket") else: return HttpResponse("Invalid Credentials") else: return HttpResponse("Data not being validated :O") -
Django settings.py with additional imports odd behaviour and email errors [Errno 111] / clarification on best practice
I've noticed some strange behavior with Django and hope to get a better clarification on why that is. This is in part related to questions like this one (Django Email Error) but goes into more depth wondering about best practices. Look at the following setup: In order to not "overload" my settings.py in my main app I am importing additional sub-settings files. My structure is something along the lines of: main_app -settings.py ... utils_app config -settings_email.py -settings_something_else.py ... utils -email.py ... ... 'email.py' contains the send_email() function and the main_app settings.py file imports as follows: from utils_app.config import settings_email And settings_email.py would look something like: EMAIL_HOST='some-host' EMAIL_PASS=os.environ.get('EMAIL_PASSWORD') EMAIL... ... Originally those variables were in my (default) main_app settings.py file. When that was the case sending email via the Django 'send_mail' function was fine. Once I've moved them out importing as above it stopped working unless I specifically name them when importing like so for example: from utils_app.config.settings_email import EMAIL_HOST, ... In the Django send_mail documentation I couldn't see anything regarding this issue. So the first question is: does Django indeed not know where to look for those variables other than default settings.py and they have to be named there specifically, … -
Django admin: how to display number with fixed length?
This is my model: from django.contrib.humanize.templatetags.humanize import intcomma class Flow(models.Model): amount = models.DecimalField(max_digits=10, decimal_places=2) def df_amount(self): return '{intcomma(abs(self.amount)):>12}' df_amount.admin_order_field = 'amount' df_amount.short_description = 'amount' In admin.py, @admin.register(Flow) class FlowAdmin(admin.ModelAdmin): list_display = ( 'df_amount', ) For amount=2800, print(self.df_amount()) gives $ 2,800.00 but $ 2,800.00 is displayed in the admin panel where the spaces in the middle were truncated to only one space, not as expected. So my question is how to reserve the spaces in the middle of the string in admin panel? Thank you! -
could I get a simple explanation to this code?
class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course, id=pk, owner=request.user) return super().dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course': self.course, 'formset': formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if formset.is_valid(): formset.save() return redirect('manage_course_list') return self.render_to_response({'course': self.course,'formset': formset}) hi guys, I need help understanding this code. I'm working on a project about an e-learning platform so I needed to generate forms for related objects ie a formset for a course module but then this code did the magic but I don't what's going on in the code. I need help and answers with understanding the code. thanks -
Django Throws Permission Denied Error While Trying To Open File
I have a structure Project/ ml_model/ mlp_model scripts/ my_script manage.py open(file_path, 'r') works when I did it inside manage.py but I want to call a function that contains open(file_path, 'r) from my_scripts via a function call. like: manage.py: from my_scripts import Y y = Y() y.do_smth(file_path)` my_script: class Y: def do_smth(self, file_path): f = open(file_path, 'r') //do smth When I do that, f = open line throws "PermissionError: [Errno 13] Permission denied" error. It works fine when I open the file inside manage.py. -
how to use static file on css file with version in django
I need help with a problem i just ran into while working with django static file. so i downloaded this free html template that references it css style as below: <link rel="stylesheet" href="assets/css/vendor.bundle.css?ver=1930"> <link rel="stylesheet" href="{% static 'assets/css/vendor.bundle.css?ver=1930' %}"> ``` meanwhile in django template, i know to reference static files like css and js without the ?ver=1930 as below ``` now my problem is that if i reference as <link rel="stylesheet" href="{% static 'assets/css/vendor.bundle.css?ver=1930' %}"> ``` it doesn't load the css and if i take away the ?ver=1930 and load it like ``` it works but my css get broken. How do i fix this problem plssss. -
How to increase 1 unit when upload a image?
I have a question. I have a user model and it has profile_image and profile_image_quantity fields. Can I increase my value of profile_image_quantity when uploading a image. My user model: class User(AbstractBaseUser): username = models.CharField(max_length=30, verbose_name="Username", help_text="Be carefully while choosing username. If you want change your username you have to pay money") email = models.EmailField(help_text="Your active email adress", verbose_name="Email", unique=True) first_name = models.CharField(max_length=20, verbose_name="First Name", help_text="Your first name") last_name = models.CharField(max_length=20, verbose_name="Last Name", help_text="Your last name") birthday = models.DateField(blank=False, null=True, help_text="Your birthday") date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(verbose_name="Staff", default=False) is_admin = models.BooleanField(verbose_name="Admin", default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified_account = models.BooleanField(default=False) is_verified_email = models.BooleanField(default=False, help_text="Your email still isn't verified") status = models.CharField(choices=status, default='Online', max_length=20, help_text="Your currently status") profile_image_quantity = models.IntegerField(default=0) profile_image = models.ImageField(upload_to=get_profile_image_path, verbose_name="Profile Image", default=default_profile_image_path, blank=True) My get_profile_image_path function: def get_profile_image_path(instance, filename): ext = filename.split('.')[-1] user = User.objects.get(id=instance.id) user.profile_image_quantity += 1 user.save() return f"User/{user.pk}/profile_images/{user.profile_image_count}.{ext}" -
Serializer is not receiving data, (data is empty OrderedDict())
please note that email is basically the username here to not get confused, in serializer.py I have debugged the data, but it seem that user is giving me None serializer.py class LoginSerializer(serializers.Serializer): def validate(self, data): email = data.get("email") print(f" email here : {email}") password = data.get("password") user = authenticate(username=email, password=password) print(f"{user} username serializer ") print(f"this is data : {data}") if user is not None: return data raise serializers.ValidationError("Incorrect Credentials") views.py class LoginView(views.APIView): def post(self, request): data = serializers.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) print(f" HEEERE::: {data}") if self.request.method == 'POST': if data.is_valid(): auth = authenticate( username=data.validated_data['email'].value, password=data.validated_data['password'].value) print(f"auth:: {auth}") if auth is not None: login(request, auth) request.session['user_id'] = auth.id print("test") return redirect("/ticket") else: return HttpResponse("Invalid Credentials") else: return HttpResponse("Data not being validated :O") on frontend side (React): import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { login } from '../actions/auth'; import axios from 'axios'; function Login(){ const [login,setLogin] = useState({ email: '', password:'' }); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ e.preventDefault(); axios.post(' http://127.0.0.1:8000/login/', login) console.log(login); } return ( <div className="container"> <form method='post' onSubmit={handleSubmit}> <h1>Login</h1> <label> Email: <input type='text' name … -
ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0
After upgrading to Django 4.0, I get the following error when running python manage.py run server File "/path/to/myproject/myproject/urls.py", line 16, in from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (/path/to/my/venv/lib/python3.9/site-packages/django/conf/urls/init.py) My urls.py is as follows: from django.conf.urls from myapp.views import home urlpatterns = [ url(r'^$', home, name="home"), url(r'^myapp/', include('myapp.urls'), ] -
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 …