Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Expecting value: line 1 column 1 (char 0) Django form
I am getting error Expecting value: line 1 column 1 (char 0) when trying to add new company with Django form. I could not find duplicate questions on google so i want to ask for any help. My files are below model.py class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300, unique=True, blank=False, null=False) domains = ArrayField(models.CharField(max_length=100)) licence_type = models.CharField(max_length=20, default='Demo') status = models.CharField(max_length=20, default='Passive') sector = models.CharField(max_length=100) security_score = models.IntegerField(default=0) licence_start_date = models.DateTimeField() licence_end_date = models.DateTimeField() insert_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name forms.py class AddCompanyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddCompanyForm, self).__init__(*args, **kwargs) class Meta: model = Company exclude = ['security_score', 'insert_date', 'licence_start_date', 'licence_end_date'] name = forms.CharField( required=True, widget=forms.TextInput( attrs={ "class": "form-control", "id": "name", "placeholder": "Company Name" } )) sector = forms.CharField( required=False, widget=forms.TextInput( attrs={ "class": "form-control", "id": "sector", "placeholder": "Company Sector" } )) domains = forms.CharField( required=True, widget=forms.Textarea( attrs={ "class": "form-control", "id": "domains", "rows": "4", "placehoder":"Separate domains with comma (,)" } )) licence_date = forms.CharField( required=True, widget=forms.TextInput( attrs={ "class": "form-control", "id": "licence_date", } )) licence_type = forms.ChoiceField( choices = [ ('Demo', 'Demo'), ('Basic', 'Basic'), ('Pro', 'Pro'), ('Enterprise', 'Enterprise')], required=True, widget=forms.Select( attrs={ "class":"form-control select2", "id":"licence_type" } )) status = forms.ChoiceField( choices = [ ('Passive', 'Passive'), ('Active', 'Active')], required=True, widget=forms.Select( attrs={ … -
argument of type 'function' is not iterable
def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_users: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this Page') return wrapper_func return decorator . . . . . . -
Heroku buildpack triggered only in staging pipeline, not in prod. Feature? Or misconfiguration?
I have specifically included heroku/python in the build pack section for my two Heroku Django projects but the build pack is triggered only when I deploy by pushing my changes in my main git branch to the staging pipeline, not when I promote the changes to production. Why is that? My builds are not stateful (as Heroku addresses in their doc on design considerations). By that I mean that I can handle all my configuration variables in the Heroku dashboard with one set of variables for staging and a separate set for production. There are no variables that are hard coded. All my configurations are dynamic. The problem I see is that when I update my requirements.txt with newer versions of Python modules/libraries, how do I instruct Heroku to trigger the build back in prod to rebuild the slug? Have I misconfigured my Heroku production pipeline? Or is it somehow unnecessary to rebuild slugs in prod but only in staging? When I typed the title for my question here, Stack Overflow recommended the following questions and answers from other users which didn't seem to answer my question: Maintaining staging+prod environments from single repo, 2 remotes with revel buildpack on heroku … -
Secondary Domain Static Files in Cpanel with a django application
I am deploying a django app in cpanel this application isnt on the main domain it is on a secondary one i tried copyaing the static files into the domain name inside the public html but the webapp doesnt read them all styles and js files are not loading on the front-end i applied collect static before deploying from github and copied the static file into a file of the secondary domain name in the file manager at first but didnt work, and tried copaying it into the public html but didnt work too i think there is a problem with the method i am following in this link https://parmarnaitik0909.medium.com/deploying-hosting-a-django-website-on-cpanel-with-git-version-control-6e8dce70a316 -
Search form in django using function
I'm trying to create a search form in view.py using a function , I have Course model which has a name attribute , a "Course matching query does not exist " error occurs when I click on the search button , here's my view : view.py here's where I'm keeping my form : form my app namespace is "uni" and the name of the search url view is "search" where is the error ? -
Uploading Data From Django SQL Database Into Google Sheets
I have an offline django webapp that works on localhost. The database contains daily attendance sheet, that needs to be viewed by teachers online through google sheets. How to transfer the data from Django SQL into Google Sheets? Any help would be appreciated.. -
Digitalocean and Django droplet very slow after upgrade
How best can I solve the issue of the server being very slow, I upgraded my droplet from : Basic - Premium AMD Shared CPU 1 vCPU 1 GB 25 GB 1 TB to this : Basic - Premium AMD Shared CPU 2 vCPUs 4 GB 50 GB 4 TB My endpoints are all cached, but the issue is still there. But the site is still very slow, what other things I should consider for the better performance ? -
Reusing JSON response after Fetch request
I try to use a JSON response from server and print for the user error message. I receive JSON response successfully and alert function works as I expect, but what I actually need is to insert element to the DOM, but when fetch.then construction ends I'm being redirected to the root '/' and Django server wipes out the template that I try to work with. On Django side I use JsonRequest function with status code=400. What I'm doing wrong? Please give me a clue. My JS code looks like this: document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); // By default, load the inbox load_mailbox('inbox'); }); function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; // Send email document.querySelector("#compose-form").onsubmit = function() { let composeView = document.querySelector("#emails-view"); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: document.querySelector("#compose-recipients").value, subject: document.querySelector("#compose-subject").value, body: document.querySelector("#compose-body").value }) }) .then(response => response.json()) .then(result => { let p = `<p>${result.error}</p>`; composeView.append(p); alert(result.error); }) } } function load_mailbox(mailbox) { // Show the mailbox … -
Django POST request data from Javascript fetch is displayed, but i get an error "Expecting value: line 1 column 1 (char 0)"
I am trying to send data with Javascript fetch and I keep getting error: "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)". inside index.js: fetch('save_user_post/', { method: 'POST', credentials: 'same-origin', headers:{ 'Accept': 'application/json', 'X-CSRFToken': user_post_form_csrf.value, }, body: JSON.stringify({ 'input_user_post_value': input_user_post.value, }) }) .then(response => { return response.json() }) .then(user_post_save_result => { console.log(user_post_save_result ) }) and than in views.py: def save_user_post(request): if request.method != "POST": return JsonResponse({"error": "no POST method"}, status=400) if request.user.is_authenticated: print(request.body) #here I checked if I can receive this data data_of_post = json.loads(request.body) input_user_post_value = data_of_post.get('input_user_post_value', '') print(f'input_user_post_value is {input_user_post_value}') #here I checked if I can get exactly this value post_save_result = {'post_saved_or_not': 'saved'} return JsonResponse(description_save_result) Although both print() commands display valid fetch data, the error that relates to the line data_of_post = json.loads (request.body) is also displayed. How to get rid of this error? -
How to dynamically create upload path for media files django-ckeditor?
I am using RichTextUploadingField in my model. I have set upload path to CKEDITOR_UPLOAD_PATH = "uploads/" I use this field when I am on path: path("<slug:p_slug>/<slug:m_slug>/<slug:slug>/edit_feature/", views.EditFeature.as_view(), name="edit_feature"), I want the path of the file looks like this, after adding a file:<slug:p_slug>/<slug:m_slug>/<slug:slug>/<file_name>/ How to achieve this? -
Generate python script on backend and pass it to user
I'm new to Django, and I have a question. How can I pass a JSON, made in the frontend by the user interacting with the UI in the frontend, to Django, run a python script that takes that JSON, converts it into another python script with the instructions that the user gave, and then downloading that script in the user's page? I already have the script that converts the JSON to the python file, but the part I don't know about is how I can connect the JSON that the user gave to the python script that converts it and then gives the result back. -
Django Rest API from Database
I have 2 APIs from my existing project. Where One provides the latest blog posts and another one provides sorting details. The 2nd API (sorting) gives blog posts ID and an ordering number, which should be in the 1st,2nd,3rd...n position. If I filter in the first API with that given ID I can get the blog post details. How can I create a Django REST API from Database? or an API merging from that 2 APIs? Any tutorial or reference which might help me? Frist API Response: { "count": 74, "next": "https://cms.example.com/api/v2/stories/?page=2", "previous": null, "results": [ { "id": 111, "meta": { "type": "blog.CreateStory", "seo_title": "", "search_description": "", "first_published_at": "2022-10-09T07:29:17.029746Z" }, "title": "A Test Blog Post" }, { "id": 105, "meta": { "type": "blog.CreateStory", "seo_title": "", "search_description": "", "first_published_at": "2022-10-08T04:45:32.165072Z" }, "title": "Blog Story 2" }, 2nd API Response [ { "featured_item": 1, "sort_order": 0, "featured_page": 105 }, { "featured_item": 1, "sort_order": 1, "featured_page": 90 }, Here I want to create another API that will provide more details about sorting for example it will sort like this https://cms.example.com/api/v2/stories/105 and catch Title, Image & Excerpt and If there is no data from Sorting details it will show the first API's response by … -
Django database migrations are gives no "No migrations to apply." error
Hi I am having issues trying to migrate my django database. I have a database that definitely cant be cleared/removed, which is what most solutions recommend. I have tried all the following command-sets: python manage.py makemigrations python manage.py migrate --run-syncdb python manage.py makemigrations django_project python manage.py migrate django_project python manage.py migrate python manage.py makemigrations && python manage.py migrate python manage.py makemigrations django_project python manage.py migrate --fake-initial python manage.py migrate I cleared the migrations folder everytime. Every set resulted in the same response: 08:59 ~/GluoApi $ python manage.py makemigrations && python manage.py migrate Migrations for 'django_project': django_project/migrations/0001_initial.py - Create model Blacklist - Create model Like - Create model Post - Create model PostReaction - Create model Profile - Create model Token - Create model ReportUser - Create model ReportPost - Add field reports to profile - Add field requests to profile - Add field user to profile - Create model PostReactionReport - Create model PostReactionLike - Add field likes to postreaction - Add field post to postreaction - Add field poster to postreaction - Add field reports to postreaction - Add field likes to post - Add field poster to post - Add field reports to post - Add field post … -
Django TemplateDoesNotExist - can not render the template
I am new to django and I am using version 4.1.2. I have created an app with the following structure I have configured the app ( 'home') template in the primary setting file like the following. but still, I am getting the error TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR/'home', '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', ], }, }, ] here is my view code from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request, ' home/welcome.html' , {}) -
In Django, How i can search robotics course by entering only robot or robo?
please help me to solve this. i am trying to search object from url by it's keyword [api.py][1] [api.py][2] [result][3] [error][4] [1]: https://i.stack.imgur.com/v2aHS.png [2]: https://i.stack.imgur.com/oyc44.png [3]: https://i.stack.imgur.com/ZI3yJ.png [4]: https://i.stack.imgur.com/8amG9.png -
How to make boolean editable as checkboxes in djano-admin change_list panel?
One of my model as a boolean field (name of the field = deactivated). This field is displayed with "green checked" or "red unchecked" icon in tha change list admin panel. I would like to have this boolean field editable with checkboxes in the change list panel I've read documentation and google my question but could not find solution... the best I found is define an action that make selected row checked/unchecked... -
Accessing Uploaded files in Django
I am trying to display the urls of Multiple files I uploaded related to the post model. My settings.py is well set up and the files gets uploaded to the target directory. How can I access the urls of these files and print them on the post details page? This is because I want an individual to be able to download these files. So far I have tried the following. # models.py class Post(RandomIDModel): student = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(null=True, blank=False, max_length=50) deadline = models.DateTimeField(null=True, blank=False) description = models.TextField(null=True, blank=False) pages = models.IntegerField( validators=[MinValueValidator(1)], default=1,null=True, blank=False) status = models.CharField(max_length=10, choices=status_choices, default="pending") price = models.DecimalField(max_digits=10,decimal_places=2, default=0.00) reference_style = models.CharField( max_length=10, choices=reference_styles, default="Apa" ) number_of_references = models.IntegerField( validators=[MinValueValidator(1)], default=1,null=True, blank=False ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.subject) # New form multiple file upload class. class PostAttachment(models.Model): attachment = models.FileField(upload_to="atlogin", blank=True, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="attachment") #views.py @login_required(login_url="/account_login") # @permission_required("main.add_post", login_url="/account_login", raise_exception=True) def create_post(request): if request.method == "POST": form = PostForm(request.POST) attachment_form = PostAttachmentForm(request.POST, request.FILES) attachments = request.FILES.getlist("attachment") if form.is_valid() and attachment_form.is_valid(): post = form.save(commit=False) post.student = request.user post.save() for f in attachments: post_attachment = PostAttachment(attachment=f, post=post) post_attachment.save() messages.success(request, "Upload Succeessful!") return redirect("/dashboard") else: form = PostForm() … -
css file not worked in VScod in Django project
I have a Django project , and I want to have a css file in templates folder . but for examples when I write 'myfirst.css' , The VScode not worked. enter image description here -
How to filter choices in django admin?
I want to create two combo boxes in my Django admin. First one is brand of object and second one is the model of that brand , when i select brand in first combo box, i want second one to get update. -
distinction about txt file and pdf file
I have a django application and a upload method. And A textarea where the content of the file will be returned. So if there is a text file uploaded. Then in the textarea the content of the textfile will be visible. I try it now also with a image in a pdf file. And I try it with a console app. And that works. Tha text in the pdf file will be extracted. But I try it now with the general upload method. And then I get this errror: TypeError at / image must be a wand.image.Image instance, not <UploadFile: UploadFile object (45)> Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.1 Exception Type: TypeError Exception Value: image must be a wand.image.Image instance, not <UploadFile: UploadFile object (45)> Exception Location: C:\Python310\lib\site-packages\wand\image.py, line 9310, in __init__ Raised during: main.views.ReadingFile Python Executable: C:\Python310\python.exe Python Version: 3.10.6 So this is the complete method: from django.shortcuts import render from django.views import View from django.http import HttpResponseRedirect from .forms import ProfileForm from .models import UploadFile from .textFromImages import TextFromImage from wand.image import Image as wi from PIL import Image import pytesseract from django.conf import settings import io import os class ReadingFile(View): def get(self, request): form … -
How to fix error when sending mail with django in docker container? (Cannot assign requested address)
I'm getting an error when sending a letter both in Celery, as in the shell itself. Without the docker itself, there is no such error on the local computer, but there is on the server. Error: send_mail('test', 'test msg', 'volkodav2312@bk.ru', ['volkodav2312@inbox.ru']) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.10/site-packages/django/core/mail/__init__.py", line 87, in send_mail return mail.send() File "/usr/local/lib/python3.10/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/usr/local/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 80, in open self.connection = self.connection_class( File "/usr/local/lib/python3.10/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python3.10/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/local/lib/python3.10/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/local/lib/python3.10/socket.py", line 845, in create_connection raise err File "/usr/local/lib/python3.10/socket.py", line 833, in create_connection sock.connect(sa) OSError: [Errno 99] Cannot assign requested address I looked through the other answers and didn't find anything helpful. I have a password configured, this error occurs in the docker. -
How to add template directory in django?
I'm getting TemplateDoesNotExist at /task/ error. This is my folder structure for project. This is my taskmate/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('task/',include('todolist_app.urls')), path('todolist/',include('todolist_app.urls')), ] This is my todolist_app/urls.py: from django.urls import path #from todolist_app import views from . import views urlpatterns = [ path('', views.todolist, name='todolist'), ] This is my todolist_app/views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def todolist(request): return render(request, 'todolist.html',{}) This is my settings.py(important components) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(os.path.join(os.path.dirname(os.path.dirname(__file__)),'todolist_app/templates').replace('\\','/'))],#'DIRS': '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', ], }, }, ] I'm highly suspicious that the issue I'm getting is due to "DIRS" of template. I have tried couple of different things there, but none seem to have worked. These are what I've tried there: 'DIRS': [os.path.join(BASE_DIR,'templates')], 'DIRS': [os.path.join(os.path.dirname(__file__),'templates').replace('\\','/')],#'DIRS': 'DIRS': [(os.path.join(os.path.dirname(os.path.dirname(__file__)),'todolist_app/templates').replace('\\','/'))],#'DIRS': I've also added "todolist_app" to installed apps. -
Can CreateView show additional rows for every row in a certain FK?
I'm sorry I do not know the correct terminology to describe what I am trying to accomplish briefly, so I am hoping you can read my explanation below. I have even added an image showing the results I want to accomplish. Background + Explanation I'm refactoring a language learning application in preparation to make it Open Source. It focuses on writing and composition. The way it works is that a user can create a Post and that post's text will automatically split into individual sentences via NLP where then each individual sentence will get added to another table called PostRow. In a separate view, a user on the platform is able to make corrections to this post. Then all of the individual corrections get added to the CorrectedRows table. When a user visits the MakeCorrection view to correct a post then the form would essentially do this: Filter all of the PostRows for the Post in question For every filtered PostRow row show the CorrectedRow form too In other words, if the Post's text has 6 sentences, then the MakeCorrection view should show 6 CorrectedRows. Tables class PostRow(SoftDeleteModel, TimeStampedModel): ... post = models.ForeignKey(Post, on_delete=models.CASCADE) sentence = models.TextField() class CorrectedRows(SoftDeleteModel, TimeStampedModel): … -
Django model property field calculated with field from another child model
class BusinessFunction(models.Model): name = models.CharField(max_length=200) priority_rating = models.PositiveIntegerField(null=True, blank=True) location = models.CharField(max_length=200) network_service_related = models.CharField(max_length=200) class Meta: ordering = ['name'] def __str__(self): return self.name class CriticalImpact(models.Model): businessfunction = models.ForeignKey(BusinessFunction, on_delete=models.CASCADE) priority = models.PositiveSmallIntegerField(null=True, blank=True) financial = models.PositiveSmallIntegerField(null=True, blank=True) legal = models.PositiveSmallIntegerField(null=True, blank=True) score = models.PositiveSmallIntegerField(null=True, blank=True) percentage = models.PositiveIntegerField(null=True, blank=True) class Meta: ordering = ['businessfunction'] class TimeImpact(models.Model): businessfunction = models.ForeignKey(BusinessFunction, on_delete=models.CASCADE) impact_score_financial = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) impact_score_asset = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) final_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class Meta: ordering = ['businessfunction'] @property def final_rating(self): final_rating = (self.final_score + ????????)/2 return final_rating I have code as above and would like to add property of final rating using calculation from own table(TimeImpact) field final_score and field from CriticalImpact field ie percentage. The problem is how i can get the field percentage from CriticalImpact table which is the child of business function table. I've searched before but most of the answer is calculated field coming from field in own table and parent table, not with another child table. Appreciate any helps. Thanks -
Could not resolve URL for hyperlinked relationship using view name "user-detail" (from Rest Framework Quickstart)
I am following the tutorial for rest framework. I have no idea this part of the code ain't working when it works for the apigroups. Please tell me what is the underlying issue. Thank you. ERROR: ImproperlyConfigured at /polls/users/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Serializers: from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url', 'name'] #Views from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from .serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited """ queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] #Urls from django.urls import path, include from . import views from rest_framework import routers # for rest framework router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('', include(router.urls)), …