django queryset not showing accurate result (building a news app) - html

I am creating a news app using django. It consists of search by date option. When i choose the date(ex:29-11-2020) and click submit, It should take me to the news of that particular day. When i try the below code instead of showing the details it is giving me a blank page.
views.py
from django.shortcuts import render
from .models import *
from django.views.generic.detail import DetailView
from django.views.generic import ListView
def index(request):
return render(request,'newspaperapp/index.html')
class nowlist(ListView):
model = newsmodel_1
template_name = 'newspaperapp/index.html'
class newslist(DetailView):
model = newsmodel_1
template_name = 'newspaperapp/home.html'
context_object_name = 'newspaperapp'
# search by giving date in index and search date
class SearchView(ListView):
model = newsmodel_1
template_name = 'newspaperapp/search.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
if query:
postresult = newsmodel_1.objects.filter(date_published__contains=query)
result = postresult
else:
result = None
return result
urls.py
from django.urls import path
app_name = 'newspaperapp'
from .views import newslist,SearchView,nowlist
from newspaperapp import views
urlpatterns = [
path('',views.index,name='index'),
path('date/',nowlist.as_view(),name = "date"),
path('<int:pk>',newslist.as_view(),name = "home"),
path('results/', SearchView.as_view(), name='search'),
]
newspaperapp/home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>Today's Paper</p>
{{newspaperapp.date_published}}
{{newspaperapp.category}}
</body>
newspaperapp/index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- this page has search option and different categories of news -->
<!-- to create search option we write views code and continue -->
<form class="form-inline my-2 my-lg-0" method="GET" action="{% url 'newspaperapp:search' %}">
<input class="form-control mr-sm-2" type="date" placeholder="Search" aria-label="Search"
name="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
{%for newspaperapp in object_list %}
<li>{{newspaperapp.title}}
{{newspaperapp.date_published}}
{%endfor%}
</ul>
</body>
</html>
newspaperapp/search.html
{% block content %}
{% for newspaperapp in all_search_results %}
<h3></h3>
{% empty %}
<h2>No results found</h2>
{% endfor %}
{% endblock %}

Contain usually translated to LIKE in sql typically is used to search for a specified text pattern in a column.
If you want to filter date, you could convert query it to datetime object, and search the objects in that particular date range using gte and lt lookups.
from datetime import datetime, timedelta
class SearchView(ListView):
model = newsmodel_1
template_name = 'newspaperapp/search.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
# query is of type 'str', convert to datetime
start_day = datetime.fromisoformat(query)
end_day = start_day + timedelta(days=1)
if query:
postresult = newsmodel_1.objects.filter(
date_published__gte=start_day,
date_published__lt=end_day
)
result = postresult
else:
result = None
return result
Note: add more logic to handle query is None

Related

Unable to populate select option from database in Django

I am a beginner to Django and unable to populate the items from my database table to <option></option>.
From models.py:
from django.db import models
from django.db.models.fields.related import ForeignKey
# Create your models here.
class Tbl_Category(models.Model):
cat_Id = models.AutoField(primary_key=True)
cat_Name = models.CharField(max_length=20, unique=True)
# def __str__(self):
# return [self.cat_Id, self.cat_Name]
class Tbl_Item(models.Model):
item_Id = models.AutoField(primary_key=True)
item_Name = models.CharField(max_length=30, unique=True)
cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE)
item_Price = models.IntegerField()
From views.py:
from django.shortcuts import render
from orderapp.models import Tbl_Item
# Create your views here.
def displayMain(request):
return render(request,'index.html')
def ct(request):
options = Tbl_Item.objects.filter(cat_Idf=1)
context = {'alloptions' : options}
return render(request, 'index.html', context)
From index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" href="{% static 'css.css' %}">
<title>DATA COLLECTION</title>
</head>
<body>
<div class="container">
<div class="order-screen">
<div class="element">
<label for="coffee-tea">Coffee-Tea</label>
<select name="coffee-tea" id="coffee-tea">
{% for opt in alloptions %}
<option value="{{opt.item_Id}}">{{opt.item_Name}}</option>
{% endfor %}
</select>
</div>
<div class="cart-screen">CART-SCREEN</div>
</div>
</body>
</html>
I assure you that my database connection is working absolutely fine and there was no problem while running makemigrations and migrate commands. My tables contain values that I have hardcoded. Please guide me with what is wrong with my approach. Thank you.
If I understand you question correctly you want to have a dropdown for different options in a form. In Django this would be done on the model with choices
example
OWNERSHIP=[
('current owner', 'Current Owner'),
('past owner','Past Owner'),
]
class Post(models.Model):
title = models.CharField(max_length=100)
ownership = models.CharField(max_length=100, choices=OWNERSHIP)
then just render the form field as {{ form.ownership }} and it will give you a dropdown

image path is not identifiable on index.html of django3

i am following a tutorial based on django 2 and currently running version 3 of django, the problem i am facing is the identifying path of the tag on the front end of index.html, i'll post the code bellow , kindly tell me where i went wrong and any other mistakes
my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS= (os.path.join(BASE_DIR, 'static'),) #static root added (A2)
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
MEDIA_URL='/media/'
my urls.py of main project
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',include('posts.urls')),
path('user/',include('user.urls')),
path('admin/', admin.site.urls),
]+ static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
my models.py of app
class Posts(models.Model): #created this model field
def min_len(val): #this is the custom validator working
if len(val)<=9:
raise validators.ValidationError("%(val)s Must be more than 10", params={'val':val})
title=models.CharField(validators=[min_len],max_length=255) #validation list provided
content=models.TextField(validators=[min_len])
thumb_nail=models.FileField(upload_to="posts/",null=True) #file field added
class Posts_Form(forms.ModelForm): #to build a form using django and not html
class Meta: #will get data of the fields=[] only
model=Posts
fields=['title','content','thumb_nail','user','category']
views.py
def index(request):
form=Posts_Form() #created form object
data=Posts.objects.all() #retrive data from the model to display
category=Category.objects.all() #we get all data of category
if request.method=='POST':
form=Posts_Form(request.POST,request.FILES) #request.FILES for file data
if form.is_valid():
# data=Posts(
# title=request.POST['title'],
# content=request.POST['content'],
# )
form.save()
return redirect('/')
return render(request,'index.html',{'title':'Add New Post','form':form,'rows':data,'categories':category})
and my index.html
{% extends "layout.html" %}
{% load static %}
{% block content%}
{%for row in rows%}
<h2>
{{row.title}}
</h2>
<p>
{{row.content}} - <small> {{row.created_at}}-{{row.user.username}} </small>
</p>
<p><img src="{%static 'row.thumb_nail.url' %}" alt="My image" width="150"> </p>
<p>{{row.category.all|join:", "}} </p>
{%endfor%}
</div>
and my layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width , initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>
{{title}}
</title>
<!--the below line is for the css bootstrap, from cdnjs official site-->
<!--link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css"-->
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>

Having two forms in one HTML page

I wanted to have a page for both sign up and login. However I couldn't handle the two forms. Here is my code.
I was wondering myself if it is possible to give names to the forms or handle it in another way?
forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("username", "email", "password1", "password2")
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["username"].label = "Display name"
self.fields["email"].label = "Email address"
url.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url('', views.SignUp.as_view(), name="signup"),
url('', auth_views.LoginView.as_view(template_name="index.html"),name='login'),
url('', auth_views.LogoutView.as_view(), name="logout"),
]
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="container">
<h1>Login</h1>
<form method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-default">
</form>
</div>
<div class="container">
<h1>Sign Up</h1>
<form method="POST" >
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-default">
</form>
</div>
</body>
</html>
Thank You very much
I believe this post has the answer you need. Here are my thoughts on the information:
Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms. This will sometimes be a bit messy as some CBVs require a primary key and others do not, which may lead to conflicts.
Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons Django form? This is the one that I prefer as it's cleaner to implement.
Actually i want able to POST and my apologies. in short you have to use Fetch API for this

angular get json from server but cannot display columns only whole model

So my problem is i can access json data from server but i dont know how to display them properly, until now i can only display all model and i would like to display only some data.
My template
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
{% verbatim %}
<body ng-app="MyApp">
<div ng-controller="MyPerson">
<div ng-repeat="person in person">
<p>{{person}}</p>
<p>{{persons.city}}</p>
<p>{{person.city}}</p>
<p>{{person.id}}</p>
<script>
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyPerson', function($scope, $http) {
$http.get('http://127.0.0.1:8000/people/person/?format=json').
success(function(personData) {
$scope.person = personData;
});
});
</script>
</div>
</div>
{% endverbatim %}
</body>
</html>
My urls
from django.conf.urls import patterns, include, url
from people.views import *
from django.contrib import admin
from people.api import PersonResource
from tastypie.api import Api
from django.contrib.auth.decorators import login_required
person_resource = PersonResource()
urlpatterns = patterns('',
url(r'^$', IndexView.as_view(), name='home'),
url(r'^first/$', FirstView.as_view(), name='first'),
url(r'^admin/', include(admin.site.urls)),
url(r'^people/', include(person_resource.urls)),
)
My api
from people.models import Person
from tastypie.resources import ModelResource
class PersonResource(ModelResource):
"""
API Facet
"""
class Meta:
queryset = Person.objects.all()
resource_name = 'person'
My model
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
slug = models.SlugField(unique=True)
parent = models.ForeignKey('Person', blank=True, null=True)
def __unicode__(self):
return "%s" % self.name
on terminal i get
[10/Dec/2014 18:38:20] "GET / HTTP/1.1" 200 797
[10/Dec/2014 18:38:20] "GET /people/person/?format=json HTTP/1.1" 200 420
and my html is
{"limit":20,"next":null,"offset":0,"previous":null,"total_count":3}
[{"city":"Budapest","id":1,"name":"Igor","resource_uri":"/people/job/person/1/","slug":"person"},{"city":"Warszawa","id":2,"name":"Karol","resource_uri":"/people/job/person/2/","slug":"person1"},{"city":"Jerozolima","id":3,"name":"Michal","resource_uri":"/people/job/person/3/","slug":"Ima"}]
So i can access json but it works only when i make ng-repeat person in persons
but then it only display data in these {{person}}
if i add sth else for example {{person.name}} it display nothing. I would like to display everything in nice format. I work on django and use rest Tastypie
If your JSON from http://127.0.0.1:8000/people/person/?format=json is coming back as an array then you need to change your $scope.person to be $scope.persons and your ng-repeat needs to read person in persons.

Django form not being submitted

I have a Django model/view/form that is rendering correctly in the template, but it is not submitting the data that is input to the database. Any help with this would be greatly appreciated!
#models.py
from django.db import models
from django.forms import ModelForm
class UserRegistration(models.Model):
user_first = models.CharField(max_length=50)
user_last = models.CharField(max_length=50)
user_email = models.EmailField()
#user_fantasyhost = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s %s' % (self.user_first, self.user_last, self.user_email)
class RegForm(ModelForm):
class Meta:
model = UserRegistration
#views.py
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acme.dc_django.models import UserRegistration
from acme.dc_django.models import RegForm
def regPage(request, id=None):
form = RegForm(request.POST or None,
instance=id and UserRegistration.objects.get(id=id))
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/league_setup/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
#repage.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="/league/">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account"
</form><br /><br />
</body>
</HTML>
Thank you for your help,
dp
I tried your code. Your problem is that the action attribute of your html form tag is set to "/league/".
Unless reqPage url is actually "/league/", it won't work. When i changed action="/league/" to action="" as such:
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account" />
</form><br /><br />
</body>
</HTML>
The form did work:
In [3]: UserRegistration.objects.all()
Out[3]: [<UserRegistration: aoeu oeu oeu#aeou.com>]