Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Calculator GUI with user input
I have a Django website and would like to include an app that serves as a form of a calculator, i.e. the user will make a few input specifications and click a button upon which Python will perform the calculations and present the output. I am trying to figure out how to build the front end for this as the user will have dropdowns and tickboxes, all of which need to be sent to the views as variables. Do I need to learn JavaScript for the front-end? If so, are there any sections of JavaScript I can focus on for this specific goal or do I resort to "a beginners guide to JavaScript" How do I "send" the user selection criteria to the Django view? TLDR; what I am actually trying to build: The end goal is a multiple regression tool where the user is presented with historic macro-economic data and an independent variable. The user will select one/many of the columns of data on which to regress the independent variable. There will also be a tick box for each chosen variable which indicates whether or not the user would want to transform the chosen variable. Once the selection has … -
convert django migrations to laravel migration
I have a django project with a large number of migration files. I want to convert these migration files to laravel migrations or directly import in laravel project to migrate. Migrating in django then export is not an option. Is there any tool or online convertor or something to do this ? -
Reload table data without refreshing the page in Django and JQuery
This post is based on a previous thread which seem to have a nice solution on how to reload table data in Django without refreshing the page. What it does In this way we use setInterval to make a GET AJAX request every 5 seconds a my view which renders a separate HTML file using this new context and then sends it as a response back to the main HTML table. I have modified the code to fit my needs, but I must have missed something since it is not working. If I try to navigate to the new html page itself it gets me the following error message: MultiValueDictKeyError at /myapp/more/ 'append_increment' Request Method: GET Request URL: http://localhost:8000/myapp/more/ Django Version: 2.2.6 Exception Type: MultiValueDictKeyError Exception Value: 'append_increment' I start to suspect the "int" in my view, I won't render only integers. increment = int(request.GET['append_increment']) If someone could point me in the right direction it would be highly appreciated! My main-table and JQuery script <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'get_more_tables' %}, // URL to your view that serves new info data: {'append_increment': append_increment} }) .done(function(response) { $('#_appendHere').append(response); append_increment += 1; }); }, … -
Passing data from python to html view in django framework
I have an Application where users can enter news they heard.The entered 'news headline' , 'news' , 'time' are stored in elasticsearch noSql database.The entered news items are first analysed with NLP techniques to detect and remove unethical words and again stored in elasticsearch database.After that I want to show them on a web page in an order.I completed the processing nlp task but still I cannot display all the news items on the web page.for that I'm using django framework. what I was trying to do was extract the news items from elasticsearch using a for loop and store each news item=[news headline,news,time] as a collection of lists inside a list [[],[],[]] and pass them to the html template python code, def news_items(request): newsData = [] es = Elasticsearch([{'host': 'localhost', 'port': 9200}]) for x in range(1, 101): results = es.get(index='reporter', doc_type='news', id=x) pyData1 = json.dumps(results) pyData2 = json.loads(pyData1) newsData = pyData2['_source'] pyNewsData1 = json.dumps(newsData) pyNewsData2 = json.loads(pyNewsData1) id = pyData2['_id'] headline = pyNewsData2['newsHeadline'] newsText = pyNewsData2['newsText'] date = pyNewsData2['date'] list = [id, headline, newsText, date] newsData.append(list) template = 'AppOne/news.html' return render(request, template, {'nd': newsData}) template code to access that data <ul> {% for a,b,c,d in nd %} <li>{{a}}</li> <li>{{b}}</li> … -
How to grab data that is coming from Django admin database and assign it a value that can be styled
Description I have a Django database model with articles, each has a "title" and a number of "columns". I have looped these using a for loop inside a template tag in my HTML file. The data displays well How can I grab the different column numbers and assign style attributes to them? models: from django.db import models class Article(models.Model): title = models.CharField(max_length=128) columns = models.IntegerField() views: from django.shortcuts import render from gamerNetApp1.models import Article import collections import re # Create your views here. def index(request): Article_list = Article.objects.order_by('title') Article_dict = { 'Articles': Article_list} return render(request, 'gamerNetApp1/index.html', context=Article_dict) CSS: body { padding: 20px; font: 1em Helvetica Neue, Helvetica, Arial, sans-serif; } * {box-sizing: border-box;} p { margin: 0 0 1em 0; } .container { border: 5px solid rgb(111,41,97); border-radius: .5em; padding: 10px; display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); width: 900px; } .item { padding: 10px; background-color: rgba(111,41,97,.3); border: 2px solid rgba(111,41,97,.5); width: 300px; } HTML: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static "gamerNetApp1/css/styles.css" %}"> <title>Document</title> </head> <body> {% if Articles %} {% for col in Articles %} <div class="container" id="container"> <div class="item">{{ col.title … -
Export callback if window is close on Django import/export package
I have a form post request that directs to views to export a file. I am loading a spinner on a form request if internet connection is slow, I think I needa callback if the window is closed or download export file to hide the spinner. How do I detect if I close the window or after I export a file? -
"GET / HTTP/1.1" 200 2163 "GET /static/images/ComapnyLogo.png HTTP/1.1" 404 1692
I got this error in Django 3.0 every time. Is there any issue with the static files or setting.py path is not well defined. my settings.py path: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATIC_DIRS = [ os.path.join(BASE_DIR, 'static') ] -
how to get a query from set of queries stored in a file and display the queries related to searched queries with python
'Want to take input query from use and display the queries related to that query as output'enter link description here -
How create application backend in django and create a api so that other developers can use that as well
I just started learning Django and wanted to make an application with API (probably REST) endpoints so that other developers can use it as well (like GitHub API), and I could connect it to my react app and android app. I want my backend to be on a different server and do not want to build my react app integrated with Django backend using the REST Framework. Can anyone just give me the general idea of what I need to do? P.S. Sorry in advance if my question sounds silly, I am still new to backend. -
Django Application running on Ubuntu VPS: This site can’t be reached
I am running an ubuntu 16.04 cloud VPS server. I've set up a venv and activated it, and installed django. I run the server with python3 manage.py runserver 0.0.0.0:8000 I am trying to access this application from a remote computer (not inside the same LAN); I'm trying to make the application visible to the world outside the VPS and VPLAN. When I try to access the site in my home computer broswer like: xx.xx.xxx.xxx:8000 I get the error: This site can’t be reached. http://xx.xx.xxx.xxx:8000/ is unreachable. Now I've tried a traceroute and it seems to reach the server ok. I also did sudo ufw enable sudo ufw 8000 allow sudo iptables -S | grep 8000 (and see the proper entries) If I wget localhost:8000 I get a response fine. I have tried doing all of the above as root and as another dedicated user but it makes no difference. Does anyone have any other ideas? Thanks in advance -
Scraped pictures on Django website are not loaded, only after I visit the src in another browser tab
I have scraped images with beautifull soup. The img source and href are send to my front end. However when my page is loaded, the pictures are not. When I open the src in a seperate tab, it suddenly works on my website as well. Do I have to download these image first? In order for them to show up. This is the html result in the browser <img src="//images.5movies.to/thumbs/us-and-them-2018-108200.jpg" alt="Us and Them (2018)"> This is what is in my html file in Django. <a href="{{ allContainers.2 }}"> <img src="{{ allContainers.1 }}" alt="{{ allContainers.0 }}"/></a> -
How to have single view for multiple HTML forms - Django
This is my view.So I want to keep 2 different HTML forms in same view ,But I am unable to do so beacuse whenever I add 1 form , I get the error of other on being none. def home(request): name = None if request.method == 'POST': name = request.POST.get('name') choices = request.POST.get('choices') subtest = request.POST.get('subtest') reference = request.POST.get('reference') unit = request.POST.get('unit') test = Test() test.name = name test.save() subtest = Subtest() subtest.test = Test.objects.get(name=choices) subtest.name = subtest subtest.unit = unit subtest.reference_value = reference subtest.save() # print(name) return redirect('home') return render(request,'main.html',{}) I have got 2 different forms . I didn't use django forms because I wanted to try something new. MY FIRST FORM <form method="POST"> {% csrf_token %} <div class="icon-holder"> <i data-modal-target="test-popup" class="icon-cross"></i> </div> <div class="input-group"> <input type="text" name="name" placeholder="Test name" /> </div> <div class="button-group"> <button type="submit">Submit</button> </div> </form> MY SECOND FORM <form method="POST"> {% csrf_token %} <div class="icon-holder"> <i data-modal-target="menu-test-popup" class="icon-cross"></i> </div> <div class="input-group"> <label for="test-select">Test Name:</label> <select name="choices" id="test-select"> {% for test in test %} <option value="{{test.name}}" name='choices'>{{test.name|title}}</option> {% endfor %} </select> </div> <div class="input-group"> <input type="text" name="subtest" placeholder="SubTest name" /> </div> <div class="input-group"> <input type="text" name="reference" placeholder="Reference rate" /> </div> <div class="input-group"> <input type="text" name="unit" placeholder="Unit" /> … -
How to add a feature of adding image to a post on a website?
I am developing a social networking website for my college project in Django. One of the features of any social networking website is to allow its users to write posts that have text and images. I have been trying to implement the same. First, I thought I could use a special tag in the text for an image as StackOverflow does and before the post is shown to followers the server would parse through and look for the tag and then replace it with the image. I am not really sure about this idea. Are there any other ways to do this. Is there any post-maker-like plugin available to do this? -
Not able to login after created account in django
I created login and signup pages in Django. I am not able to login using that username and password which I set up during sign up. although I am able to login using superuser username and password. I checked that data of signup is going in database. but while I am trying to login it is showing 'Please enter a correct username and password. Note that both fields may be case-sensitive.'. please help models.py- class userprofileinfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) phone = models.CharField(blank=False,max_length=10) hotel_manager = models.BooleanField() def __str__(self): # Built-in attribute of django.contrib.auth.models.User ! return self.user.username views.py- def HomePage(request): if request.user.is_authenticated: print('.................................-') print(request.user.email) return render(request,'homepage.html') else: print('not online..........................') return render(request,'homepage.html') return render(request,'homepage.html') def register(request): registered = False if request.method == 'POST': user_form = UserCreateForm(data=request.POST) profile_form = Formextends(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True return redirect('/login/') else: print(user_form.errors,profile_form.errors) else: user_form = UserCreateForm() profile_form = Formextends() return render(request,'signup.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) forms.py- class UserCreateForm(UserCreationForm): class Meta: fields = ("username","email","password1","password2") # ,"phone","hotel_manager") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" class Formextends(forms.ModelForm): class Meta(): model = userprofileinfo fields = ("phone","hotel_manager") settings.py- """ … -
Django Signals - creating folder on model create
I got a model where I would like to create a folder when a model is created: The model: class Drive(models.Model): user = models.ManyToManyField(User) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) path = models.CharField(max_length=150, editable=False, default='C:/Users/User/Desktop/Python/RavNet/media/storage/drives/{}'.format(str(id))) def save(self): super().save() I am trying to use signals, but I must admit this is my first ever attempt at making a signal not following a tutorial on point, and even after reading the documentation I am having a tough time. from django.db.models.signals import post_save from django.dispatch import receiver from .models import Drive import os @receiver(post_save, sender=Drive) def create_drive(sender, instance, created, **kwargs): if created: os.mkdir(Drive.path) Nothing happens when I create a new drive model via the django admin. I have tested out my code in the shell and using a placeholder path (C:/Users/User/Desktop/Python/RavNet/media/storage/drives/test) that I know works in the signal in a try to debug, and have gotten as far as realising I am having two issues. The first: When calling the Drive.path in the shell, I am getting the path: 'C:/Users/User/Desktop/Python/RavNet/media/storage/drives/<django.db.models.fields.UUIDField>' Instead of a path with the actual id as I hoped for. How do I solve this? Secondly, my signal isn't working. It's like it isn't getting called. What am I doing wrong? -
authenticate() returns None for User in system when using self.client.post()
So I'm currently working on redoing a project I did when I was new to Django. This time I'd like to ensure I'm using tests for practice and getting to know Django better. My issue is that I have a User that I know is in the system, as I have ogged in as them before, but when I run a test using self.client.post(), it returns None. I have triple checked spelling of username and password along with copy-paste the working strings in the func test and still nothing. Here is the test in question def test_login_authenticates_users(self): response = self.client.post('/', {'username' : 'TestUser', 'password' : 'password'}) self.assertRedirects(response, '/') # IDK why this line fails self.assertNotEqual(None, authenticate(username='Test.User', password='Usetheforceluke')) response = self.client.post('/', {'username' : 'Test.User', 'password' : 'Usetheforceluke'}) self.assertRedirects(response, '/home') Here is the functional test that works: from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import unittest class NewTeacher(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_teacher_adds_a_new_class(self): # The MCSP Department has a webpage used for all of the assignments # A teacher decides to go to the MSCP homepage to manage their classes self.browser.get('http://localhost:8000') # The title mentions MCSP in the title self.assertIn('MCSP', self.browser.title) # They then … -
Python Django beginner Projects
I work on an e-commerce website with the help of Django. and I'm a beginner in Django The following image provides a table of my database. It helps to add a product Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs. Request to guide me on what to do. -
django base.html doesnt exist
This is my file tree this is my error this is views.py def signup(request): proj = project.objects.all() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'Homepage/Projects.html', {'form': form,"project":proj}) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('projects/', Homepage.views.signup, name='projects') ] my settings.py html did i miss something? -
In Django admin show parent level and sort it
Django==3.0.2 class LevelOne(models.Model): ... class LevelTwoAux(models.Model): parent_level = models.ForeignKey(LevelOne, verbose_name="Level 1", on_delete=models.CASCADE) class LevelTwo(models.Model): parent_level = models.ForeignKey(LevelTwoAux, verbose_name="Level 2 aux.", on_delete=models.CASCADE) utm_suffix = models.CharField(max_length=4, choices=UTM_SUFFIXES) Example of content: Level 1: table Level 2 aux: computer table Level 2: computer table_TR computer table_COMP computer table_INFO In Django admin for Level 2 I'd like to: 1) Show Level 1 in a separate column. 2) Sort by a) Level 1 b) Level 2 inside level 1. Like this: Level 1 |Level 2 table |computer table_TR table |computer table_COMP table |computer table_INFO Could you help me cope with this task? -
AWS, django, postgresql : OperationalError could not connect to server: Connection timed out
I tried deploy my webapp with django. I made RDS to use postgresql DB server and open all port inbound / outbound of the EC2 instance. but when I try 'eb deploy', error log say: OperationalError could not connect to server: Connection timed out Is the server running on host "~~~instance name~~~" (172...~~ip address~~) and accepting TCP/IP connections on port 5432? I don't know what is the problem. could anybody kindly help me? -
Django - Getting 405 error when submitting contact form
My Html contact form <form id="contact-form" method="post" action="{% url 'index' %}"> {% csrf_token %} <div class="messages"></div> <div class="controls"> <div class="row"> <div class="col-md-6"> <div class="form-group wow fadeInDown" data-wow-delay="0.2s"> <input id="form_name" type="text" name="name" class="form-control" placeholder="Enter your full name *" required="required" data-error="Fullname is required."> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-6"> <div class="form-group wow fadeInDown" data-wow-delay="0.4s"> <input id="form_email" type="email" name="email" class="form-control" placeholder="Enter your email *" required="required" data-error="Valid email is required."> <div class="help-block with-errors"></div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group wow fadeInUp" data-wow-delay="0.6s"> <textarea id="form_message" name="message" class="form-control" placeholder="Your Message *" rows="4" required="required" data-error="Leave a message for me"></textarea> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-12"> <button class="btn btn-send" type="submit">Send message</button> </div> </div> </div> </form> urls.py from django.urls import path from .views import HomeTemplateView urlpatterns = [ path('', HomeTemplateView.as_view(), name="index") ] views.py, I defined my HomeTemplate view class with a method index that is handling my contact form from django.shortcuts import render from django.views.generic import TemplateView from .models import * from django.core.mail import send_mail from django.conf import settings class HomeTemplateView(TemplateView): template_name = 'home.html' # override get context date method def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['about'] = About.objects.first() context['services'] = Service.objects.all() context['works'] = RecentWork.objects.all() context['clients'] = Client.objects.all() return context def index(self, request): if … -
websocket onmessage - no connection - if received data equals to / consumers.py - django
New into websockets, searched but cannot find the answer. I send the message with the amount to the server and want to receive it back to update current amount of items. Hope somebody could help. No idea how to meet properly the 'cart_data' in msgData condition. While opening the page console returns onclose function, but after clicking the button sendMessage function returns an appropriate data. part of the template: <div> <a class="amountButton" name="decrease_button"> <button type="button">-</button> </a> <input id="id_amount" class="amountNumber" type="number" name="amount" value="{{ item.quantity }}" min="1" max="{{ item.auction.amount }}" required> <a class="amountButton" name="increase_button"> <button type="button>+</button> </a> </div> websocket.js: var amountbutton = document.getElementsByClassName('amountButton'); var message_cart; webSocket.onopen = sendMessage; webSocket.onmessage = receiveMessage; function receiveMessage(e) { var msgData = JSON.parse(e.data); console.log("msgData: " + msgData); //console ignores the whole line if ('auction_data' in msgData) { //some data, but never entered } else if ('cart_data' in msgData) { //some data, but never entered } }; function sendMessage() { for(let i = 0; i < amountbutton.length; i++) { //some on-click function, results updating message_cart variable webSocket.send(message_cart); //on chrome console shows the alert that WebSocket is already in CLOSING or CLOSED state. console.log(message_cart); //returns correct value } } consumers.py //not debugging in terminal at all def cart_data(self, event): … -
How to create relations of tree nodes efficiently in Django?
I have model Relation, that connects ancestor with all its descendants: class Relation(models.Model): ancestor = models.ForeignKey('Node') descendant = models.ForeignKey('Node') # Number of edges between ancestor and descendant power = IntegerField() And model Node: class Node(models.Model): ...some data... def save(self, parent, *args, **kwargs): self.create_relations(parent) return super().save(*args, **kwargs) I need to efficiently create relations between new node and ancestors. I managed to write the next function: def create_relations(self, parent): relations_of_parent = Relation.objects.filter(descendant=parent).values_list('ancestor', 'power') relations = [] for ancestor, power in relations_of_parent: relations.append(Relation(ancestor=ancestor, descendant=self, power=power + 1)) relations.append(Relation(ancestor=parent, descendant=self, power=1)) Relation.objects.bulk_create(relations) It would be good if there's only one hit database. Is there the way? -
Should I be using Django for this?
It is very possible that the answer to this question is simply “rather use Flask”, but I am hoping I can get a good enough excuse to actually get it working in Django. TLDR - Basic overview of the statistical model pre-Django: I built a model in R which I am busy porting over to Python. The model is a financial model that analyses past behaviour of client payments in order to estimate future expected losses & repayment. The model performs a number of data imports from an existing SQL database which itself gets populated by the company’s source system. The SQL database is ever growing and contains thousands of tables with loads of financial, historic, client data. The model imports what it needs and then we perform a bit of gymnastics in order to obtain a few bespoke parameters (i.e. we calibrate the model). Once all this is done, we apply the parameters to the latest set of loans in order to estimate the aforementioned forecasts. Purpose of the app: The main purpose of the web app is to “white box” the model. Clients were complaining that they have no feel for the numbers and would like to see … -
value too long for type character varying(255) SQLite3 to Postgres Django
I have switched from using sqlite3 to Postgres for my Django app. I have run these commands to get all my data from the sqlite3 database and I wanted to add it to the Postgres database: python manage.py dumpdata > db.json python manage.py loaddata db.json Then I got this error: Could not load database.Object(pk=XXXXXXXXXX): value too long for type character varying(255) In my models.py, the max_length is set to 10 and the value of the primary key is 10. Here is how I set the primary key for that object's model: models.CharField(max_length=10, unique=True, primary_key=True) Why I am getting that error? I have many other threads about this issue but I haven't yet found an answer that solved my issue.