Choice field in Django registration forms look inactive, but works - python

So the thing is that I added custom user model
models.py
class CustomUserModel(AbstractUser):
pass
Morasko = "Morasko"
Piatkowo = "Piątkowo"
district_choices = [
(Morasko, "Morasko"),
(Piatkowo, "Piątkowo"),
]
district = models.CharField(max_length=15, choices=district_choices, default=district_choices[0])
Field 'district' is supposed to be a choice field with two options. Here is custom registration form I am using.
forms.py
class NewUserForm(UserCreationForm):
district = forms.ChoiceField(widget=forms.RadioSelect, choices=CustomUserModel.district_choices)
class Meta(UserCreationForm):
model = CustomUserModel
fields = ('username', 'email', 'district', 'password1', 'password2')
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.district = self.cleaned_data['district']
if commit:
user.save()
return user
My html registration file:
register.html
{% extends "map_neigh/home.html" %}
{% block content %}
<div class='container'>
<div id='inner'>
<br>
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button class="btn btn-primary" type="submit">Register</button>
</form>
<br>
<br>
If you already have an account <strong>log in.</strong>
</div>
</div>
{% endblock %}
Choice field actually works - users are saved in DB with clicked district, but it looks inactive and I have no clue why. Clicking it doesn't change the appearance, if I hove over one of options pointer doesn't change neither.
Below screenshot of the registration form.
home.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>NoFence</title>
{% load static %}
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link rel = "stylesheet" type = "text/css" href = "{% static 'style.css' %}"/>
<!--bootstrap-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--jQuery links -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<!--leaflet links -->
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol#0.65.2/dist/L.Control.Locate.min.css" />
<script src="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol#0.65.2/src/L.Control.Locate.min.js" charset="utf-8"></script>
<!--toast-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!--jquery scripts -->
<script>
</script>
</head>
<body>
<!--navigation bar-->
{% include "map_neigh/includes/navbar.html" %}
<!--user messages-->
{% include "map_neigh/includes/messaging.html" %}
{% block content %}
{% endblock %}
</body>
</html>
style.css
body {
margin:0;
padding:0;
background-color:#808080;
}
#menu_res {
position: relative;
padding-left: 15%;
font-size: 1.25vw;
}
#menu {
position: relative;
padding-left: 15%;
padding-top: 1.5vw;
padding-bottom: 0.9vw;
font-size: 1.5vw;
}
html{
scroll-behavior: smooth;
}
#inner {
width: 50%;
margin: 0 auto;
}

Try this
models.py
class CustomUserModel(AbstractUser):
Morasko = "Morasko"
Piatkowo = "Piątkowo"
district_choices = (
(Morasko, "Morasko"),
(Piatkowo, "Piątkowo"),
)
district = models.CharField(
max_length=15,
choices=district_choices,
default=Morasko)
In your forms.py, your UserCreationForm needs to be a ModelForm, or you can just directly define it like this.
forms.py
class NewUserForm(forms.ModelForm):
class Meta:
model = CustomerUserModel
fields = ('username', 'email', 'district', 'password1', 'password2')
widgets = {
'district': forms.RadioSelect,
}

Related

Django 3: ValidationError is not displayed

I recently started learning Django framework and had some problems with variable validation. When I try to output field.errors variable in html file there is no output, although when I pass error variable from create method, it outputs "errors" list (i.e. clean_number method is supposed to work) and when I fix them, list gets smaller (i.e. clean_number method does not work). Please tell me what I am doing wrong. Thanks in advance.
File create.html
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport>
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Adding a train to the list</title>
<link href="https://getbootstrap.com/docs/5.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<style>
.sidenav {
height: 100%;
width: 267px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #f2f2f2;
overflow-x: hidden;
padding-top: 50px;
}
.container {
max-width: 900px;
}
</style>
</head>
<body>
<body class="bg-light">
<header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
<a class="navbar-brand col-md-3 col-lg-2 me-0 px-3 fs-6" href="/">Home page</a>
<button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<input class="form-control form-control-dark w-100 rounded-0 border-0" type="text" placeholder="Search" aria-label="Search">
<div class="navbar-nav">
<div class="nav-item text-nowrap">
<a class="nav-link px-3"></a>
</div>
</div>
</header>
<div class="container">
<main>
<div class="row g-5">
<div class="py-5 text-center">
<h2>Add a train</h2>
<p class="lead">On this page, you need to fill in all the fields and follow the instructions.</p>
<form method="post">
<div class="row g-3">
{% csrf_token %}
{% for field in form %}
{{ field }}
<div class="alert alert-danger">
{{ field.errors }}
{% if !field.errors %}
{{ error }}
{% endif %}
</div>
{% endfor %}
<hr class="my-4">
<button class="w-100 btn btn-primary btn-lg" type="submit">Save changes</button>
</div>
</form>
</div>
</div>
</main>
</div>
</body>
</body>
</html>
File forms.py
from .models import Train
from django.forms import ModelForm, NumberInput
from django.core.exceptions import ValidationError
class TrainForm(ModelForm):
class Meta:
model = Train
fields = ["number", "amount_stops"]
widgets = {
"number": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the train number',
}),
"amount_stops": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the number of stops'
})
}
def clean_number(self):
number = self.cleaned_data['number']
if number > 100:
raise ValidationError('The number is over 100!')
return number
def clean_amount_stops(self):
amount_stops = self.cleaned_data['amount_stops']
if amount_stops > 100:
raise ValidationError('The amount of stops is over 100!')
return amount_stops
File views.py
from django.shortcuts import render, redirect
from .forms import TrainForm
def create(request):
error = ''
if request.method == 'POST':
form = TrainForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
error = form.errors
form = TrainForm()
context = {
'form': form,
'error': error
}
return render(request, 'main/create.html', context)
Changed the template, but still nothing has changed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field }}<p>
{{ field.errors }}<p>
{% endfor %}
<button type="submit">Save</button>
</form>
</body>
</html>
===========================
10/02/23: I tried to re-create the project without using the PyCharm IDE, just using Windows PowerShell, but nothing has changed, as it is not displayed and does not show(. My project creation:
Creating an AppDjango folder
In Terminal PowerShell:
-> cd D:\AppDjango\ - Navigate to Project
-> PS D:\AppDjango> python -m venv virenv
-> PS D:\AppDjango> virenv\Scripts\Activate.ps1
-> (virenv) PS D:\AppDjango> python -m pip install Django
-> (virenv) PS D:\AppDjango> django-admin startproject AppDjango
-> (virenv) PS D:\AppDjango> cd AppDjango
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py runserver
-> (virenv) PS D:\AppDjango\AppDjango> ^C (Ctrl + C) - Finish process
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py startapp MainApp
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py migrate
Next, I changed the configuration of the setting.py file:
import os <- Only added
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MainApp' <- Only added
]
...
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR,'templates'),], <- Only changed
...
},
]
I added the table to the models.py file:
from django.db import models
class Train(models.Model):
number = models.IntegerField()
amount_stops = models.IntegerField()
def __str__(self):
return str(self.number)
I created the forms.py file and added the code:
from .models import Train
from django.forms import ModelForm, NumberInput
from django.core.exceptions import ValidationError
class TrainForm(ModelForm):
class Meta:
model = Train
fields = ["number", "amount_stops"]
widgets = {
"number": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the train number',
}),
"amount_stops": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the number of stops'
})
}
def clean_number(self):
number = self.cleaned_data['number']
if number > 100:
raise ValidationError('The number is over 100!')
return number
def clean_amount_stops(self):
amount_stops = self.cleaned_data['amount_stops']
if amount_stops > 100:
raise ValidationError('The amount of stops is over 100!')
return amount_stops
I added the code to the views.py file:
from django.shortcuts import render, redirect
from .forms import TrainForm
def create(request):
errors_Main = ''
if request.method == 'POST':
form = TrainForm(request.POST)
if form.is_valid():
form.save()
else:
errors_Main = form.errors
form = TrainForm()
context = {
'form': form,
'errors_Main': errors_Main
}
return render(request, 'MainApp/create.html', context)
I created a new file D:\AppDjango\AppDjango\MainApp\urls.py and added the code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.create, name='create')
]
I also changed the file D:\AppDjango\AppDjango\AppDjango\urls.py (the one that originally generated Django):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('MainApp.urls'))
]
I created a template file .\MainApp\templates\MainApp\create.html and added code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field }}<p>
{% for error in field.errors %} <- added
{{ error }}
{% endfor %}
{% endfor %}
<button type="submit">Save</button>
</form>
</body>
</html>
Recent changes to the PowerShell Terminal:
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py makemigrations
Migrations for 'MainApp':
MainApp\migrations\0001_initial.py
- Create model Train
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py migrate
Operations to perform:
Apply all migrations: MainApp, admin, auth, contenttypes, sessions
Running migrations:
Applying MainApp.0001_initial... OK
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py runserver
Result: Still does not display errors. Can you please tell me at what stage I screwed up?
Try to use the looping syntax of showing errors so instead of only {{field.errors}} use it as following:
{% for error in field.errors %}
{{ error }}
{% endfor %}
Thank you #Sunderam Dubey for helping. I found the answer to my question. The problem was in the create method, I rewrote it a little differently (code below) and I was able to display the error text:
def create(request):
form = TrainForm()
if request.method == "POST":
form = TrainForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
return render(request, "main/create.html", {"form": form})

How to add custom CSS for form labels to Django forms?

I have a django form for which I need to increase the font size of the labels. Based on this StackOverflow discussion, what I need to do is add a CSS class and apply it to the control-label. How do I actually go about doing that?
My form is populated like so:
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
fields_to_add = {
# many fields here, but all in this format. Removed for brevity.
'purchase_order_number': forms.ChoiceField(
label="Purchase Order",
choices=purchase_order_numbers),
}
self.fields.update(fields_to_add)
self = add_classes(self)
The add_classes code is as follows:
def add_classes(self):
"""Add styling to form inputs."""
for key, value in self.fields.items():
self.fields[key].widget.attrs.update(
{'class': 'form-control', # <- this is what I expect to change
'style': 'font-size: large',}
)
return(self)
I assume I need to modify add_classes to add some form of control-label or a custom class like {'class': 'form-control control-label',, but once I do that, where do I actually specify the size of my labels? They are not specified in my HTML template.
Edit: based on the suggestion, I have created a file named customFormStyle.css with the following contents:
.form-control {
height: 50px;
background-color: red;
}
and in the HTML of my form have included a link to that CSS:
<link rel="stylesheet" type="text/css" href="/main/static/main/css/customFormStyle.css"/>
...but my form does not reflect the change.
Here is my template, for context ({{form}} is where the form is passed in, I do not have direct access to the HTML for the fields):
{% extends "main/_one_column.html" %}
{% comment %} {% load crispy_forms_tags %} {% endcomment %}
{% block maincontent %}
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="/main/static/main/css/customFormStyle.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<form action="" method="POST" class="form" enctype="multipart/form-data">
{% csrf_token %}
{{ form}}
<input class="btn btn-primary" type="submit" value="Save">
</form>
{% endblock %}
You must add a custom class to your field, then you must add a css style, it can be from a file or directly in your html.
In this case, the class is 'form-control', so the following style would suffice
<style>
.form-control {
height: 50px;
}
</style>

How can I style a django form with css?

I tried looking for the answer earlier but couldn't seem to figure out a few things. I'm creating my form in a form.py file so its a python file.
Here is my forms.py file :
class UploadForm(ModelForm):
name = forms.TextInput(attrs={'class': 'myfieldclass'})
details = forms.TextInput()
littype = forms.TextInput()
image = forms.ImageField()
class Meta:
model = info
fields = ["name", "details", "littype", "image"]
Here is my views.py function for it if it helps find the solution :
def uploadform(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
print(request.FILES)
if form.is_valid():
form.save()
redirect(home)
return render(request, 'uploadform.html', {'form': UploadForm})
To style it I thought I could do something like this which I found in another question :
class MyForm(forms.Form):
myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'}))
Except I have no idea how to link a css page to that python file. This is what I tried writing but i think it doesnt work because its meant for html but its in a python file :
<link type="text/css" rel="stylesheet" href="templates/form.css">
And so I'm just not sure how to style my form. Thanks for any answers!
Within your template you have to just import the css file in the head tag, but do ensure you load static first.
html file:
{% load static %}
<!doctype html>
<html lang="en">
<head>
# import the css file here
<link rel="stylesheet" href="{% static 'path to css file' %}">
</head>
...
</html>
Within the css file:
# Styling the class
.myfieldclass{
width: 30% !important;
height: 100px !important;
...
}
But please note that you don't have to import a css file since you can add the style tag in the head tag as well. For example:
<!doctype html>
<html lang="en">
<head>
<style type="text/css">
.myfieldclass{
width: 30% !important;
height: 100px !important;
...
}
</style>
</head>
...
</html>
You could apply css from the python file itself as well.
Approach from the python file.
# Custom way to set css styling on a form field in python code
def field_style():
styles_string = ' '
# List of what you want to add to style the field
styles_list = [
'width: 30% !important;',
'height: 100px !important;',
]
# Converting the list to a string
styles_string = styles_string.join(styles_list)
# or
# styles_string = ' '.join(styles_list)
return styles_string
class MyForm(forms.Form):
myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass', 'style': field_style()}))
# 'style': field_style() .... field_style() will return in this case 'width: 30% !important; height: 100px !important;'
Any of those should work but I do recommend doing the styling from the hmtl or css file instead.
class StocksForm(forms.Form):
stocks = forms.CharField(
label="",
widget=forms.TextInput(
attrs={
"class": "special",
"size": "40",
"label": "comment",
"placeholder": "Comma Seperated eg - Reliance, Steel, Acrysil.. ",
}
),
)
Template side
{% load static %}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="{% static '/css/cards.css' %}">
the stylesheet has got CSS
as
.special{
font-variant: small-caps;
}
This is how django will render the form with the class, and the styling class will be taken from stylesheet
Hope this helps! :)
You can just include the CSS in the template header like any other stylesheet
Thanks
My standard template uses Django block structure so I can group page-specific CSS with its page.
{% extends "base.html" %}
{% block content %}
my html ...
{% endblock %}
{% block extracss %}
{{block.super}}
<style>
... page-specific CSS
</style>
{% endblock %}
Base.html contains an empty block definition
{% block extracss %}{% endblock %}
which serves to locate the block with other site-wide CSS.

Select objects from django model based on user input

I have a large django model with about 800 objects and I want to create a view in which the user can select a certain number of those objects to pass to another view for further processing. The fact that there are so many objects of the model makes listing all the objects very unpractical, as the user would have to scroll through 800 objects.
In order to address this problem, I want to place an as-you-type search-bar in the top of the view so that the user can type the name of the objects and select them by clicking them. When the objects are selected, they should appear under the search-bar as tags that the user can remove by clicking an "x" next to each one.
When the user has made all the required selections, then they should be able to click a button and jump to the next view where those selected objects are accessible.
The model I am using can be simplified to:
class Song():
song_name = models.CharField(max_length=256)
song_author = models.CharField(max_length=256, blank=True)
song_content = models.TextField()
def __str__(self):
return self.song_name
class Meta:
ordering = ['song_order']
song_order = models.PositiveIntegerField(editable=False, db_index=True)
So far I have been able to make a view to search through the model.
mytemplate.html
<!DOCTYPE html>
{% load static %}
<html style="height: 100%;" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="preload" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" as="style" onload="this.rel='stylesheet'">
<link rel="preload" href="https://unpkg.com/bootstrap-material-design#4.1.1/dist/css/bootstrap-material-design.min.css" as="style" onload="this.rel='stylesheet'">
<link rel="stylesheet" href="{% static 'css/main.css' %}">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
</head>
<body>
{% block body_block %}
<div class="container" style="padding-bottom:40px;margin-top: 35px;">
<div class="form-group">
<label for="searchInput" class="bmd-label-floating">Search</label>
<input type="text" class="form-control" id="searchInput" oninput="filter()">
</div>
<ul class="list-group bmd-list-group-sm">
{% for song in songs %}
<div
class="list-group-item"
data-title="{{song.song_name}}"
data-author="{{song.song_author}}"
data-lyrics="{{song.song_content}}">
<h4>
{{song.song_name}}
{% if song.song_author %}
({{ song.song_author }})
{% endif %}
</h4>
</div>
{% endfor %}
</ul>
</div>
<script>
$('#searchInput').focus();
function short(s) {
let punctuationRegEx = /[.,\/#!$%\^&\*;:{}=\-_`~()]/g;
return s.replace(punctuationRegEx, '')
.toLowerCase()
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "");
}
function filter() {
let f = short($('#searchInput').val());
$('.list-group-item').each(function (index) {
if (short($(this).data('title') + "").includes(f) ||
short($(this).data('author') + "").includes(f)
) {
$(this).show();
} else {
$(this).hide();
}
});
}
</script>
{% endblock %}
</body>
</html>
views.py
class SongListView(ListView):
context_object_name = 'songs'
model = Song
template_name = "songapp/mytemplate.html"
Any ideas on how to do the selection?
I have created a part inventory program with the as you type search.
It's a complete example of ajax call for search and database.
You can modify it to show the results under the search with the X.
https://github.com/edcodes/Django-Parts-Inventory

'QuerySet' object has no attribute 'META' 500(internal server erro)

I'm trying to practice ajax in django but I got this error 'QuerySet' object has no attribute 'META'. But it's showing the data in the traceback but not in the template because of the error.How to fix this?
models.py
from django.db import models
# Create your models here.
class Profile(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
bio = models.CharField(max_length=100)
def __str__(self):
return self.name
I think it has something to do with the views but I cant figure it out.
views.py
from django.shortcuts import render
from .models import Profile
from django.http import JsonResponse
# Create your views here.
def list(request):
return render(request, 'livedata/list.html')
def getProfiles(request):
profiles = Profile.objects.all()
# print(JsonResponse({"profiles": list(profiles.values())}))
return JsonResponse({"profiles": list(profiles.values())})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.list, name='list'),
path('getProfiles', views.getProfiles, name='getProfiles')
]
index.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
{% comment %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% endcomment %}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="{% static 'js/main.js' %}" defer></script>
<title>Hello, world!</title>
</head>
<body>
{% block contents %}{% endblock contents %}
{% block scripts %}{% endblock scripts %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
{% comment %} <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> {% endcomment %}
{% comment %} <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> {% endcomment %}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
list.html
{% extends 'livedata/index.html' %}
{% block contents %}
<h1>List of live data</h1>
<ul id="display">
</ul>
{% endblock contents %}
{% block scripts %}
<script>
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: 'GET',
url: "{% url 'getProfiles' %}",
success: function (response) {
// console.log(response);
$("#display").empty();
for (var key in response.profiles) {
var temp = "<li>" + response.profiles[key].name + "</li>";
$("#display").append(temp);
}
},
error: function (response) {
alert("Error occured");
}
});
}, 1000);
});
</script>
{% endblock scripts %}
You should not name a view list, list is a builtin function that you use in other views. By defining a view named list, the list(profiles.values()) will call the view with profile.values() as the request.
Rename list to view_list for example and update the url patterns to direct to view_list instead:
def view_list(request):
return render(request, 'livedata/list.html')
def getProfiles(request):
profiles = Profile.objects.all()
# does not refer to the view &downarrow; but to the list builtin
return JsonResponse({"profiles": list(profiles.values())})
The urls.py thus looks like:
from django.urls import path
from . import views
urlpatterns = [
path('', views.view_list, name='list'),
path('getProfiles', views.getProfiles, name='getProfiles')
]

Categories

Resources