Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why doesn't javascript work in django when css does
My script tags in django are not working, css is working. I've included MEDIA_URL and STATIC_URL in my base urls.py like so: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) The script tags only with the attributes integrity and crossorigin are working(external bootstrap cdn and jquery). But other scripts i.e. local scripts(javascript in the same file like I'll show below) and script tag with external source links (like <script src="https://js.stripe.com/v3/"></script>) are not working. The javascript code which is not working is: <button id="togglebtn" class="btn btn-warning" style="width: 100%;"> Checkout with a credit card </button> //onClick didn't work <script type="text/javascript"> function toggleDisplay() { var x = document.getElementById("collapseStripe"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } document.getElementById("togglebtn").addEventListener("click", toggleDisplay); </script> -
Build a webapp in python
I created a program in python that takes stock ticker as an input and downloads the historical data from yahoo finance and does some simulation to predict the future price. This works great in Jupyter notebook. But now i want to make this a webapp. Can someone please guide me on how to start this process. I'm very new to the web technologies, so any step by step would be of real help. Regards Raghava -
Django - Working with Forms. What does .save() do?
Hello i am new to django and this forms in django is really hard to understand. This is my code below forms.py class VideoForm(forms.Form): videoname = forms.CharField(max_length=20) videodesc = forms.CharField(max_length=20) vrform.html <form class="form-signin" method="GET" action="{% url 'vrform' %}"> {% csrf_token %} <h4 class="form-signin-heading">Add your video request here</h4> <div class="form-group"> {{formKey.videoname}} </div> <div class="form-group"> {{formKey.videodesc}} </div> <button class="btn btn-lg btn-success btn-block" type="submit">Submit</button> </form> urls.py urlpatterns = [ path('', views.homepage,name = 'home'), path('request', views.form,name = 'form'), ] views.py def vrform(request): if request.method == 'GET': formValue = VideoForm(request.GET) if formValue.is_valid(): new_req = Video(videotitle=request.GET['videoname'], videodesc=request.GET['videodesc']) new_req.save() return redirect('index') return render(request, 'videorequest/vrform.html', {'formKey': formValue}) Someone please explain me this views.py file what is this .save() method do? does it save in the database? When it encounters the line return redirect('index'). Then the next return will never execute right? It will never go to vrforms.html right? These might be silly doubts because i an new to django sorry. Please someone clear my doubts. -
How to read pandas dataframe from a postgresql db on heroku?
I have a django webapp hosted on heroku with a postgresql database. I have a file which tries to read a database table as a pandas dataframe. The code is below: rom sqlalchemy import create_engine import subprocess proc = subprocess.Popen('heroku config:get DATABASE_URL -a moviesrsfinder', stdout=subprocess.PIPE, shell=True) db_url = proc.stdout.read().decode('utf-8').strip() engine = create_engine(db_url) movies = pd.read_sql_query("SELECT * FROM movies", con=engine) ratings = pd.read_sql_query("SELECT * FROM rating", con=engine) The webapp is hosted here: https://moviesrsfinder.herokuapp.com/ Here, movies and rating are my two db tables that I need to read. But after deploying on heroku, it raises the following error : ArgumentError at / Could not parse rfc1738 URL from string '' Request Method: GET Request URL: https://moviesrsfinder.herokuapp.com/ Django Version: 2.0.6 Exception Type: ArgumentError Exception Value: Could not parse rfc1738 URL from string '' Exception Location: /app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/engine/url.py in _parse_rfc1738_args, line 254 Python Executable: /app/.heroku/python/bin/python The local vars show an error in this line: engine = create_engine(db_url) How do I fix this error? Please help me. -
Django Full example of dropdown menu populated from postgresql database
I am pretty new to django (using django 2.1.5 and python 3.7) and I can't seem to figure out how to add a dropdown menu, showing elements of one field from a table in my postgresql database. I want to ultimately allow the user to choose one element from the dropdown menu, and I will build a query with that choice and return results of that query. But I am stuck already with the dropdown menu. Here is my model in the models.py file class Locations(models.Model): gid = models.AutoField(primary_key=True) field_gid = models.BigIntegerField(db_column='__gid', blank=True, null=True) # Field renamed because it contained more than one '_' in a row. Field renamed because it started with '_'. name_location= models.CharField(unique=True, max_length=254, blank=True, null=True) x = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) y = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) z = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) geom = geomodels.PointField(srid=3912) def __str__(self): return self.name_location class Meta: managed = False db_table = 'locations' verbose_name_plural = "Locations" Here is my form in the forms.py file: from .models import Locations class LocationsForm(forms.ModelForm): locations_list = forms.ModelChoiceField(queryset=Locations.objects.all().only('name_location').order_by('name_location')) And then, in my views.py file: from .forms import LocationsForm def LocationsView(request): form = LocationsForm return render(request, 'geoportal/mforest.html', {'form': form}) And finally in my template mforest.html file: <form … -
Where is "~/.config/gspread_pandas/google secret.json" located?
people. I've just started working with Gspread-pandas. And instantly I've bumped into a problem. Documentation and all the tutorials I could find say that I should "move downloaded JSON to ~/.config/gspread_pandas/google_secret.json". But where is that folder? I can't find it anywhere. If I'm supposed to create a new folder and move it there, again, I don't know where to create it. Tried a few variants but none of them work. -
How to connect remote mongo db in django
I am trying to connect with remote mongoDB in with the help of Django in my local system it is not happening I am Using atom IDE i configured and installed djongo for mongoDB DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'Test_Jango', } } I am expecting to connect remote MongoDb with Django -
In Django www.example.com/?rcode=1 type url is not work
Hi everyone i am new in django and i am create a referal url link that fill the referal input field when link is open this is my referal url https://hp30405.pythonanywhere.com/signup/?rcode=1 but this is not fill input value where name="rcode" this is my orignal page https://hp30405.pythonanywhere.com/signup/ please tell me what is error you can use this live because my project is live -
django rest auth with Google: How to access as authenticated user?
I'm creating API using django-rest-auth. My question is how I can access as au authenticated user once I register with the website? I was successful in registering the Google account with the website from my mobile app but I still don't figure out how to access as an authenticated user. For usual token authentication, I need to Authentication: Token <token> to the header. And I tried to send like Authentication: Token <access_token>, Authentication: Token <key> but both ways doesn't work. (API returns 403) django-rest-auth 's doc doesn't have enough information. Anyone knows how to do it? -
WHAT IS DIFFERENCE BETWEEN get_user_model() ,settings.AUTH_USER_MODEL and USER in django?
WHAT IS DIFFERENCE BETWEEN get_user_model() ,settings.AUTH_USER_MODEL and User in django ? -
How to query from a many-to-many to select specific items from a db table in template django
I want to use my many-to-many table to reference which majors I want to display on my website page Model.py from django.db import models class Major(models.Model): name = models.CharField(max_length=30, db_index=True) class School(models.Model): name = models.CharField(max_length=50, db_index=True) school_Major_merge = models.ManyToManyField(Major, through='School_Major') class School_Major(models.Model): major = models.ForeignKey(Major, on_delete=models.CASCADE) school = models.ForeignKey(School, on_delete=models.CASCADE) class professor(models.Model): ProfessorIDS = models.IntegerField() ProfessorName = models.CharField(max_length=100) ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4) NumberofRatings = models.CharField(max_length=50) #delete major from the model school = models.ForeignKey(School , on_delete=models.CASCADE) major = models.ForeignKey(Major , on_delete=models.CASCADE) def __str__(self): return self.ProfessorName views.py from django.http import HttpResponse from django.shortcuts import render from .models import professor, School , def index(request): # professors = professor.objects.all() # return render(request, 'locate/index.html', {'professors': professors}) schools = School.objects.all() return render(request, 'locate/index.html', {'schools': schools}) def Major(request, Major): major_choice = professor.objects.filter(Major =Major) return render(request, 'locate/major.html', {'major_choice': major_choice}) url.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:Major>/', views.Major, name='Major') ] Basically I'm trying to figure out how to write out my views where When selecting a specific school, I would be able to use the School_Major to reference specifically what majors to display on my major section of my site, on my index.html I have the following for-loop <ul> {% for … -
Uploaded Model Data WIth DRF Data Does Not Save
I'm trying to upload a photo along with other data for my CustomerDetails model via an api endpoint. The data seems to save but, when I check my table, there is no data present. Here is my model: class CustomerDetails(models.Model): Sizes = ( ('Sizes', ( ('small', 'small'), ('medium', 'medium'), ('large', 'large'), )), ) CATEGORIES = ( ('Usage', ( ('Headache', 'Headache'), ('Backaches', 'Insomnia'), ('Menstrual Cramps & Pains','Menstrual Cramps )), ) CUSTYPE = ( ('Customer Type',( ('Athlete', 'Athlete'), ('Non-Athlete', 'Non-Athlete'), )), ) age = models.IntegerField(default="21", blank=True) nick_name = models.CharField(max_length=500, blank=True) average_order = models.FloatField(default = "0.0", blank=True) completed_orders = models.IntegerField(default = "0", blank=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer') customer_type = MultiSelectField(choices=CUSTYPE, default = CUSTYPE, max_length=100) current_selfie = models.ImageField(upload_to= 'sefies/', blank=True, default='') favorite_color = MultiSelectField(choices=TYPE, max_length=100) interested_in = MultiSelectField(choices=CATEGORIES, max_length=1000) last_signin = models.DateTimeField(default = timezone.now) liked_stores = models.ManyToManyField('Stores') liked_products = models.ManyToManyField('Product') phone = PhoneField(blank=True, help_text='Contact phone number') shares = models.IntegerField(default = "0", blank=True) signup = models.DateTimeField(default = timezone.now) def __str__(self): return self.customer.user.get_full_name() Here are my serializers & Url url(r'^api/customer/create_customer_details/$', apis.CustomerDetailViewset.as_view()), class CustomerDetailUploader(serializers.ModelSerializer): customer = CustomerDetailSerializer() current_selfie = serializers.SerializerMethodField() def get_current_selfie(self, store): request = self.context.get('request') current_selfie_url = CustomerDetails.current_selfie.url return request.build_absolute_uri(current_selfie_url) class Meta: model = CustomerDetails fields = ('nick_name', 'customer', 'current_selfie', 'favorite_color', 'interested_in', 'customer_type') Here is … -
How to store multiple images in a list in django
I am trying to use Django to store multiple user uploaded images in a list in the database. However when ever I check the product images list in the database it returns an empty list []. Any idea why? <form method="POST" enctype="multipart/form-data" id="inputform" name="form1"> {% csrf_token %} <input type="text" name="product_title" id="product_title" placeholder="Name"> <div class="row" id="row"><p id="nairasign">₦</p><input type="text" name="product_price" id="product_price" placeholder="Price"></div> <textarea type="text" name="product_description" id="product_description" placeholder="product description" ></textarea> <input type="file" name="product_images" multiple data-max-files="5" accept="image/png, image/jpeg, image/gif"> </form> def add(request): if request.method == "POST": product_title = request.POST.get("product_title") product_price = request.POST.get("product_price") product_description = request.POST.get("product_description") product_images = request.FILES.getlist("filepond") request.user.product_set.create(product_title = product_title,product_price =product_price, product_description = product_description, product_images = product_images, ) print(product_images) return render(request,"main/add.html") class product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=100, blank=True) product_price = models.CharField(max_length=30, blank=True) product_description = models.CharField(max_length=1000, blank=True) product_images = models.FileField() -
Having trouble bringing in a function from another file with Django compressor
I am currently trying to pull in a function from another file that I can use to make changes to the HTML when I click on a button (that will give the option to add event information to your own Google calendar). The person working on the code prior to me used compressor from Django for the other file and I am trying to figure out how I can invoke a function with the following code. The code is as follows: {% compress js file event-add %} <script src="{% static 'js/event/add.js' %}"></script> {% endcompress %} <script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()"> </script> When I do try, I receive the error in the console Uncaught ReferenceError: handleClientLoad is not defined at HTMLScriptElement.onload Specifically my handleClientLoad function is in my add.js file and must be used with the script for google's calendar API, but I am struggling to get the function out. The add.js file is set up as follows (shortened to just show the function I need): const AddEventForm = { googleCalendar: () => { const CLIENT_ID = 'my client id here'; const API_KEY = 'my api key here'; const SCOPES = "https://www.googleapis.com/auth/calendar.readonly"; const googleButton = document.getElementById('btn-gcalendar'); … -
After i used Django inspectdb to create models.py with chinese character in db, field names become scrambled character
My database included a lot of chinese characters in its column. After I used "python manage.py inspectdb > firstdataapp/models.py" to generate models.py, it generates lots of scrambled code that I can't execute migrate. I am barely able to find any solution related to this problem. Hopefully, if anyone can solve it? enter image description here -
why django extend base template from another app
I have two app in django make a problem the first one path: 'template/base/base.html' have the base template for this app. the second one path: 'template/base/base.html' have the base template for this app too. what is not work right when I tried to 'extends' base template for 'index page' of second app with this code {% extends 'base/base.html' %} it shows the base template of the first app and all the static file that I have included in the first app. what I have tried: I have {% block content %} in the first app when I replace it in index app it doesn't work I checked out settings of the project and Installed_app have two of them delete the cache of browser but same result change the name of base folder of the path templates/base/ I checked out views and url of the apps and it's all good and all of that didn't work I don't really know my problem can somebody help me with this? -
Deactivating user in profile
I am trying to deactivate a user's profile with a simple view that sets is_active to false when a button is pressed. However, I am getting an error that it is not setting the attribute. I am unsure what is causing this and would appreciate any help with it, thanks! views.py @login_required def deactivate(request): if request.method == 'POST': user = request.user user.is_active = False user.save() return redirect('/') return render(request, 'student/deactivate.html') HTML <form action="{% url 'student:deactivate' %}" method="POST"> {% csrf_token %} <button type="submit" name="submit" class="btn white_button msg_button">Deactivate</button> </form> -
How to skip logic and continue loop in HTML w/ Django
I have looked around stack, cant seem to find the right search phrase to even get an answer, I assume its possible if not fairly easy just cant seem to find it. Would like to have a way to skip when forloop.counter == specific numbers, I assume this is possible but haven't found anything like forloop.next {% for instance in questions %} <div> {% for field, value in instance.fields.items %} <div class="slidecontainer"> Counter: {{ forloop.counter }} {% if forloop.counter == 1 %} ???? {% endif %} <form name = "{{ field }}" id = "{{ field }}" > {{ value }}<br> <input class="slider" id="{{ field }}" input type="range" name="{{ field }}" min="0" max="10" value="5" step="1" onchange="showValue(this)" /> <span id="range">5</span> </form> </div> {% endfor %} </div> {% endfor %} Then also Similar question, I figure I could do it like this but is there a better way to write it: {% if forloop.counter == 1 or foorloop.counter == 4 or foorloop.counter == 12 or foorloop.counter == 20 %} # and more, shortened # show nothing - the parts of loop I am wanting to skip {% else %} # show what I want for the other iterations of loop {% endif … -
Why Data is Not Showing : In React Js
import React, { Component } from 'react'; import axios from 'axios'; Please help me to Display The Data in Page class ProjectDeatil extends Component { constructor(props) { super(props); this.state = { user: { name: '' } }; } . componentDidMount() { const { match: { params } } = this.props; axios.get(`http://localhost:8000/api/project/${params.pk}`) .then(({ data: user }) => { console.log( user); this.setState({"User:": user }); }); } I added her Const render() { const{ user } = this.state; return ( And then i try to display but iS not showing <div className="col-md-4 text-white animated fadeInUp delay-2s if " > <h1>{user.title}</h1> <h1> Hello Dear</h1> </div> I used Django Rest Api And i try to display user deatils by pk but i can not </div> ); } } export default ProjectDeatil -
URL/Database issue with Model Tuple?
I'm working on an app locally and created a tuple in my model - I created it as uppercase:lowercase (working from a django 1.8 tutorial when first learning) Now I created a page to order products from my model by price and the URL is returning the uppercase query in the URL and a matching query does not exist error. I went back and changed the tuple in the migrations but its still showing as all uppercase in the hyperlink. If I manually type in the url in lowercase it works fine. I'm using Django 2.0. Model class Category(models.Model): ITEM_CATEGORY_CHOICE = ( ('FOOTWEAR', 'Footwear'), ('CLOTHING', 'Clothing'), ('OUTERWEAR', 'Outerwear'), ) category = models.CharField(max_length=20, choices=ITEM_CATEGORY_CHOICE, null=True, blank=True) slug = models.SlugField(unique=True, max_length=100) def __str__(self): return self.category View def price_low_cat(request, slug): category = Category.objects.get(slug=slug) products = Product.objects.filter(cat=category).order_by('price') return render(request, 'category.html', { 'category': category, 'products': products, }) URLs path('category/<slug>/price_low_cat/', views.price_low_cat, name='price_low_cat'), HTML <a href="{% url 'price_low_cat' category %}">LOW</a> I'm expecting the url to return "/category/footwear/price_low_cat/" Instead it returns "/category/FOOTWEAR/price_low_cat/" Again, when I manually type in the former it works fine. But the link defaults to the latter if clicked. I tried to make the changes and migrate but its still the same. What can I … -
"server closed the connection unexpectedly" in long running task after trying to save stuff to db
I have django app and celery workers. One celery task is quite huge and can run for over 15 minutes. When main calculations are done and I try to save results to db I get an error: psycopg2.OperationalError: server closed the connection unexpectedly. @celery_app.task def task(param): Model1.objects.create(...) huge_calculations(param) # may run for over 15 minutes Model2.objects.create(...) # <- error here Everything that I managed to google refers to the simple solution: "update everything", but I already did, have latest versions of every package in project and still have this error. For short task (even same task w/ different params) everything works fine. I've also tried to adjust db connection timeout, but no luck :/ -
Django cannot get the current user using rest-auth/user/
I am using Django with React and I am able to login the user with http://127.0.0.1:8000/rest-auth/login/' and register user with http://127.0.0.1:8000/rest-auth/registration/ I am trying to get the current user: axios.get('http://127.0.0.1:8000/rest-auth/user/') .then(res => { console.log(res) }) But I am getting the following error: GET http://127.0.0.1:8000/rest-auth/user/ 403 (Forbidden) I also tried it on postman and I get the following: { "detail": "Authentication credentials were not provided." } Can someone show me the correct way to do it? Thanks in advance. -
Loop Through List of Dict of Lists in Python and Django
I have a queryset that returns a result like below: defaultdict(<type 'list'>, { 123: [ {'field1': 123, 'field2': 'August', 'field3': 50}, {'field1': 123, 'field2': 'September', 'field3': 25}, {'field1': 123, 'field2': 'October', 'field3': 70} ], 789: [ {'field1': 789, 'field2': 'August', 'field3': 80}, {'field1': 789, 'field2': 'September', 'field3': 22}, {'field1': 789, 'field2': 'October', 'field3': 456} ], }) I'm trying to loop through the list in a template, but I can only get the key to show, such that: {% for each in results %} {{ each }}<br> {% endfor %} Returns: 123 789 I've tried looping through results.items, and it returns nothing. I've tried using key, value, which also returns nothing. I initially thought I'd be able to have a nested for loop, and loop through each: {% for each in results %} {% for row in each %} {{ row }} {% endfor %} {% endfor %} But that returns 'int' object is not iterable I'm not sure what I'm missing, if anyone could point me in the right direction! -
success message shown on wrong page
I was trying to make this register form that redirects to the home page and shows a success message but the message isnt showing on the redirected page instead its showing me the success message on the admin panel. from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('blog-home') else: form = UserCreationForm() return render(request,'users/register.html',{'form':form}) -
Django Date Range vs postgres fields
In Django, what is the difference between, and the use cases for, "range" https://docs.djangoproject.com/en/1.11/ref/models/querysets/#range and 'daterange' https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/fields/#daterangefield It seems like the latter only for Postgres ussers, so is the former for everyone else? Is that the only difference? My specific use case is be able to take a person's date of starting and ending employment to determine if 'event' happened while they were with the company.