Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django web app css not being refreshed in browser
I'm having some issue with a django app and it's CSS file refreshing. Basically I can see that the changes I make in my file are identified and copied in the root folder of my website, however when I open up the web browser that change is not being displayed at all: I am using Firefox as a browser however this issue happens also on Chromium browser -
How do I send a file to the Django server via ajax?
I can't figure out for more than a week, I need to send an image to the Django server, but I get the error: 415 (Unsupported Media Type) If I change ContentType to multipart/form-data, I get: 400 (Bad Request) is sent via postman normally, what could be the error?: ( Script updateUser() { $.ajax({ url: "http://localhost:8002/api/update_profile/" + this.username + "/", data: { first_name: this.first_name, username: this.login, last_name: this.last_name, email: this.email, photo: this.image }, DataServiceVersion: 2.0, processData: false, contentType: false, // contentType:"multipart/form-data", type: "PUT", success: function(data) { location.reload() }, error: function(response) { console.log(this.data) let err = response.responseJSON; for (let key in err) { alert(key, err[key].toString()); } } }); }, -
Want to convert proper JSON request in AXIOS ReactJs to send to django
My payload is in string form as below: payload= "[{"message":"message text", "id":1, "code":0}, {"message":"message text", "id":2, "code":1}, {"message":"message text", "id":3, "code":0}]" I am getting the pay load from query string. ex = https:\xyz.com\endpoint?payload=[{"message":"message text", "id":1, "code":0}, {"message":"message text", "id":2, "code":1}, {"message":"message text", "id":3, "code":0}] JSON.stringify(payload) does not help here as it is a string and JSON.parse(payload) throws error. the axios request is as below: try { const response = await axiosInstance.post('/postenpoint/', payload, { headers: authHeader }); return response; } catch (error) { console.log(error); }; is there any inbuilt function or effective way in JS other than string parsing in such case? The problem is at backend which is developed using django gets the response as {'[{"message":"message text", "id":1, "code":0}, {"message":"message text", "id":2, "code":1}, {"message":"message text", "id":3, "code":0}]': ''} This must go as proper json form instead it' goin as a key only. -
pip library body_measurements (python)
I want to get the body measurements through an image using pip library body_measurements. Is there any material related to this? I have seen openCV2 library for this thing but that does not my requirement. -
Fetching specific data from SQLite DB to django forms
how do I fetch like specific data I want to a django form. I know how to fetch the entire database to a table by using loops. But I want to fetch specific data according to what user select. At the back of my mind, i know the flow. Eg. Step 1, user choose which data they want to look. Step 2, goes to the table to find the specific data user wants. Step 3: Display it in a html page. I have this table in my web and when user lets say click the edit button for 1st row, it goes to a new html with all its details listed in a table. Eventually i want it to display a form with all the data (2 tables) stored Html: {% extends "interface/base.html" %} {% block footer_scripts %} {{ block.super }} <script> // additional javascript </script> {% endblock footer_scripts %} {% block content %} <div class="content-page"> <div class="content"> <!-- start page title --> <div class="row"> <div class="col-12"> <div class="page-title-box"> <!--<div class="page-title-right"> <ol class="breadcrumb m-0"> <li class="breadcrumb-item"><a href="javascript: void(0);">Hyper</a></li> <li class="breadcrumb-item"><a href="javascript: void(0);">eCommerce</a></li> <li class="breadcrumb-item active">Devices</li> </ol> </div> --> <h4 class="page-title">{{hostname}}</h4> </div> </div> </div> <!-- end page title --> <div class="row"> … -
Django multiple radio input from HTML form with same name
I am having a problem with Django forms. I am currently using the request.POST to validate the POST within views. I want to send inputed-data(radio type) from my template with the same name. In my template.py: <form method="post" action="{% url 'app:AnsSubmission' %}"> {% csrf_token %} {% for i in Exam %} <div class="form-group col-xl-12"> <label>{{ i.question }}</label> <div class="radio"> <label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="True" required>True</label> </div> <div class="radio"> <label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="False" required>False</label> </div> </div> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> And willing to fetch these data in views.py like: givenAns_list = request.POST.getlist('givenAns') for i in givenAns_list: this_givenAns = givenAns_list[i] But the problem here is this radio type input field doesn't take value for the same name(not as a list I wish). If I select answer of 2nd question, the 1st one's selection is unselected. Please suggest how can I fix this? -
Django Jazzmin add button disappeared after adding mptt admin
I'm using jazzmin for django admin and mptt. After adding mptt to admin, in jazzmin theme add button disappeared. I'm using latest versions of all libraries class CustomMPTTModelAdmin(MPTTModelAdmin): # specify pixel amount for this ModelAdmin only: mptt_level_indent = 30 admin.site.register(Menu, CustomMPTTModelAdmin) Here you can see the admin where button disappeared When I disable jazzmin or remove Mptt add button returns back on place INSTALLED_APPS = [ # 'jazzmin', ..... ] Here you can button returns back There is also issue was opened on github https://github.com/farridav/django-jazzmin/issues/126 but I could not find solution for this problem -
cannot activate virtualenv via python terminal
I create a virtual environment named djangoenv. I can run it with using cmd but I cannot in python terminal this is cmd picture and this is python terminal picture how can I run this server in python terminal? -
Problems in debugging Django projects in Pycharm
I'm having a problem debugging Django projects in Pycharm (2021 CE) and following is my config I can run (by clicking the run button) the project with no problem; Server runs fine and serves traffic. But I have problems debugging it. This the command generated by Pycharm /home/cheng/Environments/proj1_env/bin/python3.8 /snap/pycharm-community/248/plugins/python-ce/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 34965 --file /home/cheng/code/test_web/manage.py runserver The error message is Connected to pydev debugger (build 212.4746.96) /home/cheng/Environments/proj1_env/bin/python3.8: can't find '__main__' module in '' Need some help. Thanks! -
Please help me on following error with Django and PostgreSQL with docker
My Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /django COPY requirements.txt requirements.txt RUN pip install -r requirements.txt My docker-compose.yml version: '3' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db web: build: . volumes: - .:/django ports: - "8000:8000" links: - db:db depends_on: - db image: web:django container_name: django_container command: python manage.py runserver 0.0.0.0:8000 And I am getting error like django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution -
Django REST with jwt + regular admin panel
I've setup a basic django app using scaffolding which creates all those nice admin panels for free. I want to expose a REST api so I've followed this tutorial to get it running and add JWT authentication through simplejwt. I have tested my rest auth endpoints, gotten a token and used that token to consume a secured rest endpoint. The problem is -- as soon as I enable this auth scheme, the admin panel stops working. I can't login at all. Which I guess it makes sense considering I've changed the auth paradigm, but it kinda defeats the purpose of the scaffolding to lose all those free admin panels. Is it possible to combine both jwt authentication for my REST services while keeping regular authentication scheme for my admin panel? I want to do a public frontend through REST but keeping my backoffice within the same deployment as the backedn itself. -
I send any email with website that also show me on my email's sent box
Hello I have 1 question that i want to integrate my outlook with my django website that means if i send any email with website that also show me on my email's sent box. Can anyone help me to do this. -
How to set default for the foreignkey when using a form?
Scenario: I want to make an app that has servers(500+) as a model and another model that has posts as a foreign key to the server model to log what we did on each server.So as I said I have two models the server and the posts. models.py from django.db import models from django.db.models.deletion import CASCADE # Create your models here. class Cluster(models.Model): STATUS = ( ('N','Not Started'), ('I','In Porgress'), ('C','Closed'), ) TYPE = ( ('R','RDC'), ('C','CDC'), ('G','GC'), ) cluster_code = models.CharField(max_length=250) cluster_status = models.CharField(max_length=20,choices=STATUS) cluster_type = models.CharField(max_length=20,choices=TYPE) jira_link = models.CharField(max_length=250) def __str__(self): return self.cluster_code class Post(models.Model): name = models.CharField(max_length=250) time = models.CharField(max_length=20) cluster_log = models.TextField(null=True,blank=True) cluster_code = models.ForeignKey(Cluster,on_delete=CASCADE) def __str__(self): return str(self.cluster_code) + " " + str(self.time) class Meta: ordering = ['-id'] I used ModelForms for the posts part of the app when making a new post. Ideally I want to hide the 'cluster_code' field on the form. How do I set it so that the 'cluster_code' is automatically set to the server I am editing the post for. forms.py from django.forms import ModelForm from django import forms from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ['name','time','cluster_log','cluster_code'] views.py def CreateNewPost(request,cluster_code): form = PostForm() cluster_code … -
how to set update url page into jquery - django
i'm trying to go update page . my models.py class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) my views.py @login_required def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for i in lists: item = { 'id':i.id, 'admin':i.admin.username, 'main_type':i.main_type, 'date':i.date } data.append(item) return JsonResponse({'data':data}) and this is my template $.ajax({ type:'GET', url:'/list-main-group', success:function(data){ data = data.data spinnerBox.classList.add('non-visible') var k = '<tbody>' for(i = 0;i < data.length; i++){ const date = new Date(data[i]["date"]).toLocaleString(); const id = parseInt(data[i]['id']) // const url = '{% url "products:update_maingroup" %}' // const my_url = url + "/"+id k+= '<tr>'; k+= '<td>' + data[i]['id'] + '</td>'; k+= '<td>' + data[i]["admin"] + '</td>'; k+= '<td>' + data[i]["main_type"] + '</td>'; k+= '<td>' + date + '</td>'; k+= '<td align="center">'+ '<button class="btn btn-info bg-info" id="update" data-url='+{% url "products:update_maingroup" id %}+ '><i class="far fa-edit"></i></button>'+ ' <button class="btn btn-danger btn-del bg-danger" data-did='+parseInt(data[i]["id"])+"><i class='far fa-trash'></i></button>"+ '</td>'; k+= '</tr>' } k+='</tbody>' tableBody.innerHTML = k $('#maingroupid').dataTable({ "order": [[ 0, "desc" ]] }); }, // error:function(error){ // console.log(error) // } }); <div class="card-body table-responsive" > <div id="spinner-box" class="spinner-border text-primary text-center" role="status"> </div> <table id="maingroupid" class="table table-bordered table-striped text-center"> <thead> <tr> <th>#</th> <th>{% trans "admin" %}</th> <th>{% trans "name" %}</th> <th>{% trans "date" %}</th> <th>{% … -
how do i make program to store the onclick image as password instead of its position?
I have a graphical password system sample. currently everything works fine but how do I amend the program to store the image that the user chooses as the password instead of the position? this is the sample program from GitHub: https://github.com/mohith7548/Graphical-Password-User-Authentincation -
ELASTICSEARCH delete is not working when used ELASTICSEARCH_DSL_SIGNAL_PROCESSOR in Celery
I need to do the elasticsearch syncing process Asynchronous. So I override the django-elasticsearch-dsl signal processor with a CelerySignalProcessor. ELASTICSEARCH_DSL_SIGNAL_PROCESSOR = 'core.services.elasticsearch_service.CelerySignalProcessor' Following django-elasticsearch-dsl this documentation, I create a CelerySignalProcessor. from django_elasticsearch_dsl.signals import RealTimeSignalProcessor class CelerySignalProcessor(RealTimeSignalProcessor): def handle_save(self, sender, instance, **kwargs): # create a celery task to do the handle_save task def handle_pre_delete(self, sender, instance, **kwargs): # create a celery task to do the handle_pre_delete task def handle_delete(self, sender, instance, **kwargs): # create a celery task to do the handle_delete task handle_save is working fine in Asynchronous. But handle_pre_delete and handle_delete are not working. When Celery worker would pick up the delete job, the model instance would already deleted. Can anyone give me any idea of how to make the delete process Asynchronous? -
Reverse for '{{ feature.featurename }}' not found. '{{ feature.featurename }}' is not a valid view function or pattern name
When I AM trying to load html page an error occur . that is Reverse for ' {{ feature.featurename }} ' not found. ' {{ feature.featurename }} ' is not a valid view function or pattern name. home.html {% for feature in features_obj %} <li class="nav-item px-3 px-md-2"> <a class="nav-link active text-light" aria-current="page" href="{% url '{{feature.featurename}}' %}">{{ feature.featurename }}</a> </li> {% endfor %} urls.py path('',views.home,name='home'), path('tutorial',views.tutorial,name='tutorial'), path('knowledge',views.knowledge,name='knowledge'), views.py def home(request): logo_obj = websitename.objects.all() features_obj = features.objects.all() return render(request,'home.html',{'logo_obj':logo_obj,'features_obj':features_obj}) def tutorial(request): return render(request,'tutorial.html') def knowledge(request): return render(request,'knowledge.html') models.py class features(models.Model): featurename = models.CharField(max_length=200) image = models.FileField(upload_to='') description = models.CharField(max_length=200) value that i want to access featurename = tutorial , knowledg -
how to embad an advance domain name search in django
I working on a web-hosting project where i need to integrate a domain name search for clients to search for a domain. using whois or PyNamecheap, i can check if domain is available or not. but I want something more like namecheap domain search page to have Suggested Results and show combination of other extensions(top-level-domains) in my Results too. -
Django form validation with Bootstrap 5
I want to create django login form with bootstrap 5. How can i ensure that the form is valid? Can i styling raise validationError with bootstrap in template? Here is my code: forms.py class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField() def clean(self): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") # Check if user and password is matching and exists user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This is an invalid user.") login_page.html <form method="POST" class="row g-3 needs-validation" novalidate> {% csrf_token %} <input type="text" name="username" class="form-control" placeholder="Username" required> <div class="invalid-feedback">{{ #raise ValidationError here }}</div> <input type="password" name="password" class="form-control" placeholder="Password" required> <div class="invalid-feedback">{{ #raise ValidationError here }}</div> <input class="btn btn-primary" type="submit" value="Login"> Can i do that? Or is there a better solution to create login form validation? Thankyou. -
My for loop does not work as expected - Data does not show up in my django template
I am trying to use a for loop in my Django template to show the data stored in the models of a table but for some reason , the data does not show up in the template. Views.py def add_part(request): parts = Parts.objects.all() context = { "parts": parts } return render(request, 'admintemplate/add_parts_template.html', context) def add_part_save(request): if request.method != "POST": messages.error(request, "Method Not Allowed!") return redirect('add_part') else: part_name = request.POST.get('part_name') part_type = request.POST.get('part_type') supplier_id = request.POST.get('suppliers') suppliers = Suppliers.objects.get(id=supplier_id) try: part = Parts(part_name=part_name, part_type=part_type, supplier_id=supplier) part.save() messages.success(request, "Part Added Successfully!") return redirect('add_part') except: messages.error(request, "Failed to Add Part!") return redirect('add_part') models.py The parts and the services model are exactly the same with different column names, so I think the functionality for both should be the same. Suppliers models class Suppliers(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) Parts model class Parts(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) part_type = models.CharField(max_length=20) supplier_id = models.ForeignKey(Suppliers, on_delete=models.CASCADE) Services model class Services(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) service_type = models.CharField(max_length=20) supplier_id = models.ForeignKey(Suppliers, on_delete=models.CASCADE) Part template {% extends 'admintemplate/base_template.html' %} {% block page_title %} Add Parts {% endblock page_title %} {% block main_content %} {% load static %} <section class="content"> <div class="container-fluid"> <div class="row"> <div … -
Django 3.2.3 I'm trying to serialize object with its fields and properties methods
I'm new to django framework, I simply want to return a model object with its attributes and properties back to an ajax call as a Json response. I have an Item model with a property balance which returns an integer value. Here is my code: models.py class Item(models.Model): entered_by = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=50, blank=True) @property def balance(self): return Stock.objects.filter(item_id=self.id).aggregate(Sum('quantity')).get('quantity__sum') class Stock(models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) name = models.CharField(max_length=50, blank=True) quantity = models.PositiveIntegerField() serializers.py from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): balance = serializers.SerializerMethodField(source="get_balance") class Meta: model = Item fields = ('entered_by', 'name', 'balance') views.py from stocks.serializers import * from django.http import HttpResponse, JsonResponse def viewItem(request): if request.is_ajax and request.method == "GET": id = request.GET.get("item_id", None) item = Item.objects.get(id=id) if item: serializer = ItemSerializer() # return serializer.data return JsonResponse(serializer.data, status = 200) The output I'm seeking is a Json output like this: { name:"item name", entered_by: null, balance: 10, } Right now this is what I'm getting { entered_by: null name: "" } any thought will appreciated. -
Cloud Build Django: retry when error (collectstatic, ServiceUnavailable)
I'm building and deploying a Django app to Cloud Run with Google Cloud Build. All production migration and static file uploading are done with the same Cloud Build yaml file. However, when the step executes python manage.py collectstatic, an error occurred: google.api_core.exceptions.ServiceUnavailable: 503 DELETE [FILEPATH]: We encountered an internal error. Please try again. The official document doesn't give too much information. The storage is managed by django-storage. Is there any quick solution to retry the command if any error with cloud build? -
django how to display the todolist of the current user login
I wanna take this todoapp to the next level and display the current users todoitems aka (content). I already created a new table called todoitem with id,content,userid. The userid comes from AuthUser id. And it's showing error Cannot query "username": Must be "AuthUser" instance. here's my views.py from django.contrib.auth.decorators import login_required @login_required def todoView(request): all_todo_items = Todoitem.objects.filter(userid=request.user) return render(request, 'todoapp/home.html', {'all_items': all_todo_items}) urls.py urlpatterns = [ path('', TemplateView.as_view(template_name="todoapp/index.html")), path('home/', todoView), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] index.html {% load socialaccount %} <html> <body> {% if user.is_authenticated %} <p>Welcome, {{ user.username }} !</p> {% else %} <h1>My Google Login Project</h1> <a href="{% provider_login_url 'google' %}">Login with Google</a> {% endif %} </body> <a href="/home/">Check your Todolist</a> </html> home.html {% load socialaccount %} <h1>Welcome, {{ user.username }} !</h1> <table> <tr> <th colspan="2">List of Todos</th> </tr> {% for todo_items in all_items %} <tr> <td>{{todo_items.id.content}}</td> </tr> {% endfor %} </table> -
Unable to makemigrations in Django
Problem statement: I am trying to create a new model in a new file - app1/models/model2.py I dont see any error when I try to makemigrations. But Django doesnt detect any changes. If I put the same code in my previous file app1/models/model1.py - makemigrations works. I have tried - python manage.py makemigrations app1 & python manage.py makemigrations My basic model: from django.db import models class Xyz(models.Model): name = models.CharField(max_length=100) I tried through pycharm & normal terminal. I am using UBuntu 20.04LTS. I deleted all migration files then reran makemigrations for app1 , it only picked old changes. did not pick new Xyz model. So perhaps there is something wrong in the way I am creating this new model2.py file. But I am creating it normally like model1.py. I even tried to copy paste and rename the same file. All my folder have init.py in them. -
Django: stop saving the same value in the database
my gorgeous friends on the internet. I have a problem with my Django app, implementing a function not to save the same value in the database. When I hit command + r on a Macbook Air, my app save the previous value in the form although the form was empty. If someone knows how to stop, please let me know. Here is the code below. @login_required def blog(request, pk): blog = get_object_or_404(Blog, pk=pk) comments = Comment.objects.order_by('-created').filter(blog=blog.id) number_of_comments = comments.count() if request.method == 'GET': form = CommentForm() elif request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.user = request.user comment.save() form = CommentForm()