i m new to all this, still learning.
Now task for me is to create search bar using mongodb
What i have done so far
created the mongodb_connection.py to establish connection using pymongo
from pymongo import MongoClient
def mongosearch(title=""):
connection = MongoClient('localhost',27017)
db = connection.djangodb
collection = db.spiderCollection
title = collection.find()
for title in titles:
pprint.pprint()
created view and importing method from mongodb_connection as follows:
from django.shortcuts import render
from django.http import HttpResponse
from .mongodb_connection import mongosearch
from .models import AppModel
# Create your views here.
def search_view(request):
results = []
title_term = ""
search_term = ""
titles = AppModel.objects.all()
if 'search' in request.GET:
search_term = request.GET['search']
titles = titles.filter(title__icontains=search_term)
results = mongosearch(title=title_term)
print(results)
context={
'results':results,
'count':len(results),
'search_term':search_term,
'titles':titles
}
return render(request, 'search.html', context)
added the models.py
from django.db import models
class AppModel(models.Model):
title = models.CharField(max_length=100, primary_key=True)
desc = models.CharField(max_length=100)
url = models.CharField(max_length=100)
class Meta:
db_table = "spiderCollection"
then modified the urls
from django.urls import path, include
from . import views
from django.conf.urls import url
app_name = 'searchapp'
urlpatterns=[
path('',views.search_view, name='search_view'),
]
created html page under apps/templates
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!doctype html>
<html>
<nav class="navbar navbar-light bg-light">
<form class = "form-inline my-2 my-lg-1">
<input
class="form-control mr-sm-2"
type="search"
placeholder="Search"
aria-label="Search"
name = 'search'
value = "{{request.GET.search}}">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
<ul>
{%for i in titles %}
<li>
{{i.titles}}
</li>
{% endfor %}
</ul>
</form>
</nav>
</html>
The problem is i m getting the data fetching from mongodb. I think i m pretty close. As soon as i enter values in the search and hit submit , it errors out in the following.
Exception Type: NameError
Exception Value:
name 'titles' is not defined
Exception Location: /Users/qasimbutt/PycharmProjects/IntegratedProject/searchui/searchapp/mongodb_connection.py in mongosearch, line 9
Can someone assist me, what change can i make in the mongodb_connection.py file to get it rolling? Also please advise if anything is missing here.
As i need to fetch the data from mongodb and display it under search.
Thanks again.
Just looking at your first function, the line:
for title in titles:
references titles before it is defined anywhere. You might have meant:
titles = collection.find()
for title in titles:
Related
I have simple requirement. There is a URL that is stored in DB. I need to retrieve this URL from the DB and in my template use this URL as SRC value in an iframe.
Model.py:
from django.db import models
# Create your models here.
class DashboardLink(models.Model):
dashboard_url = models.CharField(max_length=255, unique=True)
Views.py
from django.shortcuts import render
from .models import DashboardLink
def index(request):
dashboard_url = DashboardLink.objects.all()
return render(request, 'index.html')
In Index.html I have the following code, in which I want to use the url retrieved from the DB.
index.html
<p>{{ dashboard_url.dashboard_url }}</p> ### This is to just check if the data is being fetched or not.. This too results in blank. ####
<section>
<iframe width="100%" height="700" src="{% for item in dashboard_url %} {{ item }} {% endfor %}" frameborder="0" allowfullscreen></iframe>
</section>
<br><br>
</div>
In urls.py I have the following code:
*urls.py*
path('index/', logged_in_views.index, name='index'),
When I use Inspect, I see the following
[![enter image description here][1]][1]
Can someone please help me in understanding what am I missing?
[1]: https://i.stack.imgur.com/C7Oek.png
Send context to template:
def index(request):
dashboard_url = DashboardLink.objects.all()
context = { "dashboard_url": dashboard_url}
return render(request, 'index.html', context)
You can use models.URLField for urls too
I am trying to activate the navigation bar links using context_processors.py file .Here I used a dropdown menu and some links to load contents in the same html page.Dropdown menu is for selecting the 'category' and links are used for selecting the 'genre'.'category' app is used for adding the categories via admin panel and 'genre' app is used for adding the genres.'review' app is created for display the details.In 'review' app model 'details' is created and 'category' model in the 'category' app and 'genre' model in the 'genre' app is defined in the 'details' model using ForeignKey.I want to display items in the same page(index.html) when clicks a link.Link given in dropdown menu worked properly,but when I click links other than links mentioned in dropdown menu are not working and it display's 404 error like below:
Page not found (404)
No category matches the given query.
Request Method: GET
Request URL: http://127.0.0.1:8000/drama/
Raised by: review.views.index
Using the URLconf defined in movie.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
<slug:category_slug>/ [name='index_by_category']
The current path, drama/, matched the last one.
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.
Can anyone suggest a solution for this.
HTML Page:
{% extends 'base.html' %}
{% block content %}
<nav class="navbar navbar-main navbar-expand-lg navbar-light border-bottom">
<div class="container">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#main_nav" aria-controls="main_nav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="main_nav">
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link pl-0" data-toggle="dropdown" href="#"><strong> <i class="fa fa-bars"></i>   Category</strong></a>
<div class="dropdown-menu">
<a class="dropdown-item" href="{% url 'index' %}">All Category</a>
<div class="dropdown-divider"></div>
{% for i in links %}
<a class="dropdown-item" href="{{i.get_url}}">{{i.category_name}}</a>
{% endfor %}
</div>
</li>
{% for x in genre_links %}
<li class="nav-item">
<a class="nav-link" href="{{x.get_url}}">{{x.genre_name}}</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</nav>
urls.py
from django.urls import path
from . import views
urlpatterns=[
path('',views.index,name="index"),
path('<slug:category_slug>/',views.index,name="index_by_category"),
path('<slug:genre_slug>/',views.index_by_genre,name="index_by_genre"),
]
views.py
from django.shortcuts import render,redirect,get_object_or_404
from review.models import details
from category.models import category
from genre.models import genre
def index(request,category_slug=None):
if category_slug!=None:
categories = get_object_or_404(category,slug=category_slug)
movies = details.objects.filter(Category=categories)
else:
movies = details.objects.all()
return render(request,"index.html",{'movies':movies})
def index_by_genre(request,genre_slug=None):
if genre_slug != None:
genres = get_object_or_404(genre, slug=genre_slug)
movies = details.objects.filter(Genre=genres)
else:
movies = details.objects.all()
return render(request,"index.html",{'movies':movies})
context_processors.py(category)
from .models import category
def menu_links(request):
links = category.objects.all()
return dict(links=links)
context_processors.py(genre)
from .models import genre
def menu_links(request):
genre_links = genre.objects.all()
return dict(genre_links=genre_links)
models.py(genre)
from django.db import models
from django.urls import reverse
class genre(models.Model):
genre_name = models.CharField(max_length=50,unique=True)
slug = models.SlugField(max_length=100,unique=True)
description = models.TextField(max_length=255,blank=True)
genre_image = models.ImageField(upload_to='categories',blank=True)
class Meta:
verbose_name = 'genre'
verbose_name_plural = 'genres'
def get_url(self):
return reverse('index_by_genre', args=[self.slug])
def __str__(self):
return self.genre_name
models.py(genre)
from django.db import models
from django.urls import reverse
class category(models.Model):
category_name = models.CharField(max_length=50,unique=True)
slug = models.SlugField(max_length=100,unique=True)
description = models.TextField(max_length=255,blank=True)
cat_image = models.ImageField(upload_to='categories',blank=True)
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('index_by_category',args=[self.slug])
def __str__(self):
return self.category_name
models.py(review app)
from django.db import models
from category.models import category
from genre.models import genre
class details(models.Model):
movie_name = models.CharField(max_length=250)
description = models.CharField(max_length=5000)
director = models.CharField(max_length=100)
writer = models.CharField(max_length=100)
cast = models.CharField(max_length=1000)
year_release = models.CharField(max_length=20)
time = models.CharField(max_length=30)
image = models.ImageField(upload_to='images')
Category = models.ForeignKey(category,on_delete=models.CASCADE)
Genre = models.ForeignKey(genre,on_delete=models.CASCADE)
def __str__(self):
return str(self.movie_name)
Modify urls.py file so that we can solve this issue.Remove last two paths from urls.py file.Put path('<slug:category_slug>/',views.index,name="index_by_category"),code in urls.py file of category app and path('<slug:genre_slug>/',views.index_by_genre,name="index_by_genre"), in urls.py file of genre app.Also remove 'index_by_genre' function from views.py and put it in views.py file of genre app.Similarly for 'category'.Do not forgot to give connection between app urls and project urls.
I have a Django Project I am currently working on where I want to be able to add a product to a database. I have a few fields where the user enters the details of the product and this is then sent to the create function and should save it to the Database. Unfortunately this isnt happening. This is my first use of Django so I'm not sure whats going wrong here. Here is the code I have so far:
My Index.html page:
<!DOCTYPE html>
<html>
<body>
<h2>Create product here</h2>
<div>
<form id="new_user_form" method="post">
{% csrf_token %}
<div>
<label for="name" > Name:<br></label>
<input type="text" id="name"/>
</div>
<br/>
<div>
<label for="description"> description:<br></label>
<input type="text" id="description"/>
</div>
<div>
<label for="price" > price:<br></label>
<input type="text" id="price"/>
</div>
<div>
<input type="submit" value="submit"/>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/text/javascript">
$(document).on('submit', '#new_user_form', function(e)){
e.preventDefault()
$.ajax({
type: 'POST',
url:'/user/create',
data:{
name:$('#name').val(),
description:$('#description').val(),
price:$('#price').val(),
}
success.function(){
console.log('created')
}
})
}
</script>
</html>
Here is my urls.py code:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from testapp import views
admin.autodiscover()
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('user/create', views.create_product, name='create_user')
]
My views.py code:
from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
def index(request):
return render(request, 'index.html')
#csrf_exempt
def create_product(request):
if request.method == 'POST':
name = request.POST['name']
description = request.POST['description']
price = request.POST['price']
User.objects.create(
name = name,
description = description,
price = price
)
return HttpResponse('')
And the models.py code:
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32)
desscription = models.TextField()
price = models.CharField(max_length = 128)
The problem with this is the POST request is sent when run, but the data is not saved to the database and I can't figure out why. I have followed a couple tutorials and documentation to get to this stage but can't work out what it is that's not working correctly here. Can someone have a look and let me know please?
I am working on a project i python3 Django,
it will test your knowledge from road-signs in Slovakia.
A problem occurred when i stored all 300 signs images on Imgur.
If i open firstly just image with a sign and than image inside of my HTML page everything works just fine, but i need to generate random images so i dn't know which one will be next one. Console in google chrome gives me 403 error code 'forbidden' also i can see in network tab of developer tools that it loads the image as txt/plain, which seems suspicious to me.
Can you help me somehow please?
Here is my html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static
'app_signs/style.css' %}">
</head>
<body class="question">
<form action="/question" method = "post">{% csrf_token %}
<div class="container">
<br>
<img src="{{ right_sign.signurl }}" class="main_sign" alt="FOTKA">
<br>
<h3>Aka je to znacka?</h3>
{% for sign in list%}
<p>{{ sign }}<p>
{% endfor %}
</div>
</form>
</body>
Here are views.py
from django.http import HttpResponse
from django.template import loader
from django.views.decorators.http import require_http_methods
from django.shortcuts import redirect
from app_signs.models import sign
import random
#require_http_methods(["GET", "POST"])
def question(request):
if request.method == 'GET':
rndint1 = '{:03}'.format(random.randint(1, 386))
rndint2 = '{:03}'.format(random.randint(1, 386))
rndint3 = '{:03}'.format(random.randint(1, 386))
rndint4 = '{:03}'.format(random.randint(1, 386))
right_sign = sign.objects.get(sign_id=rndint1)
fake_sign1 = sign.objects.get(sign_id=rndint2)
fake_sign2 = sign.objects.get(sign_id=rndint3)
fake_sign3 = sign.objects.get(sign_id=rndint4)
list_sign = [right_sign.sign_name,
fake_sign1.sign_name,
fake_sign2.sign_name,
fake_sign3.sign_name]
random.shuffle(list_sign, random.random)
template = loader.get_template('app_signs/question.html')
return HttpResponse(template.render({'right_sign': right_sign,
'list': list_sign}, request))
And here are models
from django.db import models
class sign(models.Model):
sign_category = models.CharField(max_length=250)
sign_id = models.CharField(max_length=4)
sign_name = models.CharField(max_length=250)
sign_url = models.CharField(max_length=250)
def __str__(self):
return self.sign_name
I finally found solution, it wasn't anything with python code. Trick was in changing 127.0.0.1 to localhost in url.
I have followed the official documentation of django tables 2 but it is not working I dont know why
views.py
from django.shortcuts import render
from django_tables2 import RequestConfig
from django.template.response import TemplateResponse
from .models import Customer
from .tables import CustomerTable
from .tables import TableView
from django_tables2.export.export import TableExport
def user_profile(request):
table= CustomerTable(Customer.objects.all())
RequestConfig(request,paginate={'per_page':15}).configure(table)
return render(request, 'home.html', {'table': table})
def TableView(request):
table = CustomerTable(Customer.objects.all())
RequestConfig(request).configure(table)
export_format = request.GET.get('_export', None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response('table.{}'.format(export_format))
return render(request, 'table.html', {
'table': table
})
my html template
{% extends 'base.html' %}
{% block content %}
{% load render_table from django_tables2 %}
{% load querystring from django_tables2 %}
<!doctype html>
<html>
<head>
<title>List of Customers</title>
</head>
<body>
{% querystring '_export'='csv' %}home
{% for format in table.export_formats %}
<a href="{% querystring '_export'=format %}">
download <code>.{{ format }}</code>
</a>
{% endfor %}
<p margin-bottom:500px;> </p>
<div style="width: 2500px; height: 600px; overflow-y: scroll;">
<div id ="users">
<input class="search" placeholder="Search" />
{% render_table table %}
{% endblock %}
</div>
</div>
</body>
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', user_profile, name="user_profile"),
url(r'^$', TableView, name="TableView"),
]
tables.py
import django_tables2 as tables
from .models import Customer
from django_tables2.export.views import ExportMixin
from .models import Customer
class CustomerTable(tables.Table):
class Meta:
model = Customer
template = 'django_tables2/bootstrap.html'
class TableView(ExportMixin, tables.SingleTableView):
table_class = CustomerTable
model = Customer
template_name = 'django_tables2/bootstrap.html'
I have a feeling something is wrong with the way I have defined urls.py but i cannot figure out what is wrong
There is a note in the documentation on exporting saying:
This example assumes you define a list of possible export formats on your table instance in attribute export_formats.
So you need to add the desired export formats to a list on your table like this:
class CustomerTable(tables.Table):
export_formats = ['csv', 'xls']
class Meta:
model = Customer
template = 'django_tables2/bootstrap.html'
You an also define the list in a context variable for your template, if you prefer that. There is no 'right' in this.
So I also banged my head against the wall a little bit on this, and then in a moment of clarity it hit me, you need wrap the query string tag like this in the template file
download as csv