Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
'LoginForm' object has no attribute 'get_user'
I tried to get login with login class based view, but when I did that, it Showed me this error: AttributeError: 'LoginForm' object has no attribute 'get_user' and this is my login form code in forms.py: from django import forms class LoginForm(forms.Form): """ The login form """ def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(LoginForm, self).__init__(*args, **kwargs) username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) and this one is my login class based view code in views.py: from django.contrib.auth.views import LoginView from django.urls import reverse_lazy from users.forms import LoginForm class Login(LoginView): form_class = LoginForm template_name = 'users/login.html' success_url = reverse_lazy('phones:show') what can I do now? Please help me; -
how to put figure tag instead of p tag in django-ckeditor for images
Hello guys ✋ Im working on a django project I just Added ckeditor to my project. when i Added image in ckeditor it automatically insert img tag in a p tag. how to insert img tag in figure tag in django-ckeditor? thanks -
AWS EC2,NGINX, DJANGO, GUNICORN static files not found
I am currently trying to launch my django website using NGINX and GUINCORN but my static files are not being found. I am on a LINUX AMI not ubuntu which makes things a bit harder and different because I got nginx with sudo amazon-linux-extras install nginx1.12 I was looking at these tutorials http://www.threebms.com/index.php/2020/07/27/set-up-a-django-app-in-aws-with-gunicorn-nginx/ https://linuxtut.com/en/ce98f7afda7738c8cc1b/ but whenever I launch my website with gunicorn --bind 0.0.0.0:8000 myappname.wsgi it always says my static files are not found.... I have already done python manage.py collectstatic STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") This is my config file found at. sudo vi /etc/nginx/nginx.conf I dont really know if I should keep the first server part but the tutorials say just add a new one to the end # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 4096; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files … -
How to check a check box is checked with if statement in django template
I am making a registration form where I want that until the user checks the checkbox to accept the terms and conditions the registration(submit) button must be disabled. When the users check the box the button is enabled. This is the code that i have written: This is the check box <label for="agree"><input type="checkbox" id="agree" name="agree" value="checked"><span style="color: springgreen;">I AGREE, to the terms and conditions.</span></label><br> and this is the button to be in conditions <input type="submit" value="REGISTER" > please suggest me i am beginner. -
django-react cannot fetch data properly
models.py class Book(models.Model): name = models.CharField(max_length=100, unique=True) author = models.CharField(max_length=64) passcode = models.CharField(max_length=80) serializers.py class BookSerializer(serializers.ModelSerializer): class Meta: model = models.Book fields = '__all__' views.py class GetBooks(APIView): def get(self, request): books = models.Book.objects.all() data = serializers.BookSerializer(books, many=True).data return Response(data, status=status.HTTP_200_OK) urls.py urlpatterns = [ path('get-books', views.GetBooks.as_view(), name='get-books') ] Main.js import React, { Component } from 'react' export default class Main extends Component { constructor(props){ super(props) this.state = { books: '' } this.getBooks() } getBooks() { fetch('http://127.0.0.1:8000/api/get-books') // go down to see the data .then((response) => { const books = response.json() console.log(books) // go down to see the output <---- !! this.setState({ books: books }) }) } render() { return ( <div> // for book in books show book.name, book.author ... </div> ) } } Books data from (http://localhost/api/get-books) [ { "id": 1, "name": "book1", "author": "author1", "passcode": "123" }, { "id": 2, "name": "book2", "author": "auhthor2", "passcode": "123" } ] console.log(data) Promise { <state>: "pending" } <state>: "fulfilled" <value>: Array [ {…}, {…} ] 0: Object { id: 1, name: "book1", author: "author1", … } 1: Object { id: 2, name: "book2", author: "author2", … } length: 2 <prototype>: Array [] I want to … -
Skip DRF Authentication on Graphql Query
I am trying to add my existing authentication on GraphQl api in my Django project. I have done the following: class DRFAuthenticatedGraphQLView(GraphQLView): @classmethod def as_view(cls, *args, **kwargs): view = super(DRFAuthenticatedGraphQLView, cls).as_view(*args, **kwargs) view = permission_classes((IsAuthenticated,))(view) view = authentication_classes((TokenAuthentication, ))(view) view = api_view(['POST','GET'])(view) return view urlpatterns = [ path('graphql', csrf_exempt(DRFAuthenticatedGraphQLView.as_view(graphiql=True))) ] This applies authentication checks on all mutations and queries of GraphQl. I want 1 query to be without an authentication check. How can I skip that Query? -
addEventListener doesn't see change in dropdown list
I'm learning django and javascript and i have a problem witch addEventListener function. It doesn't work. Any idea what I'm doing wrong? dropbox html: <div class="ui selection dropdown" id="okej"> <input type="hidden" name="artykuł"> <i class="dropdown icon"></i> <div class="default text" id="mozeto">Wybierz artykuł</div> <div class="menu" id="produktybox"> <!-- <div class="item" data-value="0">baton</div>--> <!-- <div class="item" data-value="1">konserwa</div>--> <!-- <div class="item" data-value="2">ziemniaki</div>--> <!-- <div class="item" data-value="3">pomidory</div>--> </div> </div> myjs.js const choose=document.getElementById("okej") - - - $.ajax({ type: 'GET', url: 'produktJson/', success : function(response) { console.log('success', response) const produktyData = response.produkty produktyData.map(item=>{ const option=document.createElement('div') option.textContent = item option.setAttribute('class','item') option.setAttribute('data-value', item.nazwa) produktyDataBox.appendChild(option) }) }, error: function (response) { console.log ('error', error)}, }) Here I'm looking for a problem. choose.addEventListener('change' , e=>{ console.log('success! I see it!') }) -
Querying objects with the same value and distinguishing them in python django
I'm having trouble querying objects that have the same value from the database, i normally use the .first() and .last() to distinguish between two queries with the same value. But the program that I'm making gives me more than two objects with the same value! What should I use in my case, it's been such a headache such that I tried using .second(). But I failed! Anyone knows anything? -
Urlpatterns: category/subcategory/article-slug
Django==3.2.5 re_path(r'^.*/.*/<slug:slug>/$', Single.as_view(), name="single"), Here I'm trying to organize the following pattern: category/subcategory/article-slug. Category and subcategory are not identifying anything in this case. Only slug is meaningful. Now I try: http://localhost:8000/progr/django/1/ And get this: Page not found (404) Request Method: GET Request URL: http://localhost:8000/progr/django/1/ Using the URLconf defined in articles_project.urls, Django tried these URL patterns, in this order: admin/ ^.*/.*/<slug:slug>/$ [name='single'] articles/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, progr/django/1/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Could you help me? -
how to create a trigger with Sqlite in django
I have a "quenstion" and "comments" model I wanted to automatically delete any questions that will not be commented after 30 days of its publication -
RemovedInDjango40Warning at /accounts/log-in/ when logging in
RemovedInDjango40Warning at /accounts/log-in/ django.utils.http.is_safe_url() is deprecated in favor of url_has_allowed_host_and_scheme(). Request Method: POST Request URL: http://127.0.0.1:8000/accounts/log-in/ Django Version: 3.2.5 Exception Type: RemovedInDjango40Warning Exception Value: django.utils.http.is_safe_url() is deprecated in favor of url_has_allowed_host_and_scheme(). Exception Location: C:\Users\keyvan\Desktop\Django_ECommerce\venv\lib\site-packages\django\utils\http.py, line 329, in is_safe_url Python Executable: C:\Users\keyvan\Desktop\Django_ECommerce\venv\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\keyvan\\Desktop\\Django_ECommerce', 'C:\\Users\\keyvan\\Desktop\\Django_ECommerce', 'C:\\Program Files\\JetBrains\\PyCharm ' '2021.1\\plugins\\python\\helpers\\pycharm_display', 'C:\\Program Files\\Python38\\python38.zip', 'C:\\Program Files\\Python38\\DLLs', 'C:\\Program Files\\Python38\\lib', 'C:\\Program Files\\Python38', 'C:\\Users\\keyvan\\Desktop\\Django_ECommerce\\venv', 'C:\\Users\\keyvan\\Desktop\\Django_ECommerce\\venv\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2021.1\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] -
Materialize sidenav not working on small devices
I am using Materialize with Django. Navbar is working fine on large screens, but sidenav is not working on small screens. var elems = document.querySelectorAll('.sidenav'); var sidenavInstance = M.Sidenav.init(elems); <a href="#" data-target="mobile-nav" class="sidenav-trigger "> <i class="material-icons">menu</i></a> <ul id="slide-out" class="sidenav"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Academics</a></li> <li><a href="#">Events</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Login</a></li> </ul> This is my code snippet. I am getting the error "Cannot read property 'M_Sidenav' of null" on small screens. Could anybody tell me why am I getting this error? -
Accessing field values across multiple HTML pages with JavaScript
I am practicing Django on a dummy project and it contains several HTML pages. The pages have forms that have some numeric fields. I want to perform some calculation and logic to define some particular fields in one form by accessing fields from another form in another HTML page. I am suggested to use Local Storage to achieve that. But I'm having some difficulties there. Hope I can get some help here. Below are my templates or the HTML pages. package.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Package Form</title> </head> <body> <form action="" method="post" novalidate> <input type="hidden" name="csrfmiddlewaretoken" value="MmwcfNcoQmNheHv6HKNQXkD4ZzjuAMqu3UIejr9MSmnWom2hRXrTK5er9k2BBi8N"> <p><label for="id_package_form-date_of_admission">Date of admission:</label> <input type="text" name="package_form-date_of_admission" required id="id_package_form-date_of_admission"></p> <p><label for="id_package_form-max_fractions">Max fractions:</label> <input type="number" name="package_form-max_fractions" onfocus="mf();" onblur="tp();" required id="id_package_form-max_fractions"></p> <p><label for="id_package_form-total_package">Total package:</label> <input type="number" name="package_form-total_package" onfocus="tp();" onblur="onLoad();" step="0.01" required id="id_package_form-total_package"></p> <button type="submit" id="savebtn">Save</button> </form> <script src="/static/account/js/myjs.js"></script> <script src="/static/account/js/test.js"></script> </body> </html> Note: The total_package field itself is derived after performing logical calculations on some other fields, which you will see in the myjs.js codes. receivables.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Receivables</title> </head> <body onload="onLoad();"> <form action="" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="Ft1uZYJAKpGvw9tgCt8vZbdospwZ5XHKW1dw3CGYMpgaGO0rMGMyMWOLCaf66tp3"> <p><label for="id_discount">Discount:</label> <input type="number" … -
run wordpress and django application on same Apache server | remove Port number from django web url
I am running wordpress site on servver and I installed django application on same linode server. I am able to run my django website/application on http://ip:8000 & http://domain-name:8000. I need information on where to edit setting to remove 8000 from django application in apache. installed ssl but domain-name giving 403 forbidded error on port 443. <VirtualHost *:80> ServerAdmin webmaster@localhost ServerAlias test.factory2homes.com DocumentRoot /home/ubuntu/env/mysite ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/env/mysite/ecom/static <Directory /home/ubuntu/env/mysite/ecom/static> Require all granted </Directory> Alias /media /home/ubuntu/env/mysite/ecom/media <Directory /home/ubuntu/env/mysite/ecom/media> Require all granted </Directory> <Directory /home/ubuntu/env/mysite/ecom> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ubuntu/env/mysite/mysite/wsgi.py WSGIDaemonProcess django_app python-path=/home/ubuntu/env/mysite python-home=/home/ubuntu/env WSGIProcessGroup django_app RewriteEngine on RewriteCond %{SERVER_NAME} =test.factory2homes.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet