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

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')
]

Related

im having trouble Django materialize css form when a render the form i get the variable does not exist from field.html from django-materializecss-form

I'm new to Django. whenever I render the form I get "Exception has occurred: VariableDoesNotExist
Failed lookup for key [required_css_class] in " . I don't understand this error if anybody explain or tell me what I'm doing wrong will be much appreciated
thank you in advance
this is my view
def considerations(request):
if request.method == "POST":
form = B2bConsideration(request.POST)
v = form.is_valid()
if form.is_valid():
instance = form.save(commit=True)
#adding date to instance from request not in table but a good idea
#instance.date = request.date
instance.save()
return HttpResponseRedirect(reverse('b2b:TypeOfTitle'))
else:
return HttpResponse(form.errors)
else:
form = B2bConsideration()
return render(request, 'b2b/B2B_notes.html',{'form':form} )
this is my modelform
class B2bConsideration(ModelForm):
CHOICES = [('yes_title_under_name', 'yes'),('No_title_under_name','no'),]
under_name_title = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())
class Meta:
model = Consideration
fields = ['under_name_title','salvage_title','is_title_paidoff']
this is my model
under_Name_choices = [('yes_title_under_name', 'yes'),('No_title_under_name','no'),]
salvage_title_choices =[('yes_salvage_title','yes'),('no_salvage_title','no'),]
is_title_paidoff_choices = [('yes_title_paidoff', 'yes'),('no_title_paidoff','no'),]
class Consideration (models.Model):
under_name_title = models.CharField(max_length=21, choices=under_Name_choices)
salvage_title = models.CharField(max_length=18, choices=salvage_title_choices)
is_title_paidoff = models.CharField(max_length=21, choices=is_title_paidoff_choices)
here is where the error points to. this is what it said "Exception has occurred: VariableDoesNotExist
Failed lookup for key [required_css_class] in "
<label class="control-label {{ classes.label }} {% if field.field.required %}{{ form.required_css_class }}{% endif %}">{{ field.label }}</label>
this is my HTML
{% load static %}
{% load materializecss %}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Titlemax B2B</title>
{% block css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
{% endblock css %}
{% block javascript %}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
{% endblock javascript %}
<script src="{% static 'B2B_index.js' %}"></script>
<link rel="stylesheet" href="{% static 'B2B_index.css' %}">
</head>
{{ form.under_name_title.0}}
{{ form.under_name_title.1}}
{{ form|materializecss:'m6' }}
I think the problem is that you are overriding the variable "form" by passing it to your template with the line:
return render(request, 'b2b/B2B_notes.html',{'form':form} )
Try renaming your variable to something other than 'form', such as:
return render(request, 'b2b/B2B_notes.html',{'my-form':form} )
Make sure to also rename the variable in your html in the last 3 lines where you call {{ form }}

How do I fix '... is not a registered namespace' Django 2.1 error

so Im building and simple mooc plataform using Django 2.1 and Im having a problem.
Here you can find my entire project but ill describe all situation above, and here u can find a entire printscreen of django error.
So i have this project called TamerMooc, this project has 2 apps. A core app and a courses app.
This is the /courses/views.py file:
from django.shortcuts import render, get_object_or_404
from .models import Course
def index(request):
courses = Course.objects.all()
template_name = 'courses/index.html'
context = {
'courses':courses
}
return render(request, template_name, context)
def details(request, slug):
course = get_object_or_404(Course, slug=slug)
template_name = 'courses/details.html'
context = {
'course': course
}
return render(request, template_name, context)
And this is the /courses/urls.py file:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('',views.index ,name='index'),
path('<slug:slug>', views.details , name='details'),
]
And at least the /core/templates/base.html file quoted in the error file.
<!doctype html>
{% load static %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Simple MOOC - Uma simples plataforma de ensino a distância" />
<title>Tâmer MOOC</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css">
<link rel="stylesheet" href="{% static 'css/styles.css' %}" />
</head>
<body>
<div class="header">
<div class="pure-menu pure-menu-open pure-menu-fixed pure-menu-horizontal">
<a class="pure-menu-heading" href="{% url 'home' %}">TÂMER MOOC</a>
<ul>
<li class="pure-menu-selected">Início</li>
<li>Cursos</li>
<li><a href="{% url 'contact' %}"}>Contato</a></li>
</ul>
</div>
</div>
<div class = "content">
{% block content %}{% endblock %}
<div class="footer">
Tâmer MOOC - Uma simples plataforma de ensino a distância
</div>
</div>
<script src="http://yui.yahooapis.com/3.12.0/build/yui/yui-min.js"></script>
</body>
</html>
I really read a lot of questions here on stackoverflow about similar errors but cant find a solution.
I think the problem is here.
<a href=" {{ course.get_absolute_url }} "> <!--- {% url 'courses:details' course.slug %}--->
^^^^^ ^^^^
In django template, comments does not work in this way. If you want to comment out something do it like this:
{% comment %}
{% url 'courses:details' course.slug %}
{% endcomment %}
Or
{# url 'courses:details' course.slug #}
Relevant documentation can be found here.

Autocomplete search with jquery and AJAX in django webapp

I am trying to implement an autocomplete search by following this tutorial
https://medium.com/#ninajlu/django-ajax-jquery-search-autocomplete-d4b4bf6494dd
And i am failing to implement it, and i think it has something to do with my urls or the way i am putting scripts in my .html file.
My search bar is in my index view
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'KPI/style.css' %}">
<script>
$(document).ready(function(){
$("#txtSearch").autocomplete({
source: "/login/index",
minLength: 2,
open: function(){
setTimeout(function () {
$('.ui-autocomplete').css('z-index', 99);
}, 0);
}
});
});
</script>
<form id="search" method="POST" action="{% url 'kpi:search' %}">
{% csrf_token %}
<input type="text" class="form-control" id="txtSearch" name="txtSearch">
<button type="submit" class="btn btn-default btn-submit">Submit</button>
</form>
</body>
</html>
urls.py
app_name = 'kpi'
urlpatterns = [
path('login/', views.LoginView.as_view(), name='login'),
path('login/index/', views.IndexView.as_view()),
]
now in the tutorial it says to put this path url(r'^ajax_calls/search/', autocompleteModel), but it doesn't seem like the path has to be this way, so i changed the path to login/index/ and called the class view IndexView which holds the autocompleteModel like so
views.py
class IndexView(LoginRequiredMixin,TemplateView):
template_name = 'KPI/index.html'
def autocompleteModel(self,request):
if request.is_ajax():
q = request.GET.get('term', '').capitalize()
search_qs = Epic.objects.filter(name__icontains=q)
results = []
print(q)
for r in search_qs:
results.append(r.name)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return JsonResponse(data, mimetype)
Epic is the model i am searching on with the value name.
with the code i have above it doesn't do anything, and i'm hoping someone can see a flaw in it.

Rendering different templates to the same URL pattern in Django

My question is similar to Same URL in multiple views in Django, but I am not rendering templates on the basis of user_authentication, but rather on the basis of JavaScript enabled or disabled in the browser.
What I am trying to do?
I am trying to render the index.html page if JavaScript is enabled in the browser, otherwise I want to render jsDisabled.html page if it's disabled and both of the pages should be rendered on the same URL pattern, for example:
localhost:8000 should either render index.html if JavaScript is enabled in the browser or it should render jsDisabled.html page if JavaScript is disabled.
Note: I am checking if JavaScript is disabled in the browser by using the <noscript> tag which will run when JavaScript is disabled.
Here is my code so far:
base.html:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body class="noJs">
...
abc
...
<noscript>
<style type="text/css">
.noJs {
display: none;
}
</style>
<meta http-equiv="refresh" content="{% ulr 'index' 1 %}"> /* This should render jsDisabled.html page on the same URL which is 'localhost:8000' */
</noscript>
</body>
</html>
urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
...
url(r'^(?P<flag>[0-1])$', views.index, name='index'),
]
views.py:
from django.shortcuts import render
def index(request, flag):
if (flag):
return render(request, 'jsDisabled.html')
else:
return render(request, 'index.html')
Depending on your Django version you may need to specify TEMPLATE_DIR = in settings.py (in newer versions this isn't required).
Here is some helpful information on template and tag logic:
Main/templates/myapp/base.html
Main/templates/myapp/index.html
Main/templates/myapp/includes/yes_js.html
Main/templates/myapp/includes/no_js.html
base.html:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
index.html:
{% extends 'myapp/base.html' %}
{% load staticfiles %}
{% block content %}
<noscript>
{% include 'no_js.html' %}
</noscript>
{% include 'yes_js.html' %}
{% endblock %}
After a lot of debugging I finally found the solution :) And here it is:
base.html:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="noJs">
...
abc
...
</div>
<noscript>
<style type="text/css">
.noJs {
display: none;
}
</style>
{% include 'includes/jsDisabled.html' %}
</noscript>
</body>
</html>
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^articles/', include('articles.urls')),
url(r'^contact/', include('contact.urls')),
url(r'^temp/',views.temp, name="temp"),
url(r'^$', views.index, name='index'),
]
views.py:
from django.shortcuts import render
def index(request):
return render(request,'index.html')
def temp(request):
return render(request,'temp.html')
I included the include built-in template tag as {% include 'includes/jsDisabled.html' %} suggested by #noes1s by creating a folder named includes inside the templates folder and placing jsDisabled.html inside of it.

django url tag, not a valid view function or pattern name

I tried to link an anchor to another page in Django. But I get the error " Reverse for 'animals.all_animals' not found. 'animals.all_animals' is not a valid view function or pattern name."
I tried several ways to do it.. no success. I have one app called animals and Im tyring to display the list of animals in the by clicking an anchor on the homepage. I attached here my Django files.
from django.shortcuts import render, get_object_or_404
from .models import Animal
def animal_list(request):
animals = Animal.objects.all()
return render(request, 'animals/animal_list.html', {'animals': animals})
// and here is the html
{% for animal in animals %}
<h1>{{animal.species}}</h1>
<p>{{animal.description}}</p>
{% endfor %}
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.animal_list, name='all_animals'),
url(r'^(?P<pk>\d+)/$', views.animal_detail, name='all_details'),
]
{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animals Site</title>
<link href="{% static 'css/base.css'%}" rel="stylesheet">
</head>
<body>
{% block content %}
<nav>
Animal List
</nav>
<a></a><h2>I love cats!</h2>
{% endblock content %}
{% block listbar %}
<ul>
<li>Sphynx</li>
<li>Catto</li>
<li>Bengal</li>
</ul>
{% endblock listbar %}
</body>
</html>
{% block listcolor%}
<style>
h2{
font-family: 'Calibri';
color: blue;
}
</style>
{% endblock listcolor%
You need a colon not a dot in the notation:
Animal List
Or in case the included urls from your app are not namespaced:
Animal List

Categories

Resources