Display data from Django database - django

I am trying to display data from mysql database. I have already uploaded data to database using django admin:
enter image description here
This is my models.py:
from django.db import models
# Create your models here.
class Newsform(models.Model):
headline = models.CharField(max_length=50)
description = models.CharField(max_length=100, default='')
content = models.CharField(max_length=100, default='')
image = models.ImageField(upload_to='news_image', blank=True)
views.py:
from django.shortcuts import render
from blog.models import Newsform
def first(request):
return render(request, 'blog/index.html')
def show_content_from_database(request):
headline_news=Newsform.objects.all()
context = {
'headline_news': headline_news
}
return render(request, 'blog/index.html', context)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ headline_news.headline }}</h1>
<img src="{{ headline_news.image }}">
</body>
</html>
I have blank page as a result. What's wrong?

headline_news is a queryset, ie a list of all the Newsform items in the database. The queryset itself doesn't have a headline or an image, only the individual items in it do. So you need to iterate through it:
<body>
{% for headline in headline_news %}
<h1>{{ headline.headline }}</h1>
<img src="{{ headline.image.url }}">
{% endfor %}
</body>
Note also, as I show above, you need to explicitly use the .url attribute on an ImageField to get the value for the src.

the attribut url search images uploaded inside media by default folder, and you can call it using {{ headline.image.url }}

Related

django: taking user input from html, processing it and showing output in the same page

I am quite new in Django and stuck at specific point. I want to take user input from html that goes into database, process it with specific python script and return result to the same html page.
I want Users to enter score in "exam_score" line, then process that input with specific python script and then to output result to "uni_name_1_result". For now, python script that just prints 'Hello world' is enough, just want to understand the mythology of how it can be done.
Would appreciate any help.
models.py
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.EmailField(max_length=254,unique=True)
exam_score = models.FloatField(null=True, validators=[MinValueValidator(0.0),MaxValueValidator(700)])
uni_name_1 = models.CharField(max_length=254)
uni_name_1_result = models.CharField(max_length=254)
forms.py
from django import forms
from django.core import validators
from ielts_app.models import User
class NewUserForm(forms.ModelForm):
# validations can be set here
class Meta():
model = User
fields = '__all__'
views.py
from django.shortcuts import render
# from ielts_app import forms
from ielts_app.forms import NewUserForm
# from django.http import HttpResponseRedirect
def index(request):
return render(request,'ielts_app/index.html')
def users(request):
form = NewUserForm()
if request.method == 'POST':
form = NewUserForm(request.POST)
if form.is_valid():
variable:form.cleaned_data
form.save(commit=True) # to save forum data (user data), commit=True to database
# return HttpResponseRedirect('/THANKS/')
return index(request) # return back to homeage after getting user data
else:
print("ERROR!")
return render(request,'ielts_app/users.html',{'form':form})
users.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Users</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h1>Please Sign Up:</h1>
<div class="container">
<form method="POST">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class='btn btn-primary' value="Submit">
</form>
</div>
</body>
</html>
You can do following way.
from django import forms
from django.core import validators
from ielts_app.models import User
class NewUserForm(forms.ModelForm):
# validations can be set here
class Meta():
model = User
fields = ('exam_score',)
And in your user.html do this.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Users</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h1>Please Sign Up:</h1>
<div class="container">
<form method="POST">
{% for field in form %}
{{ form.as_p }}
{{ field }}
{% endfor %}
{% csrf_token %}
<input type="submit" class='btn btn-primary' value="Submit">
</form>
</div>
</body>
</html>
It is better you rename your model to some other model name as it may collide with User Model given by django.

objects.all() is not returning all items from DB

I am following an online course about Django and I am encountering a strange problem:
When I am referring to my db entry and when I am expecting to get all entries, I only receive the field that I designated to be returned as a string when I defined the class.
My files are as follow:
models.py
from django.db import models
class About_me(models.Model):
name = models.CharField(max_length=100)
position = models.CharField(max_length=100)
about = models.TextField(max_length=5000)
location = models.CharField(max_length=100)
email = models.CharField(max_length=100)
linked_in = models.CharField(max_length=100)
github = models.CharField(max_length=100)
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from .models import About_me
# Create your views here.
def cv(requests):
cv = About_me.objects.all()
return render(requests, 'cv/cv.html', {'cv': cv})
cv.html template
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>About me</title>
</head>
<body>
<h1>CV</h1>
{% for item in cv %}
<p>{{item}}</p>
{% endfor %}
</body>
</html>
I am expecting to get a list with all fields: name, position, about, etc... but I am getting only the Name and to be honest I don't understand why.
Since I am in a learning project, I would better like to know why is this happening rather than just fix it.
Thank you all in advance
<head>
<meta charset="utf-8">
<title>About me</title>
</head>
<body>
<h1>CV</h1>
{% for item in cv %}
<p>item.name}</p>
<p>item.position}</p>
....
{% endfor %}
</body>

django-autocomplete-light's suggestions displayed beyond the drop-down list

For some reason, suggestions from django-autocomplete-light 3.5.0 are displayed beyond the drop-down list, to the right (there's narrow blue rectangle visible that indicates suggestions):
I'm able to reverse the widget's url and obtain correct suggestions. Everything's working fine but rendering - when I click on this narrow rectangle, correct value appears in the edit box. I collected all the static files. I'm working on Linux 20.04 LTS, Chrome 83.0.4103.106, python 3.7.7, django 3.0.3, bootstrap 4.5.0 and font-awesome 4.7.0. Here is the code (except settings) that I wrote
forms.py
class OpinionForm(forms.ModelForm):
# user field is defined as hidden and disabled such that it couldn't be changed
user = forms.ModelChoiceField(
widget=forms.HiddenInput,
queryset=get_user_model().objects.all(),
disabled=True
)
# defining all the fields with autocomplete feature
country = forms.ModelChoiceField(
queryset=Country.objects.all(),
widget=autocomplete.ModelSelect2(url="country_autocomplete")
)
class Meta:
model = Opinion
fields = ("content",)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["country"].label = "Kraj"
self.fields["content"].label = "Treść"
models.py
class Country(models.Model):
name = models.CharField(max_length=200, null=False)
def __str__(self):
return self.name
class Opinion(models.Model):
user = models.ForeignKey(to=settings.AUTH_USER_MODEL)
content = models.TextField()
created = models.DateTimeField(auto_now=True)
urls.py
urlpatterns = [
path("add_opinion", views.CreateOpinionView.as_view(), name="add_opinion"),
path("country-autocomplete/", CountryAutocomplete.as_view(create_field="name"),
]
views.py
class CountryAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return Country.objects.none()
qs = Country.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
class CreateOpinionView(LoginRequiredMixin, CreateView):
form_class = OpinionForm
template_name = "opinions/create.html"
def get_initial(self):
"""
When our view is instantiating the form, it will pass the result of get_initial() as the 'initial'
argument and the POST data as the 'data' argument
:return:
"""
return {
"user": self.request.user.id
}
def form_valid(self, form):
"""
If a form is valid, CreateView will call form_valid.
If the form isn't valid, CreateView will re-render the template.
:param form:
:return:
"""
action = self.request.POST.get("action")
# when we want to save, we will call the original form_valid method
# the original method saves the new opinion
if action == "SAVE":
# save and redirect as usual
return super().form_valid(form)
return HttpResponseBadRequest()
create.html
{% extends "base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block title %}Dodaj opinię{% endblock %}
{% block content %}
<div class="col-md-12">
<h1>Dodaj opinię</h1>
<form method="post">
{{ form | crispy }}
{% csrf_token %}
<button class="btn btn-primary" type="submit" name="action" value="SAVE">Zapisz</button>
</form>
</div>
{% endblock %}
{% block footer %}
<script type="text/javascript" src="{% static "admin/js/vendor/jquery/jquery.js" %}"></script>
{{ form.media }}
{% endblock %}
Your code seems to work fine for me, so the error must be somewhere else, probably somewhere in your CSS.
Your code had two errors that prevented it from running though:
on_delete is a required argument for ForeignKey since Django 2.0. Are you sure about the versions you are running?
- user = models.ForeignKey(to=settings.AUTH_USER_MODEL)
+ user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
I assume this one was a copy-paste error when creating the question
- path("country-autocomplete/", CountryAutocomplete.as_view(create_field="name"),
+ path("country-autocomplete/", CountryAutocomplete.as_view(create_field="name"), name='country_autocomplete'),
Here are additional details of my setup, perhaps you can find what is different from yours:
Versions:
Django==3.0.3
django-autocomplete-light==3.5.0
django-crispy-forms==1.9.1
base.html:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock title %}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
{% block content %}
{% endblock %}
{% block footer %}
{% endblock %}
</body>
</html>
settings.py:
# ...
INSTALLED_APPS = [
# ...
'dal',
'dal_select2',
'crispy_forms',
'yourappname'
]
# ...
# (everything else left at defaults)

Django: Getting "Page not found" Error While Using Slug in URL

I am a beginner learning Django through a building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews.
Right now, I am facing an error just after I have added codes to use slug in the URLs. When I go to http://127.0.0.1:8000/index, I see this page:
When I click on "Samsung," I get this error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/index/samsung/
Raised by: PhoneReview.views.ModelView
No phone model found matching the query
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I have successfully performed migration. But still, I am facing the issue.
Here are my codes of models.py located inside PhoneReview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(unique=True, max_length=150)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
slug = models.SlugField(unique=True, max_length=150)
def __str__(self):
return self.model_name
def save(self, *args, **kwargs):
self.slug = slugify(self.model_name)
super().save(*args, **kwargs)
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
link = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are my codes of urls.py located inside PhoneReview folder:
from . import views
from django.urls import path
app_name = 'PhoneReview'
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('index/<slug:slug>/', views.ModelView.as_view(), name='modellist'),
path('details/<slug:slug>/', views.ReviewView.as_view(), name='details'),
]
Here are my codes of views.py located inside PhoneReview folder:
from django.shortcuts import render
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/index.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.DetailView):
model = PhoneModel
template_name = 'PhoneReview/phonemodel.html'
context_object_name = 'phonemodel'
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are my codes of apps.py located inside PhoneReview folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are my codes of index.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Brand List
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
<ul>
{% for brand in all_brands %}
<!-- <li>{{ brand.brand_name }}</li>-->
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of phonemodel.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
<li>{{ phonemodel.model_name }}</li>
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of details.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
<html>
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<html lang="en">
{% block title%}Details{% endblock %}
{% block content %}
<h1>This is the Details Page</h1>
<h2>Review:</h2>
<p>{{ review.review_article }}</p>
<h2>News Link:</h2>
<p>{{ review.link }}</p>
{% endblock %}
</html>
I feel that I have made a mistake on either index.html or phonemodel.html. But being a beginner, I can't catch it.
How can I fix the issue?
Update: I added the following codes in phonemodel.html to loop over phone models, as suggested by #c.grey :
<ul>
{% for model_name in all_model_name %}
<li>{{ phonemodel.model_name }}</li>
{% endfor %}
</ul>
Also, I added this line in index.html:
<li>{{ brand.brand_name }}</li>
Moreover, I added these codes in views.py:
class ModelView(generic.ListView):
template_name = 'PhoneReview/phonemodel.html'
context_object_name = 'all_model_name'
def get_queryset(self):
return PhoneModel.objects.all()
But now, I am getting this error:
django.urls.exceptions.NoReverseMatch: Reverse for 'modellist' with arguments '('',)' not found. 1 pattern(s) tried: ['index/(?P<slug>[-a-zA-Z0-9_]+)/$']
Here is the link to my project files:
https://github.com/shawnmichaels583583/phoneradar
Basically you are passing Brand model slug to get PhoneModel model data.
To get details from PhoneModel you need to pass PhoneModel slug to get data
Your error is that your link points to brand.slug (here samsung) but it seems to me that you don't have any phone model whose name is just samsung, do you?
You mix up brands and phone models

Django giving "IntegrityError NOTNULL constraint failed" when submitting django form data

I'm making a simple webapp in django where a user can log in , choose one of the given category and post an article under the chosen category. But when I submit my django form to create a new post, it throws me " IntegrityError NOTNULL constraint failed ". I searched many solutions on internet and implemented the same but still it gives me the same error.
Please help me out as to how I fix this bug??
Here are the code snippets:
Models.py
class Category(models.Model):
name = models.CharField(max_length=128,unique=True)
slug = models.SlugField()
def save(self,*args,**kwargs):
self.slug = slugify(self.name)
super(Category,self).save(*args,**kwargs)
def __unicode__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(Category,null=True,blank=True)
title = models.CharField(max_length=128,null=True,blank=True)
content = models.TextField(blank=True,null=True)
def __unicode__(self):
return self.title
views.py
def index(request):
category_list = Category.objects.all()
context = {'category_list':category_list}
return render(request,'index.html',context)
def category(request,category_name_slug):
context = {}
try:
category = get_object_or_404(Category,slug=category_name_slug)
context['category_name'] = category.name
post = Post.objects.filter(category=category)
context['post'] = post
context['category'] = category
context['category_name_slug'] = category_name_slug
except Category.DoesNotExist:
pass
return render(request,'category.html',context)
#login_required
def create_post(request,category_name_slug):
created = False
instance = get_object_or_404(Category,slug=category_name_slug)
a = Post(category=instance)
if request.method == 'POST':
form = PostForm(request.POST,instance=a)
if form.is_valid():
post = form.save(commit=False)
post.save()
created = True
else:
print form.errors
else:
form = PostForm()
context={
'form':form,
'instance':instance,
'created':created
}
return render(request,"add_post.html",context)
forms.py
from django import forms
from app.models import Post,Category,UserProfile
from django.contrib.auth.models import User
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter category")
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Category
fields = ('name',)
class PostForm(forms.ModelForm):
title = forms.CharField(max_length=128)
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Post
fields = ('title','content')
exclude = ('category',)
urls.py
from django.conf.urls import url
from django.contrib import admin
from app import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^about/$',views.about,name='about'),
url(r'^add_category/$',views.add_category,name="add_category"),
url(r'^category/(?P<category_name_slug>[-\w]+)/create_post/$',views.create_post, name='create_post'),
url(r'^category/(?P<category_name_slug>[-\w]+)/$',views.category, name='category'),
url(r'^(?P<id>\d+)/$',views.post_detail,name='post'),
url(r'^register/$',views.register,name="register"),
url(r'^login/$',views.user_login,name="login"),
url(r'^logout/$',views.user_logout,name="logout"),
url(r'^(?P<username>[-\w]+)/$',views.view_profile,name="profile"),
]
templates/add_post.html
<html>
<head>
<title>Create Post</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
<h1>Create Post under {{ instance.name }}</h1>
{% if created %}
<strong>Post created successfully</strong>
<a href='/app/'>Home</a>
{% else %}
<form id='post_form' method='post' action='/app/category/{{ instance.slug }}/create_post/' enctype='multipart/form-data'>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Create Post" />
</form>
{% endif %}
</body>
</html>
templates/category.html
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
{% if category %}
<h1>{{ category_name }}</h1>
{% if post %}
<ul>
{% for poste in post %}
<li>{{ poste.title }}</li>
{% endfor %}
</ul>
{% else %}
<strong>No posts in this Category</strong>
{% endif %}
{% else %}
<strong>No Category found with {{ category_name }}</strong>
{% endif %}
<a href='/app/category/{{ category.slug }}/create_post/'>Create post</a>
</body>
</html>
It's shows me an error at " post.save() " line in views.py.