Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django app listening on localhost:8000 vs 0.0.0.0:8000
I have a Django app running on Google Kubernetes Engine.If I run the enter the pod , and run netstat -l command. It shows that the service is listening on localhost:8000 I ran the same service on Elastic Kubernetes service on AWS. There the service didn't respond to the outside requests when the container was listening on localhost:8000. I had to run python manage.py runserver 0.0.0.0:8000, so that container listens on all the network interfaces. On AWS , the output of netstat -l looks like this I want to understand, that Why the same app was running on the google Kubernetes engine, but not on EKS, and I had to specifically define to listen on 0.0.0.0:8000. Why the google Kubernetes engine listens to outside traffic , when the netstat -l shows that it is listening on localhost:8000 -
Getting error on terminating Django server using Threading and Schedule
I'm trying to use Schedule on the background using threads in my Django application as it was described in Oz123's answer, everything works fine without any problem, except when I'm trying to use commands from the terminal (e.g. python manage.py makemigrations or python manage.py runserver ) they will not end and finished until I'm sending keyboardInterupt. Then it will give me the following error: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 1388, in _shutdown lock.acquire() p.s.: for python manage.py runserver I have to send KeyboardInterupt two times. one for ending the server, then the second one will end the function and raise the mentioned error. My application is using one schedule in the background which is happening every hour to check a model for specific changes. So, there is no stop to this schedule and I want to run it until the server is running (forever). Is there any way to solve this problem? It is so much annoying to press KeyboardInterupt (CTRL + C) for ending every command. -
Change a future date every five days
I am working on a point of sale app in Django in which the customer books a product and it is delivered in 45 days. I can get the delivery date while booking using the following: from datetime import datetime, timedelta DELIVERY_IN_DAYS = 45 delivery_on = datetime.today() + timedelta(days=DELIVERY_IN_DAYS) delivery_on = delivery_on.strftime('%Y-%m-%d') now I want the delivery_on to remain same for 5 days and change on the 6th day. can I do it without using a background celery job? Thanks in advance. -
What's wrong with {% if join_detail.designated_code == element.designated_code %}?
I am a student learning Django. I want to display value_code as follows, but there is a problem that it does not appear. I don't know where the heck is the problem. To represent value_code, designated_code.designated_code is expressed in this way, but all information in the model is not output or output. I want to print only the value corresponding to the if statement. It would be really appreciated if you could tell us what the problem is and how to solve it. Model.py from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse # 회원 class Member(AbstractUser): username = models.CharField(primary_key=True, max_length=20, verbose_name='아이디') name = models.CharField(max_length=20, verbose_name='이름', default='') password = models.CharField(max_length=64, verbose_name='비밀번호') phone = models.CharField(max_length=64, verbose_name='전화번호') def __str__(self): return self.username class Meta: verbose_name = ('Member') verbose_name_plural = ('Members') # 카테고리 class Category(models.Model): category_code = models.AutoField(primary_key=True) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, allow_unicode=True) class Meta: ordering =['category_code'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_in_category', args=[self.slug]) # 상품 class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() … -
Django autocomplete light only works in the admin section
I'm trying to insert the autocomplete in the select to speed up the request. The problem is that it only works in the admin section. Autocomplete in admin section In the user's view, however, it doesn't work at all. Autocomplete not working in user view -
How to integrate Sales force and Django?
I have to complete a task as bellow:- I have to implement salesforce integration. Which include fetching user token from salesforce using OAuth2. Once you have the token I need to fetch the list of Users, Accounts, and Contacts from salesforce and store it in the database. I need to write the code in Django and not supposed to use any existing third-party salesforce integration app? Please suggest me resourses or algorithm to achieve the solution.. Thanks in advance. Hope to here from you soon.. -
How to collect multiple payment from customer and calculate with remaining balance in Django?
info I am trying to create a monthly installment app using Django. I don't know how I could calculate Property' price with amount. I want to calculate the property price with the Payment amount and get the remaining price and save it to database. Customer has multiple payments so every month i get new payment from single customer and compare with remaining amount and get new remaining amount. i don't know how can i do that? models.py class Property(models.Model): area = models.CharField(max_length=255) price = models.IntegerField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) remaining = models.IntegerField(default=0) def save(self, *args, **kwargs): self.remaining = self.prop_select.price super().save(*args, **kwargs) class Payment(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True, related_name='payment') amount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.customer.remaining - self.amount super().save(*args, **kwargs) self.customer.save() -
How to connect my REST API to another API
I have a REST API written in django-rest-framework. I want to connect it to another REST API that has a database set up with postgresql. My API extends the base User model and provides some additional features. I do not want to create new tables for users, but just use the existing users in the second API. Do you have any suggestion how to do so? -
geting eror while addong mysql table to html form in django ProgrammingError (1146, "Table 'insert.insertemp_empinsert' doesn't exist")
This is django code in views.py so when I run this I get programing error and my database is MySql from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages from django.http import HttpResponse def Insertrecord(request): if request.method=='POST': if request.POST.get('productname')and request.POST.get('f1')and request.POST.get('f2')and request.POST.get('f3')and request.POST.get('f4')and request.POST.get('f5'): saverecord=EmpInsert() saverecord.productname=request.POST.get('productname') saverecord.f1=request.POST.get('f1') saverecord.f2=request.POST.get('f2') saverecord.f3=request.POST.get('f3') saverecord.f4=request.POST.get('f4') saverecord.f5=request.POST.get('f5') saverecord.save() messages.success(request,'Record Saved Successfully...!') return render(request,'Index.html') else: return render (request,'Index.html') -
Loading images from an AWS bucket media folder to a HTML pdf template
I am trying to generate a PDF file out of a post created by a user, and include an image, which I want to store in an AWS bucket. This is how it was working with my own file system My function to generate a pdf in views.py: def form_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') form = get_object_or_404(Post, pk=pk) template_path = 'form/pdf2.html' context = { 'form': form } # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response And rendering the image in the html template <div> <img src="{{form.image.path}}"> </div> Now after uploading the files in a bucket it doesn't seem to work. The image is being stored there after uploading the post, but when creating the PDF the image is not displayed.(And it gives me an error: This backend doesn't support absolute paths). I tried to change the image source in the HTML template but it still didn't work. -
Pass Django Form to js
I am new to django and I want to write an easy Django application with Django 2.3 and Python 3.7. I am using in my view.py (if more of my code is needed, I can provide it): context["form"] = MyForm(request.POST, request.FILES) return render(request, "myhtml.html", context) My forms.py also looks very simple: class MyForm(forms.Form): name = forms.CharField() address = forms.CharField() I want to build in my application a button in which the form appears, but I do not want to hide the form by display: none; Is it possible to give the form over in a format that I can use JavaScript to build the form or do I always need to build the form in HTML and manipulate it afterwards with JS? Is it reasonable to return the Form as JSON.Response or does Django always return the Forms as HTML strings and not JS elements? -
How do i display django class based view api on bootstrap template?
I am working on a photography website and i have created a rest api for blog but i am facing trouble how to display the api on template. My project structure enter image description here This is my view.py of Blog from rest_framework.response import Response from rest_framework import permissions from rest_framework.views import APIView from rest_framework.generics import ListAPIView, RetrieveAPIView from blog.models import BlogPost from blog.serializers import BlogPostSerializer from rest_framework.renderers import TemplateHTMLRenderer class BlogPostListView(ListAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostDetailView(RetrieveAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostFeaturedView(ListAPIView): queryset = BlogPost.objects.all().filter(featured=True) serializer_class = BlogPostSerializer lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostCategoryView(APIView): serializer_class = BlogPostSerializer permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = BlogPost.objects.order_by('-date_created').filter(category__iexact=category) serializer = BlogPostSerializer(queryset, many=True) return Response(serializer.data) This is urls.py of Blog from django.urls import path from .views import BlogPostListView, BlogPostDetailView, BlogPostFeaturedView, BlogPostCategoryView urlpatterns = [ path('', BlogPostListView.as_view(), name='bl'), path('featured', BlogPostFeaturedView.as_view()), path('category', BlogPostCategoryView.as_view()), path('<slug>', BlogPostDetailView.as_view()), ] This urls.py of application from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from portfolio import urls, views from blog import urls from django.conf … -
How to use bootstrap with django-ckeditor?
I just want to add the bootstrap class form-control to my ckeditor form. Thank you in advance. -
RuntimeError at URL , while reloading with action attribute
I am a Django beginner, trying to build a website I am trying to redirect user to the the same page after submitting a form using action attribute but its giving me an error these are the project files Project urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', admin.site.urls), path('',include('firmpage.urls')) ] App urls.py from django.contrib import admin from django.urls import path,include from firmpage import views admin.site.site_title = "Dashoard" admin.site.site_header = "Admin Panel" admin.site.index_title = "Database manager" urlpatterns = [ path('/',views.home,name='home'), path('',views.home,name='home'), path('home/',views.home,name='home'), path('about/',views.about,name='about'), path('services/',views.services,name='services'), path('contact/',views.contact,name='contact') ] App views.py from django.shortcuts import render,HttpResponse from firmpage import models def home(request): return render(request,'index.html') def contact(request): if request.method == 'POST': print(request.POST) name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] description = request.POST['desc'] print(name,email,phone,description) contactObject = models.contact(name=name,email=email,phone=phone,desc=description) contactObject.save() print("data written succesful") return render(request,'contact.html') def services(request): return render(request,'services.html') def about(request): return render(request,'about.html') contact.html {% extends "base.html" %} {% block title %}Contact{% endblock title %} {% block contactactive %}active{% endblock contactactive %} {% block body %} <script> function myFunction() { alert("Submitted successfully."); } </script> <div class="container my-3"> <h1 class="text-center">Contact Me</h1> <form action="/contact" method="post"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="name" class="form-control" id="name" name="name" placeholder="Your Name"> </div> <div … -
Where developers save choice options in Django?
For example i have a choice COLORS = ( ('red', 'Red'), ('blue', 'Blue'), ('yellow', 'Yellow'), ) Should i create a model like: class Color(models.Model): color = models.CharField(...) and create some color instances in django-admin or i need to declare CHOICE(above), where i save all colors(even if there are many colors)? -
How to update multiple objects from a model in django model form
I'm learning Django recently. i created a model with SQLite database and created views with model from. so i need to edit all of objects from a model in a page. something like this: doesn't matter that update button to be just one button for all objects or one button for each one of them. this is html page (edit_info.html): <table class="table"> <thead class="thead-primary"> <tr> <th class="">نام</th> <th class="">نام خانوادگی</th> <th class="cell100 column2">جنسیت</th> <th class="cell100 column3">کد ملی</th> <th class="cell100 column4">شماره پرسنلی</th> <th class="cell100 column5">تلفن</th> <th class="cell100 column6">آدرس</th> <th class="cell100 column7">وضعیت تاهل</th> <th class="cell100 column8">سن</th> <th class="cell100 column9">حقوق دریافتی</th> <th class="cell100 column10">ویرایش</th> </tr> </thead> <tbody> {% for employee in employees %} <tr class="row100 body"> <form method="POST" class="post-form" action="/update/{{employee.personnel_code}}"> {% csrf_token %} <th class="cell100 column0"><input type="text" name="first_name" id="id_first_name" required maxlength="100" value="{{ employee.first_name }}" /></th> <th class="cell100 column1"><input type="text" name="last_name" id="id_last_name" required maxlength="100" value="{{ employee.last_name }}" /></th> <th class="cell100 column2"> <input {% if employee.gender %} checked {% endif %} type="checkbox" name="gender" id="id_gender" /> </th> <th class="cell100 column3"><input type="number" name="eid" id="id_eid" required maxlength="20" value="{{ employee.eid }}" /></th> <th class="cell100 column4"><input type="text" name="personnel_code" id="id_personnel_code" required maxlength="6" value="{{ employee.personnel_code }}" /></th> <th class="cell100 column5"><input type="text" name="phone_number" id="id_phone_number" required maxlength="15" value="{{ employee.phone_number }}" /></th> <th class="cell100 column6"><input … -
django-graphene resolver using dataloader to make m2m relationship data_fetch batched
class UserWork(models.Model): work_uuid = models.AutoField() user_id = models.OneToOneField(User) doc = models.ManyToManyField(Docs, through=u'UserDoc') class UserDoc(models.Model): document = models.ForeignKeyField(Doc) work = models.ForeignKeyField(UserWork) class Doc: upload_location = models.TextField() From this db_schema , I am making a graphql request query{ user(id){ userworks{ work_id, docs{ upload_location } } } } The issue is that the request happens for doc seperately for each work. I am stuck at adding a dataloader's load_many() and pull all the docs related to all work_ids at a time. -
Python Django Post Requests Spam Prevention
I have developed a project with Django. But I want each user IP to be able to post request for 2 minutes to prevent spam. How can I achieve this? Do you have a suggestion? -
What is the proper python/django way of formatting the URL?
Hello fellow programmers, I am working on a web app for cs50w course and my code is almost fully functional however, I noticed that when I use a specific function the URL not displayed properly. Below is a function that return an entry and displays the URL properly: def display_entry(request, entry): entrykey = util.get_entry(entry) markdowner = Markdown() context = {'entry': markdowner.convert(entrykey)} context.update({'title':entry}) context.update({'content': entrykey}) return render(request, "encyclopedia/entry.html", context) Below is a random function that returns an entry but the URL is not what it should be... def random_entry(request): # retrieves a list of the entries entries = util.list_entries() entry = random.choice(entries) # retrives a the content of a random entry entrykey = util.get_entry(entry) # formats the random entry for display and returns the content to page markdowner = Markdown() context = {'entry': markdowner.convert(entrykey)} context.update({'title':entry}) context.update({'content': entrykey}) return render(request, "encyclopedia/entry.html", context) Finally, my URL patterns ... urlpatterns = [ path("", views.index, name="index"), path("create", views.create, name="create"), path("edit", views.edit_entry, name="edit_entry"), path("save", views.save_entry, name="save_entry"), path("search", views.search_entry, name="search_entry"), path("wiki/<str:entry>/", views.display_entry, name="view_entry"), path("random_entry", views.random_entry, name="random_entry"), ] I tried changing the random_entry to wiki/<str:entry>/ but that created more problems. Feel free to comment on my code without necessarily giving me the answers. Kind regards, A -
To output D-Day from Django
I'm a student who is learning how to do a funeral. I'd like to print out how many days are left from a certain date, such as D-Day. The current database stores recruitment start and end dates as start_date and due_date. I would appreciate it if you could tell me how to print out D-Day. class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() class Meta: ordering = ['product_code'] index_together = [['product_code', 'slug']] def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_detail', args=[self.product_code, self.slug]) -
【Django】 I hope my users can create their own table through AdminStie(including fields), is that possibile?
It's an assets management site, each of our user can have an account. Login in to the AdminSite, they are allow to create a table for their specific assets, such as a BOOK table with bookName、price、number、author for user A , and a BROTHER table with name、age、hobby、location ... -
how to send image file in post request from django
I am building article writing website where user can write and add images to their articles. I am using imgur.com api and its access-token to upload images to imgur.com. but i cant upload image directly to imgur.com from post fetching because it can reveal my access-token, so i want to send that image to my django server(post request) from where django can make a post requests to imgur to upload that sent image and in return i will get image link. my postman request. im seting image file to django server where i will send this image to imgur.com django post api code class ImageUploadView(APIView): permission_classes = [ AllowAny ] parser_classes = [MultiPartParser, FormParser] def post(self, request): print(request.data) uploaded_file = request.FILES['image'] uploaded_file2 = str(uploaded_file.read()) url = "https://api.imgur.com/3/upload" payload={} files=request.FILES['image'] headers = {'Authorization': 'Bearer vghgvghvhgvhgv'} response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text) i am getting this error ValueError: too many values to unpack (expected 2) -
how can i deal with this problem "TypeError: Cannot read property 'toString' of undefined"
html file:- <div class="my-3"> <label for="quantity">Quantity:</label> <a class="minus-cart btn"><i class="fas fa-minus-square fa-lg" id="{{cart.product.id}}" ></i></a> <span id="quantity">{{cart.quantity}}</span> <a class="plus-cart btn"><i class="fas fa-plus-square fa-lg pid={{cart.product.id}} ></i></a> </div> jquery file:- $('.plus-cart').click(function () { var id = $(this).attr("pid").toString(); var eml = this.parentNode.children[2]; console.log(id); $.ajax( { type: "GET", url: "/pluscart", data: { prod_id: id }, success: function (data) { console.log(data); eml.innerText = data.quantity; document.getElementById("amount").innerText = data.amount.toFixed(2); document.getElementById("totalamount").innerText = data.totalamount.toFixed(2); } }) }); error image please help me to solve this probelm this is last error that i have been occure in my project -
Full Stack Web Development roadmap [closed]
I am in 1st yr of the university and I would like to start learning full-stack web development to build portfolio projects to get internships. I already know intermediate Python, HTML and core CSS and some psql. Here is the learning roadmap I have decided to follow this summer I just need opinions on if I should add anything remove anything, do a different order or change frameworks. Javascript Flask Django Node.JS Express.JS React.JS p.s (feel free to give project ideas as well that would look good on resumes I currently have a chat app and a Netflix clone) -
Getting errors While generating a Zoom meeting using Django?
my view @csrf_exempt @api_view(['POST']) @permission_classes((IsAuthenticated, )) def createZoomMeetings(request): try: payload = {'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=30), 'iss': credentials['API-KEY'] } token = jwt.encode(payload, credentials['API-SECRET']).decode("utf-8") conn = http.client.HTTPSConnection("api.zoom.us") headers = { 'authorization': "Bearer " + token, 'content-type': "application/json" } except Exception as e: print(e) return Response(e) conn.request('POST', '/users/me/meetings', headers=headers) res = conn.getresponse() data = res.read() data = data.decode('utf8').replace("'", '"') return Response(data) request body { "title" : "trignometry", "type" : 2, "start_time" : "2021-07-12T12:02:00Z", "duration" : 60 } I am using Jwt app and got APi key and Api secret from there and currently i am tring to create a zoom meeting using above body object but is is giving this response response received "{\"page_count\":1,\"page_number\":1,\"page_size\":30,\"total_records\":1,\"users\":[{\"id\":\"l5aHV-z2T9-vcx_Zcjg9Jw\",\"first_name\":\"dhruv\",\"last_name\":\"singhal\",\"email\":\"dhruvsin@iitk.ac.in\",\"type\":1,\"pmi\":5495443330,\"timezone\":\"Asia/Calcutta\",\"verified\":1,\"created_at\":\"2020-09-01T04:57:25Z\",\"last_login_time\":\"2021-07-05T08:04:40Z\",\"last_client_version\":\"5.7.1.1254(android)\",\"language\":\"en-US\",\"phone_number\":\"\",\"status\":\"active\",\"role_id\":\"0\"}]}" I didn't understand what is it and why i am not getting the original Response , please help in resolving this doubt and create a zoom meeting