Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form make calculations
Hi, a im new in Django. My first application is a simulator for bank loan, just for learn, not professional. I have created in models.py a class named EntradasMaisAlimentos with the following struture: class EntradasMaisAlimentos(models.Model): valor = models.DecimalField(max_digits=7, decimal_places=2, blank=False, default=0.00) divisao = models.DecimalField(max_digits=7, decimal_places=2, blank=False, default=0) carencia = models.PositiveIntegerField(default=0) taxa = models.DecimalField(max_digits=7, decimal_places=2, blank=False,default=0.0) Than i write in forms.py: from django import forms from .models import class simulaForm(forms.ModelForm): class Meta: model = EntradasMaisAlimentos fields='__all__' The form is rendered for: from django.shortcuts import render from django.http import HttpResponse from PronafMaisAlimentos.forms import simulaForm def index(request): dadossimulacao=simulaForm() dados={ 'dadossimulacao': dadossimulacao } return render(request, 'index.html', dados) Please, dont think it is a silly question, but how i can get the values inserted in form input by the user and make some calculations and than show the results in a new template named results.html? -
Data Exploration in django
I am new to django and just started building a database of some data I have. The next step would be to create a GUI that allows the user to explore the data from the database models. I was doing some research online and came across pivottable.js https://github.com/nicolaskruchten/pivottable , which allows the integration of pivot tables and charts, which seems like a decent solution, instead of building the GUI from scratch! How can Integrate it in my django project? -
why use put method if I can use post
how exactly http methods work. the both view function do the same thing django code: //post method def create1_post(request): if request.method=="POST": any_model=AnyModel(title="example") any_model.save() //put method def create2_post(request): if request.method=="PUT": any_model=AnyModel(title="example") any_model.save() I read a lot about http methods ,But all I learned is PUT method is for update or create resource and POST method is for create resource Now I am confused . if I can edit and create models with python why I need to use put or any other http methods -
Save different instances on different get request in ajax
I am building a simple blog app and I made a view to save the instance or update the instance in model field. So, I am getting request.GET of button But It was working only when clicks on that particular class. so, I made a another elif statement to get another button But it is not working second not first. What I am trying to do ? :- I am trying to update the instance in model on different button click, like first button will update "First" in model and second button will update "Second" in model. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=1000) recommend_name = models.CharField(max_length=1000) views.py def save_instance(request, user_id): profile = get_object_or_404(Profile, user=user_id) if request.GET.get('submit') == 'first': profile.recommend_name = "First" profile.save() return redirect('home') elif request.GET.get('submit_2') == "second": profile.recommend_name = "Second" profile.save() return redirect('home') template.html <form method="GET" class="myForm" action="{% url 'save_instance' user.id %}" data-pk="{{ user.id }}"> <span id="idForm{{user.id}}"> <button type='submit' name="First">Save First</button> </span> </form> <form method="GET" class="second_form" action="{% url 'save_instance' user.id %}" data-pk="{{ user.id }}"> <span id="second_form{{user.id}}"> <button type='submit_2' name="second">Save First</button> </span> </form> <script> document.addEventListener('DOMContentLoaded', function() { window.addEventListener('load', function() { $('.unpro').submit(function(e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: thisElement.attr('action'), data: {'submit': 'first'}, dataType: 'json', method: … -
Class based views in Django
I am new to Django and I am finding it difficult to understand the nuances of class-based views. How can I go about understanding the class-based views with ease. If there are any good resources that would help me with the basic understanding of class-based views please share them. Thank you!! -
How to choose Heroku dyno type and quantity
I have an app that is currently just using the free dyno tier but needs an upgrade. My app has several clock process jobs scheduled all day long, making API calls, sorting through and manipulating data, and last month I went past my allotted hours. I've read through all the documentation and understand the concept of dyno 'containers'. But I guess I don't really understand how much each dyno can handle and how many/ what types I should use to ensure the quality of my site's performance and all the jobs get completed. Any suggestions, tips, experiences would be great. Thanks! -
Django template inheritance is not working inside the folder file. How to do?
I am extending base.html inside the folder file. My root file name is base.html and I want to extend base.html inside the folder file. base.html(mainfile) -credential(foldername) --login.html(filename) I am trying like this {% extends '././base.html' %} {% block login %} {% endblock %} -
Django Javascript append options
In my class in models.py I have a field: names = models.TextField(max_length=40, choices=sektor, default="Adam", verbose_name="Name") sektor = ( ("Adam", "Adam"), ("Tom", "Tom"), ) When I change an option in my page, I run the following script <script type="text/javascript"> var endpoint = '/call_jquery_sektor/' var sektor = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ sektor = data.sektor //loop $(sektor).each(function(i) { $("#id_names").append("<option>" + sektor[i] + "</option>") //append options }) }, error: function(error_data){ console.log("error") console.log(error_data) } }) </script> I get all data, writen as two elements of each tuple, in one row. I would like to clear all previous options and when I run script I would get list of all names, each name single time and only 1 in 1 row. I get: Adam, Adam, Tom, Tom I would like to get: Adam Tom -
Django, how upload file into newly created folder
I'm Trying upload file into folder, but folder created as soon as take request from client -
Django Heroku Application Error (Need Help)
I have been looking for this answer for over days and have not found the right one yet so finally decided to make a question. My code successfully deployed on the heroku but I got this Application Error. When I run the cmd heroku logs --tail, it said H10 code error. I looked for the solution on google and mostly it said that have an issue in the Profile file. But my Procfile is ok. When I deployed it said, remote: -----> Discovering process types remote: Procfile declares types -> web like this. Here is my Procfile: web: gunicorn advamedservice.wsgi And I saw people say that the name in the Procfile should be the same as the project name and also in the wsgi file. So I look for it and the name is the same nothing wrong. I really need this to work perfectly fine on the internet. So please help me. -
ValidationError "value must be a decimal number"
I have a model class FunderProgramMember(models.Model): buyer = models.IntegerField() supplier = models.IntegerField() discount_rate = models.DecimalField(max_digits=3, decimal_places=2) In my serializer I am trying to get the discount field: discount_rate = FunderProgramMember.objects.values('discount_rate').get(supplier=item.invoice.supplier_id, buyer=item.invoice.buyer) Even if I replace my filter "get(supplier=item.invoice.supplier_id, buyer=item.invoice.buyer)" with pk=2 I still receive the following validation error: ["“{'discount_rate': Decimal('0.25')}” value must be a decimal number."] It appears to get a decimal value. How do I fix this error? -
HTML & CSS - label position and size changes when click on edit
I have 4 labels and one save/update button depends on when user want to edit or save it functionality is working fine but the button and labels moves when user click on edit and also i want it to be of same equal label size .I have tried out but i'm not getting the expected one.I dont know where im going wrong all i just edited and changed the container size. When i removed the save/update button the label didnt moved it sticked to the same position but the lable size differs.I'm using django as backend but I haven't specified anything for the frontend.it just completely html css n js. without button when user saves when user edits html: <div class="container-l" id='firstcontainer'> <div class="container-fluid"> <div class="fade-in"> <div class="card"> <div class="card-header">User's Details <span class="badge badge-info mfs-2"></span> <div class="card-header-actions"><a href="#" target="_blank" class="card-header-action"> <small class="text-muted"></small></a></div> </div> <div class="card-body"> <br> <div class="container-md" id='firstcontainer'> <form action=" " method="POST" autocomplete="off"> {% csrf_token %} <!-- <div class="container-md"> --> <!-- <h4 id='text' align='center'>User Details </h4> --> <div class="row"> <div class="row mb-3"> <div class="col" id='c1'> <small> Email address</small></div> <div class="col" id='c2'><small> Username</small></div> <div class="col" id='c3'><small> Select Format</small></div> <div class="col" id='c4'><small>Select Timezone</small></div> </div> </div> <!-- <div class="container-md"> --> <!-- <div … -
Cannot integrate 'ckeditor_wiris' plugin into django-ckeditor in custom toolbar configuration
I am using django to make a science related blog site where I am using django-ckeditor as the richtext editor. I encountered the following problem: I am trying to integrate the 'ckeditor_wiris' external plugin in custom toolbar. Other external plugins - 'Codesnipet' and 'Symbol' are working fine but 'ckeditor_wiris' is not visible on the toolbar. CKEDITOR_CONFIGS = { 'default': { 'height':'250px', 'width':'100%', 'tabSpaces': 4, 'toolbar': 'Custom', 'toolbar_Custom': [ ['Smiley', 'CodeSnippet', 'Symbol', 'ckeditor_wiris'], ['Bold', 'Italic', 'Underline', 'RemoveFormat', 'Blockquote'], ['TextColor', 'BGColor'], ['Link', 'Unlink'], ['NumberedList', 'BulletedList'], ['Maximize'] ], 'extraPlugins': ','.join(['codesnippet', 'symbol', 'ckeditor_wiris' ]), } } WIRIS plugin not visible on toolbar Though if I use the 'full' toolbar instead of 'custom' then 'ckeditor_wiris' is visible on the toolbar. What can I do to make it visible on the toolbar in custom settings? -
How to solve TypeError at admin page?
I am pretty new to Django and I was just following along witht the tutorial. I worked on adding a leads page, and coudn't load the admin page after adding the leads page. I am getting a message like this TypeError at /admin/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\urls\resolvers.py, line 460, in _populate Python Executable: C:\Users\Dell\Desktop\prog\programa\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\Dell\\Desktop\\prog', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\\python39.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\Dell\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\\Users\\Dell\\Desktop\\prog\\programa', 'C:\\Users\\Dell\\Desktop\\prog\\programa\\lib\\site-packages'] -
how to get the path of any folder i want when i select them in django
I want the user to be able to get the path of any directory so that my code can handle the dicom images in that directory. is there any way? I tried using tkinter but its window is always showing out before I get on my web. enter image description here -
Django makemessages fails both with django-admin and manage.py
I have a fresh Django project with no third-party apps installed. I'm trying to create a multilingual setup, with from django.utils.translation import gettext_lazy as _ in my Python files and {% translate %} in my templates. When I try to extract the messages, I get an error. (venv) d:\dev\py\filfak\src>py manage.py makemessages -l es processing locale es CommandError: errors happened while running msgmerge msgmerge: unrecognized option `--previous' Try `(null) --help' for more information. Somebody has an idea why does this happen? And, more important, how to solve it? If it helps somehow, I'm using Python 3.9.6 and Django 3.2.8 on Windows. -
I want to represent django QUERY as table in html page with table heading same as django field name. How can I implement this?
I would like to find a way to represent on HTML table a recordset obtained through a SQL query. I consulted a previous post that spoke of a similar problem to mine but in that post refer to a model and I couldn't adapt it to my needs. I would like to adapt the solution of that post so that it works even when I use SQL query. It would be possible? The post is this: I want to represent django model as table in html page with table heading same as django field name. How can I implement this? Here my view: def posts_discussione(request,pk): discussione = Discussione.objects.get(pk=pk) posts = Post.objects.raw(f'SELECT * from forum_post where discussione_id = {pk} order by dataCreazione ASC') context = {'posts':posts,'discussione':discussione} return render(request,'posts-discussione.html',context) Here my HTML code: <table> <thead> <th>Autore</th> <th>Data</th> <th>Contenuto</th> </thead> <tbody> {% for post in posts %} <tr> <td>{{post.autorePost}}</td> <td>{{post.dataCreazione}}</td> <td>{{post.contenuto}}</td> {% endfor %} </tbody> </table> -
I keep getting path error when i input in the django app
this is my views.py, when i input in anything i get error i tried changing the path to /fo still there is error.............................................. from django.shortcuts import render import requests import sys from subprocess import run, PIPE def button(request): return render(request, 'home.html') def button(request): return render(request, 'home.html') def output(request): data = requests.get("https://www.google.com/") print(data.text) data = data.text return render(request, 'home.html', {'data': data}) def external(request): inp = request.POST.get('param') out = run([sys.executable, 'buttonpython/buttonpython/test.py', inp], shell=False, stdout=PIPE) print(out) return render(request, 'home.html', {'data1': out.stdout}) -
Getting the error 'ClassAssignment' object has no attribute 'assignmentfileupload'
The models that I am using are as followed class ClassAssignment(models.Model) : classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE) title = models.CharField(max_length=300, blank=False, null=False) instructions = models.TextField(blank=True, null=True) completed = models.ManyToManyField(User) due_date = models.DateTimeField(blank=True, null=True) created_on = models.DateTimeField(default=datetime.now()) def __str__(self) -> str : return self.title class AssignmentFileUpload(models.Model) : assignment = models.ForeignKey(ClassAssignment, on_delete=models.CASCADE) attachment = models.FileField(upload_to="assignment_uploads/") created_on = models.DateTimeField(default=datetime.now()) def __str__(self) -> str : return self.assignment.title def delete(self, *args, **kwargs) : self.attachment.delete(save=False) return super().delete(*args, **kwargs) The code for the serializer class AssignmentSerializer(serializers.ModelSerializer) : assignmentfileupload = serializers.HyperlinkedRelatedField( view_name='file_uploads', many=True, read_only = True ) class Meta : model = ClassAssignment fields = ( 'id', 'classroom', 'title', 'instructions', 'due_date', 'created_on', 'assignmentfileupload' ) I am not able to understand where I am doing wrong. Even the documentation says the same thing and I followed it but it is not working as expected. -
How to display child row information using jQuery DataTables plugin with Django
I am referring to https://www.geeksforgeeks.org/how-to-display-child-row-information-using-jquery-datatables-plugin/ and I want to display datatable with child rows. The problem I faced now is to pass the view function I created. I want to pass the django url on the line: "ajax": "nestedData.txt", instead of a file as it is here $(document).ready(function () { /* Initialization of datatables */ var table = $('#tableID').DataTable({ "ajax": "nestedData.txt", "columns": [{ "className": 'details-control', "orderable": true, "data": null, "defaultContent": '' }, { "data": "name" }, { "data": "designation" }, { "data": "city" }, { "data": "salary" } ], "order": [[1, 'asc']] }); Kindl assist -
model methods returning empty strings
I am getting empty in return (from my model methods), I don't get where I am wrong , we can model using self class SocialLinks(models.Model): alias_name = models.CharField(max_length=10,) name = models.CharField(max_length=30) url_link = models.URLField() def get_fb_link(self): try: fb = self.objects.get(alias_name='fb') return fb.url_link except: return "" def get_linkdin_link(self): try: linkdin = self.objects.get(alias_name='linkedin') return linkdin except: return "" def get_insta_link(self): try: insta = self.objects.get(alias_name='insta') return insta.url_link except: -
Not Found The requested resource was not found on this server. python
I try to upload my project to cpanel, but when i try error like this Not Found The requested resource was not found on this server. i try to edit my wsgi file many times, but still not working i try to install django with virtualenv and upgrade pip with virtualenv, but still not working, i try to reset my cpanel and do it again still not working, i try to ask with the customer service but there is no answer this is my project directory enter image description here and this is my python app enter image description here this is my passanger_wsgi file and this is my requirements.txt file asgiref==3.4.1 certifi==2021.10.8 charset-normalizer==2.0.7 Django==3.2.8 idna==3.3 Pillow==6.2.2 pytz==2021.3 requests==2.26.0 sqlparse==0.4.2 urllib3==1.26.7 app an this is my settings """ Django settings for web_test project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
How do you install npm for Windows?
I am trying to install tailwind CSS, and one of the codes I need to write is the following: $ npm init -y && npm install tailwindcss autoprefixer clean-css-cli && npx tailwindcss init -p However, this is obviously for the macOS. Is there another way to do this for the windows system? Thank you, and please ask me any questions you have. -
drf create manytomany fields
models class CreatorRawArtwork(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=500) descripton = models.TextField() editions = models.IntegerField(null=True, blank=True) price = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) medias = models.FileField(null=True, blank=True, upload_to="raw-medias") user = models.ForeignKey( to=Login, on_delete=models.CASCADE, related_name="creatorrawartwork", null=True, blank=True ) collection = models.ForeignKey( to=DesignerCollection, on_delete=models.CASCADE, related_name="creatorrawartwork", null=True, blank=True ) categories = models.ManyToManyField(DesignerCategories, related_name='creatorrawartwork') def __str__(self): return self.title serializer class CreatorRawArtworkSerializer(serializers.ModelSerializer): categories = serializers.PrimaryKeyRelatedField(queryset=DesignerCategories.objects.all(), many=True) class Meta: model = CreatorRawArtwork fields = "__all__" depth=1 views class CreatorRawArtworkView(viewsets.ModelViewSet): queryset = CreatorRawArtwork.objects.all() serializer_class = CreatorRawArtworkSerializer Here i am trying to create manytomany fields using drf serialier it is showing some error plese check the screenshot for parameter and responses What can be the issue please take a look -
how to redirect to another page in django without refreshing?
how to redirect to another page in Django without refreshing? how to redirect to another page in Django without refreshing? how to redirect to another page in Django without refreshing?