Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Django model extesion validator doesn't work
I want to only .xlsm files to be uploadable to the form.I tried a lot of thing according to this question. But did not work. I don't know why? How can I solve it? models.py from django.core.validators import FileExtensionValidator ... pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True, validators=[FileExtensionValidator(allowed_extensions=['xlsm'])]) ... -
How to include Run functionality in my API in Django?
I'm working on Django project where I have to make a API. In my normal Django I have one functionality named Run , that I want to add that functionality in my API View Here's my model class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") def __str__(self): return self.robot class assignParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True) here's my serializer.py from .models import Robot,assignParameter from rest_framework import serializers class assignParameterSerializer(serializers.ModelSerializer): class Meta: model = assignParameter fields = ['id', 'parameterName', 'assignRobot'] class RobotSerializer(serializers.ModelSerializer): param = assignParameterSerializer(many=True, read_only=True) class Meta: model = Robot fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job', 'jenkins_token', 'jenkins_build', 'jenkins_build_status','param'] here's my normal run function def Run_data(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) jenkinsJob = list(Robot.objects.values('jenkins_job').get(pk=id).values())[0] jenkinsToken = list(Robot.objects.values('jenkins_token').get(pk=id).values())[0] fm = RobotReg(Request.POST, instance=pi) out = fm.data robot_params = list(dict(out).values()) node = robot_params.pop(1)[0] url = list(Lookup.objects.values('Value').filter(Type='JENKINS_URL').values())[0].get('Value') Uipath = list(Lookup.objects.values('Additionalinfo').filter(Type='JENKINS_NODES',Value=node).values())[0].get('Additionalinfo') robotexe = list(Lookup.objects.values('Value').filter(Type='ROBOT_EXE_PATH',Additionalinfo=node).values())[0].get('Value') robot_params.append(['node', node]) robot_params.append(['Uipath', Uipath]) robot_params.append(['robotexe', robotexe]) params_count = len(robot_params) params_exist = len(robot_params[1][0]) params = "" urlFinal = "" # url = Lookup.objects.filter(Type="JENKINS_URL").values_list(Value) if params_count > 0: for i in … -
How to correctly delete Model object field in django
Hello I want to delete my field : tag_number = models.PositiveIntegerField('Tag number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) and write fo this method: # @require_POST def book_tag(request, pk): book = get_object_or_404(Book, pk=pk) book.tag_number = **book.tag_number.delete()** book.tag_number = book.generate_tag() book.save() return redirect('book:book-list') But it delete all Book Model!I want to delete just the field 'tag_number'. -
Can I write one viewset for List, Retrieve, Update, and Delete?
I am using a viewset.ModelViewSet to list, retrieve, update and delete Car objects. I have two urls: one ends with .as_view({'get': 'list'}) and other with .as_view({'get': 'retrieve'}), and latter one is used for updating and deleting a car object. Is it ok (won't it throw some errors in the future) or should I rewrite the PUT and DELETE in another view? -
Best practice to compile Django translation files
I am looking for a best practice approach on how to compile translation files in Django. Currently the following is given: GitHub + POEditor Importing into POEditor is done with Webhooks, which works quite fine. Exporting is also done automatically, but compiling the *.po to a *.mo still needs human intervention. One approach could be to do this with GitHub Actions. Is there such a thing as a Best Practice for this? How are large organisations are dealing with this? Thanks -
Using fields from a aggregated QuerySet in a django template
So I got a QuerySet result from an aggregate function to display in a low-spec eBay clone of mine. But my problem is displaying certain fields in the Django template as I want, for example, I want to display the highest bidder's username and bid. When I call the whole object itself like so {{winner}}, then it displays. But when I try to access its fields like so {{winner.user_id.username}}, I get no output although the QuerySet does execute. When I try to get a field like so (winner.user_id.username): When I only call winner: models.py from django.contrib.auth.models import AbstractUser from django.db import models CATEGORIES = [ ('Appliances', 'Appliances'), ('Tech', 'Tech'), ('Gaming', 'Gaming'), ('Fashion', 'Fashion'), ('Sports and Fitness','Sports and Fitness'), ('Other','Other'), ("Hygiene and Medicine","Hygiene and Medicine"), ("Stationery","Stationery"), ('Decor', 'Decor'), ('Furniture','Furniture'), ('Cars and Mechanical Things','Cars and Mechanical Things'), ("Tools","Tools") ] # Create models here class User(AbstractUser): pass class Auction_Listing(models.Model): user_id = models.IntegerField(default=1) list_title = models.CharField(max_length=64) desc = models.TextField(max_length=600) img_url = models.URLField(max_length=200, null=True, blank=True) start_bid = models.IntegerField() category = models.CharField(choices=CATEGORIES, max_length=35, null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return f"ID:{self.id}, {self.list_title}: {self.desc}, {self.start_bid} posted by user:{self.user_id} in Category:{self.category}, url:{self.img_url}" class Bids(models.Model): user_id = models.ForeignKey('User', on_delete=models.CASCADE) auctions = models.ForeignKey('Auction_Listing', on_delete=models.CASCADE, default=1,related_name='bidauc') bid = models.IntegerField() def … -
How to obtain custom simpleJWT tokens in views with Django?
I have a custom serializer to get tokens without a password for a user: class ObtainTokensWithoutPasswordSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password'].required = False def validate(self, attrs): attrs.update({'password': ''}) return super(TokenObtainPairWithoutPasswordSerializer, self).validate(attrs) In my views I use it like this: class ObtainTokensWithoutPasswordView(TokenViewBase): serializer_class = ObtainTokensWithoutPasswordSerializer And finally, this is the url to get the tokens: path('token/', views.ObtainTokensWithoutPasswordView.as_view()), Making a request to this url returns tokens correctly but I would need to obtain a pair of tokens in another class in views.py. Can I do it somehow using my serializer class, for example something like this: class UserClass(generics.ListCreateAPIView): permission_classes = (AllowAny,) serializer_class = UserSerializer def post(self, request): ... tokens = ObtainTokensWithoutPasswordSerializer -
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.