Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display Predictive model graph on Django framework?
I've made a predictive model using LSTM which predicts future prices for raw materials like cotton,fibre,yarn etc. At the end of code I used matplotlib library to plot graph which displays the original prices, predicted prices and future predicted prices. This is the graph which shows future prices according to dates How do I display this graph on Django framework? Because I need to deploy this model on a web application using Django but the tutorials I've seen so far show predictive models which take user input and don't really show anything related to plots or graphs. Following is the code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime as dt from datetime import datetime import warnings warnings.simplefilter(action='ignore', category=FutureWarning) from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint, TensorBoard import os import glob import pandas import numpy from sklearn import preprocessing import numpy as np # Importing Training Set dataset_train = pd.read_csv('201222-yarn-market-price-china--034.csv1.csv') dataset_train.info() # Select features (columns) to be involved intro training and predictions cols = list(dataset_train)[1:5] # Extract dates (will be used in visualization) datelist_train = list(dataset_train.iloc[0]) datelist_train = [dt.datetime.strptime(date, '%m/%d/%Y').date() for date in datelist_train] print('Training set shape == {}'.format(dataset_train.shape)) print('All timestamps == {}'.format(len(datelist_train))) print('Featured selected: … -
'course_custom_tags' is not a registered tag library. Must be one of:
I am trying to add templatetags in using django, but i get this error after creating the template tags, i don't know if there is something i need to change in my settings.py to make this work. template.html {% extends 'base/base.html' %} {% load static %} {% load course_custom_tags %} {% block content %} course_custom_tags.py from course.models import UserCourse , Course register = template.Library() @register.simple_tag def is_enrolled(request , course): user = None if not request.user.is_authenticated: return False # i you are enrooled in this course you can watch every video user = request.user try: user_course = UserCourse.objects.get(user = user , course = course) return True except: return False ```[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/39yyT.jpg -
Python Django 'HTTPSConnection' object has no attribute 'rfind''HTTPSConnection' object has no attribute 'rfind'
I'm trying to connect an url for a payment system but I am getting this error: 'HTTPSConnection' object has no attribute 'rfind'. I checked and connection is good. url is sandbox-api.iyzipay.com and here is my code: iyzicoApiKey = data2['iyzicoApiKey'] iyzicoSecretKey = data2['iyzicoSecretKey'] url = data2['url'] options = { 'api_key': iyzicoApiKey, 'secret_key': iyzicoSecretKey, 'base_url': connection } connection = httplib.HTTPSConnection(url) request = dict([('locale', 'tr')]) request['conversationId'] = '123456789' request['subMerchantExternalId'] = subMerchantExternalId request['subMerchantType'] = 'PRIVATE_COMPANY' request['address'] = address request['taxOffice'] = taxOffice request['legalCompanyTitle'] = legalCompanyTitle request['email'] = email request['gsmNumber'] = gsmNumber request['name'] = name request['iban'] = iban request['identityNumber'] = identityNumber request['currency'] = 'TRY' sub_merchant = iyzipay.SubMerchant() sub_merchant_response = sub_merchant.create(request, options) I have tried to search but I couldn't find any info about HTTPSConnection and rfind error. Thanks in advance. -
Does django rest framework query all objects from database for a single instance?
When working with RetrieveAPIView queryset must be defined and usually it is defined as queryset = <Model>.objects.all() Why does retrieving a single instance require loading all the objects? -
I am trying to set up the environment for Django, but facing the following errors. Can someone please help me out in complete set up process of django
Fatal error in launcher: Unable to create process using '"c:\python39\python.exe" "C:\Python39\Scripts\pip.exe" install virtualenv': The system cannot find the file specified. -
on click event with JavaScript doesn't work in Django
this is the code for (cart.js) in the static/js folder var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) }) } and in the HTML file in the bottom: <button data-product="{{ product.id }}" data-action="add" class="update-cart btn btn-outline-secondary add-btn ">Add to Cart</button> and call the js in main.html <script type="text/javascript" src="{% static 'js/cart.js' %}"> </script> and I add static in the setting.py, and everything correct. and everything working well, when I try to (console.log) without a button click event... the problem is only with the button event because it doesn't work -
form.is_valid() always returns false perhaps issue with "This field is required" error
I am learning django. I am stuck with this problem. The problem is that form.is_valid() always returns false. I tried to debug and I think that the problem is because of "This field is required" error and I think that the field is file_name. I tried to resolve the issue but I am unable to do so. Just to give a context of what I am trying to do - I have created a form in which a user uploads a text file and selects a gender. In the backend I want to save the name of the text file along with the gender in a model. The purpose of doing this is because when multiple users will use the application, I should know which user selected what gender so that I can produce the desired output. Here is the link to my git repository - git repository As I already said I am new to django and some help will be appreciated. -
Why is my Django session not storing keys correctly when path converter is used in URLconf?
I'm working on the basket app of my eCommerce project and stumbled upon this error that I cannot figure out. When a user adds an item to the basket, it should store the product id and quantity in a dictionary. The quantity should be incremented if the user adds more of the same item. I've noticed that when I specify an 'int' path converter in the URLconf that this doesn't behave as expected. The second time a user adds another amount of the same item, instead of it incrementing the current value, it instead adds another key of type string to the dictionary. Form to accept desired quantity: <form action="{% url 'add_to_basket' product.id %}" method="POST"> {% csrf_token %} <div class="row justify-content-center"> <div class="col-10 col-md text-md-end"> <label class="col-form-label" for="qty_input_{{ product.id }}">Quantity:</label> </div> <div class="col-10 col-md"> <input name="quantity" type="number" class="form-control" value="1" min="1" max="99" id="qty_input_{{ product.id }}"> </div> <div class="col-10 col-md mt-2 mt-md-0"> <input type="submit" class="btn bg-red btn-outline-dark border-0" value="Add to Basket"> </div> <input type="hidden" name="redirect_url" value="{{ request.path }}"> </div> </form> View: def add_to_basket(request, product_id): if request.method == 'POST': quantity = int(request.POST['quantity']) basket = request.session.get('basket', {}) url = request.POST['redirect_url'] if product_id in basket: basket[product_id] += quantity else: basket[product_id] = quantity request.session['basket'] = basket … -
Read uploaded fasta file in django using Bio library
in index.html I used <input type="file" name="upload_file"> in views.py from Bio import SeqIO def index(request): if request.method == "POST": try: text_file = request.FILES['upload_file'] list_1, list_2 = sequence_extract_fasta(text_file) context = {'files': text_file} return render(request, 'new.html', context) except: text_file = '' context = {'files': text_file} return render(request, 'index.html') def sequence_extract_fasta(fasta_files): # Defining empty list for the Fasta id and fasta sequence variables fasta_id = [] fasta_seq = [] # opening a given fasta file using the file path with open(fasta_files, 'r') as fasta_file: print("pass") # extracting multiple data in single fasta file using biopython for record in SeqIO.parse(fasta_file, 'fasta'): # (file handle, file format) print(record.seq) # appending extracted fasta data to empty lists variables fasta_seq.append(record.seq) fasta_id.append(record.id) # returning fasta_id and fasta sequence to both call_compare_fasta and call_reference_fasta return fasta_id, fasta_seq The method sequence_extract_fasta(fasta_files) work with python. But not on the Django framework. If I can find the temporary location of the uploaded file then using the path, I may be able to call the method. Is there any efficient way to solve this? your help is highly appreciated. Thank you for your time. -
How to unit test "if request.user.is_superuser:" and "if request.method == 'POST':" using unittest framework
I've a view which is add_product. So, now I want to unit test this view using python unittest framework. In my add_product function I'm checking that if user is a superuser and if the request.method == 'POST' how can I do this? views.py def add_product(request): if request.user.is_superuser: if request.method == 'POST': product_name = request.POST['product_name'] product_category = request.POST['product_category'] product_price = request.POST['product_price'] product_photo = request.FILES['product_photo'] product_description = request.POST['product_description'] add_product = Product(product_name = product_name, category = product_category, price = product_price, description = product_description, pub_date = datetime.today(), image = product_photo) add_product.save() return render(request, 'home/home.html') else: return HttpResponse("404-Not Found") else: return render(request, 'html_view_with_error', {"error" : "PERMISSION DENIED"}) here is my try so far test_views def test_add_product(self): product = Product.objects.create( product_id = 16, product_name = "Mango", category = "Fruit", price = 350, description = "Fresh Mangoes", pub_date = "2022-02-18", ) client = Client() response = client.get(reverse('home')) self.assertEquals(response.status_code, 200) self.assertEqual(str(product), "Mango") -
IntegrityError - Exception Value: null value in column "username_id" of relation "post_comment" violates not-null constraint
I'm building out a comments section for the post app and I'm coming across this error that I can't resolve. This is arising once I submit the comment.body with the form loaded in the views. If possible I would like the authenticated user to be assigned to the username of the comment model as well as the date_added. models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) username = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.post.title} - {self.username}" def get_absolute_url(self): return reverse("new-comment", kwargs={"slug": self.post.slug}) forms.py class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "body" ] views.py def add_comment(request,slug): if request.method == "POST": form = NewCommentForm(request.POST, request.FILES) if form.is_valid(): form.instance.post_slug = {'slug': slug} form.save() messages.success(request, "Your comment was added successfully.") return redirect("food-feed") messages.info( request, "There was an problem trying to add your comment.", ) form = NewCommentForm() return render(request, "post/new_comment.html", {"new_comment_form": form}) views.py path("post/<slug:slug>/new-comment", views.add_comment, name="new-comment") -
Django ForeignKey как заменить выпадающий список на простое поле для ввода в админ панели?
Всем привет. Я новичок в Django и уже дня 4 пытаюсь найти как заменить выпадающий список ForeignKey на обычное поле для ввода в админ панели. Дело в том что, у меня если будет очень много записей о заказчиках, то создавать новые записи о заказах в админ панели будет очень не удобно через выпадающий список, а так же, мне не нужно, чтобы другим админам были видны данные о заказчиках (их номера), поэтому решил поискать информацию о замене с выпадающего списка на простое поле для ввода (в котором будут проверятся данные, существует данный заказчик или нет). Очень сильно надеюсь, что правильно описал свою проблему. Заранее спасибо!!! -
Heroku permanent database - Django project [duplicate]
I have uploaded my Django project on Heroku, However, all inserted data in my database, after being uploaded will be deleted after a while. do you have any ideas on how to have a permanent database? or any other free hosts to deploy a Django project? -
React unable to find html document while using Django Backend
I am trying to configure a react frontend with a django backend and everything is fine, it complies, it loads etc. The issue i am facing is that my react component is unable to find the actual index.html document Uncaught ReferenceError: root is not defined my react app is constructed the standard way in ./src/components/App.js //proper imports up here {react, reactDOM} export default function App(){ return ( <h1>hello world</h1> ) } root = reactDOM.createroot(document.getElementById('root)) root.render(<App />) In my index.js located in .src/index.js import App from './components/App.js' and my webpack config file points to this index.js file Yes, I have ensured there is a div with an id of root in my boilerplate HTML The django backend compiles fine, and using webpack/babel things seem to be fine on that end. Bu that error is what pops up in the chrome console upon loading. The urls and views are properly set up and any html/css I add to the page displays as expected Thank you in advance -
Django ajax update context
i want to update my template context "threedobject" my view file def threedProductCategory(request): id = request.GET['id'] todos = mProduct.objects.filter(category_id_id=id).values() return JsonResponse({"threedobject" : list(todos)}) my ajax function refresh(i){ $.ajax({ type:"GET", url: 'cpd/', data:{"id": i}, success: function (result) { threedobject = result; $.each(result.threedobject, function(item){ $(".carousel-indicators").append(item); }); } }); } i want to update my html context threedobject my html: {% for item in threedobject%} {% if foorloop.index == 0 %} <li data-target='#carousel-custom1' data-slide-to='0' class='active '> <img src='{{item.image_url.0}}' alt='' /> <p class="product-name">{{ item.name.0 }}</p> <p class="producer-name">{{ item.user_id.0 }}</p> <div class="rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star"></span> <span class="fa fa-star"></span> </div> </li> {% endif %} <li id="categoryItem" onclick=" document.getElementById('threedSelecteImg').src = '{{ item.image_url }}'; document.getElementById('threedSelecteName').innerHTML ='{{ item.name }}'; document.getElementById('threedSelecteProducer').innerHTML='{{ item.user_id.name }}'; document.getElementById('threedSelecteDescription').innerHTML='{{ item.description }}'; " data-target='#carousel-custom1' data-slide-to='1' > <img class="threedObjectsImg" src='{{item.image_url}}' alt='' /> <p id="threedObjectsName" class="product-name">{{ item.name }}</p> <p id="threedObjectsProducer" class="producer-name">{{ item.user_id.name }}</p> <div class="rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star"></span> <span class="fa fa-star"></span> </div> </li> {% endfor %} this ajax not change anythings, but this one change first image: function refresh(i){ $.ajax({ type:"GET", url: 'cpd/', data:{"id": i}, success: function (result) { threedobject = result; for (var … -
post request of the crud functionality not working in my django rest_framework app
I am trying to make a crud api using django rest_framework the get request seems to work fine for me but the post request is not working at all when I try to print the request.data it gives empty dictionary Please help me to resolve this issue views.py file from rest_framework import serializers from . models import freelancerJob from django.http import JsonResponse from .serializers import jobPostSerializer from django.views import View from django.views.decorators.csrf import csrf_exempt from rest_framework.status import HTTP_200_OK,HTTP_400_BAD_REQUEST from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.decorators import parser_classes from rest_framework.parsers import JSONParser from rest_framework import viewsets @csrf_exempt @api_view(['GET', 'POST','DELETE']) @parser_classes([JSONParser]) def jobPostView(request,format=None): if request.method == "POST": print("data",request.data) serializer = jobPostSerializer(data=request.data) print(serializer.initial_data) if serializer.is_valid(raise_exception=True): serializer.save() return JsonResponse({'data':serializer.data},status = HTTP_200_OK ) else: return Response({'status':'error','data':serializer.data},status = HTTP_400_BAD_REQUEST) if request.method == "GET": data = freelancerJob.objects.all().order_by('id') serializer = jobPostSerializer(data ,many = True) return Response({"status":'success','data':serializer.data},status = HTTP_200_OK) My serializers.py file from rest_framework import serializers from . models import freelancerJob class jobPostSerializer(serializers.HyperlinkedModelSerializer): def create(self,validated_data): return freelancerJob.object.create(**validated_data) class Meta: model = freelancerJob fields = ['title','description','skill','duration','budget','types'] my models.py file from operator import truediv from django.db import models class freelancerJob(models.Model): Job_duration = ( ('1','Less than 1 month'), ('3','1 to 3 months'), ('6','3 to 6 month'), ('12','More than 6 … -
How can I create objects in for loop in Django?
Only data coming to database is one record with one key and one value (and this is the last one from frontend). How can I send many records to my database in objects.create()? My HTML <div class="container"> <div class='element row' id='div_1'> <input class="col" type='text' placeholder='Enter key' id='key_1' name='key'> <input class="col-7" type='text' placeholder='Enter value' id='value_1' name="value">&nbsp; <span class='add col-2 btn btn-success'>+</span> </div> </div> Script so user can duplicate or remove div $(document).ready(function(){ $(".add").click(function(){ var total_element = $(".element").length; var lastid = $(".element:last").attr("id"); var split_id = lastid.split("_"); var nextindex = Number(split_id[1]) + 1; var max = 20; if(total_element < max ){ $(".element:last").after("<div class='element row' id='div_"+ nextindex +"'></div>"); $("#div_" + nextindex).append("<input class='col' name='key' type='text' placeholder='Enter key' id='key_"+ nextindex +"'>&nbsp;<input class='col-7' name='value' type='text' placeholder='Enter value' id='value_"+ nextindex +"'>&nbsp;<span id='remove_" + nextindex + "' class='remove col-2 btn btn-danger'>-</span>"); } }); $('.container').on('click','.remove',function(){ var id = this.id; var split_id = id.split("_"); var deleteindex = split_id[1]; $("#div_" + deleteindex).remove(); }); }); and Django views class NoteCreateView(views.View): def post(self, request, pk): data = request.POST note = Note.objects.create( topic = get_object_or_404(Topic, pk=pk), title = data.get('title'), summary = data.get('summary') ) Record.objects.create( key = data.get("key"), value = data.get("value"), note = note ) return redirect('platform:topic-list') -
Getting AttributeError: 'TestCalls' object has no attribute 'assertTemplateUsed' when trying to unit test views.py using unittest framework
Here is my code for unit test fruit view. But getting AttributeError test_views.py class TestViews(unittest.TestCase): def test_fruit_GET(self): client = Client() response = client.get(reverse('products:fruit')) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'products/fruit.html') views.py def fruit(request): product = Product.objects.filter(category="Fruit") n = Product.objects.filter(category="Fruit").count() params = {'product': product, 'n': n} return render(request, 'products/fruit.html', params) -
Django admin view_on_site redirect gives me extra https:// on production
view_on_site works perfect on localhost, but when I tried in production return this: https://https//expample.com//accounts/details/9/ What can i do to fix it? -
How to combine a django frontend + django REST Framework?
I already developed a whole django website (front-end + back-end) and now I would like to "decouple" the back and the front since I want to be able to link an android app to the database. Am I supposed to create two different projects: one for the REST API and one for the front? Or can I just put every thing together? In both cases, how to render the templates in the front-end views? Thank you in advance for your answers! Paul -
Secret Key in Django when upload to Github
I been following a Django course on Youtube and coding an local app. But when I commit to my repo on Github, i get a mail from GitGuardian says that Django Secret key exposed. I don't know anything about this, does this mean my account at risk or something? The app I made just by following step from the course, it just an local app run on my computer. Is there any harm to anything of mine(code, computer,...)? I am very worried now Here is the messeage i get in my mail from gitguardian -
Django not loading content into template
i have a problem with Django not loading content of the html file. I believe i did everything according to tutorial but it doesn't seem to work. When i open server and go to localhost:8000/reviews/ it shows only home.html file This is my template file ("home.html", it is in the same folder as second html file) <!Doctype html> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <div> <div class="review" id="review4"> <img style="grid-area: person;" class="img-responsive img-fluid" id="person" src="{% static 'home/images/pfp.png' %}"></img> <p style="grid-area: name;" class="h3" id="name">Daniel M.</p> <img style="grid-area: star1;" class="img-responsive img-fluid star" id="star1" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> <img style="grid-area: star2;" class="img-responsive img-fluid star" id="star2" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> <img style="grid-area: star3;" class="img-responsive img-fluid star" id="star3" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> <img style="grid-area: star4;" class="img-responsive img-fluid star" id="star4" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> <img style="grid-area: star5;" class="img-responsive img-fluid star" id="star5" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> </div> {% block content %} {% endblock content %} </div> And this is html file that i want to put into home.html ("reviews.html") {% extends 'home/home.html' %} {% block content %} <h1>Hello i am working</h1> <form id="reviews-form" method="POST"> <input type="text" name="name" id="form-name" placeholder="Tvoje meno" required> <textarea placeholder="Ako sa ti u … -
Python Django: "Post.author" must be a "User" instance error
I am trying to assign username to author field in Post model , Django spews out the following error: "Post.author" must be a "User" instance. model: class Post(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='',null=True,blank=True) image_url = models.CharField(max_length=200,default=None,null=True,blank=True) date = models.DateTimeField(default=timezone.now) content = models.TextField() author = models.ForeignKey(User, null=False, blank=False,on_delete=models.CASCADE) categories = models.ManyToManyField(Category) published = models.BooleanField() def __str__(self): return self.title view: @login_required def new_post(request): # Add a new post if request.method != 'POST': # No data submitted, create a blank form form = PostForm() else: # Post data submitted, process data form = PostForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user.username new_post.save() return redirect('elogs:posts') #Display a blank or invalid form context = {'form':form} return render(request,'elogs/new_post.html',context) form: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','content','image','image_url','published'] widgets = { 'title': forms.Textarea(attrs={'placeholder': 'Title..'}), 'content': forms.Textarea(attrs={'placeholder': 'What is on your mind?'}), 'categories': forms.TextInput() }enter code here -
FieldError at /answer/ Cannot resolve keyword 'i' into field. Choices are: add_time, answer, detail, id,
believe it or not I've been here for 4 hours trying to get this to work, so yes, I've been trying to make a question and answer site, currently trying to make an answer form so I can send in answers to the question that I am currently viewing, trying to get the id of the question so I can attach the answer into that, but I'm getting this error, I'm sure I wrote 'id' but it thinks I wrote 'i'... What? Anyway here is the traceback, please tell me what I am doing wrong, thanks. Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/answer/ Django Version: 4.0.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.humanize', 'forum', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'crispy_forms', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'vote'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/titsnium/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/titsnium/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/edit.py", line 184, in post return super().post(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/edit.py", line 153, in post return self.form_valid(form) File "/home/titsnium/Documents/eduzec/forum/views.py", line 78, in … -
do we need a package like spatie for Permissions and Roles with Django
i am new with Django, and I have been using Spatie with Laravel for a long time, my question is does I need to use something like it with Django? or even do I need to do anything about multi roles and permission with Django since the admin panel looks perfect and completed already..... Thanks