I have a model named Search in my models.py file. I have made migrations and everything is working totally fine except one problem. In my views.py file I have created one variable called var1 which queries "search_query" field into the database, but unfortunately, it couldn't assign that variable.
Please help me how to access my model to work this line,
var1 = Search.objects.latest('search_query')
Here is my models.py file,
from django.db import models
class Search(models.Model):
search_query = models.CharField(max_length=64)
views.py file,
from django.shortcuts import render, redirect
import requests
from git_profile.forms import SearchForm
from git_profile.models import Search
def index(request):
var1 = Search.objects.latest('search_query')
EDIT:
I want to replace 'var1' with this replacement
python
user_profile = requests.get('https://api.github.com/users/{0}'.format(str(vββββar1)))
content = dict()
content['user'] = user_profile.json()
but var1 can not be replaced by replacement field and API gives me weird error
There is an useful search using boolean operator that you can use from django.db.models import Q # filter using operators '&' or '|'.
Example:
class RestaurantListView(ListView):
def get_queryset(self):
slug = self.kwargs.get("slug")
if slug:
queryset = RestaurantLocation.objects.filter(
Q(category__iexact=slug) |
Q(category__icontains=slug)
)
else:
queryset = RestaurantLocation.objects.all()
return queryset
For more information of using queryset, refer to https://docs.djangoproject.com/en/1.11/ref/models/querysets/
https://simpleisbetterthancomplex.com/tutorial/2016/11/28/how-to-filter-querysets-dynamically.html
Cheers
Henry
In your view you most create a Dictionary and assign the select variable to a property and the pass the dictionary to the view in this way:
def index(request):
var1 = Search.objects.latest('search_query').search_query
context = {'property': var1 }
return render(request, 'YOURVIEW', context)
and then access to the dictionary in the view:
{{ property.your_key}}
See more information in the Django App part 3 tutorial: https://docs.djangoproject.com/en/1.11/intro/tutorial03/
I have had a hard time understanding what you're trying to do, however these are typical use cases.
from django.shortcuts import render, redirect
import requests
from git_profile.forms import SearchForm
from git_profile.models import Search
def index(request):
var1 = Search.objects.all()
# do something with variable var1
# another example
def index(request, search_query):
# as you can notice I'm expecting the parameter search_query, so make sure that in urls.py you define it properly.
var1 = Search.objects.filter(search_query=search_query)
edit as per Klaus D.'s comment:
you're also missing a dot
def index(request):
var1 = Search.objects.latest('search_query').search_query
# do something with variable var1
Related
I want to pass data from 'About' model to html template, but I can't figure out what is going wrong.. as I am new to Django. I gave lot of time to it.. but it still remains the same:
from django.db import models
class About(models.Model):
image = models.ImageField(upload_to = 'pics')
desc = models.TextField()
views.py
from django.shortcuts import render
from .models import About
def index(request):
abt = About.objects.all()
return render(request,'home/index.html',{abt:'abt'})
html
<img src="{{abt.image}" alt="profile photo">
<p>{{abt.desc}}</p>
{abt:'abt'}
No, it's other way around.
{'abt':abt}
Label on the left, data on the right.
If you want to get a single instance you can use first method
<p>{{abt.first.desc}}</p>
or in the similar way, provide only the first object
return render(request,'home/index.html',{'abt': abt.first()})
What does it mean when we write request.session["tasks"] and assign it to something in django views? Like in the script below in the index function request.session["tasks"] = [ ],does that mean an empty list named tasks has been created for that particular session? and if so, where exactly all these session details are stored in django? and also what does cleaned_data["task"] in the add function is exactly doing in this script? I tried looking in the documentation but couldn't find any satisfactory information about this, so I'm sorry if this sounds a little stupid but I'm new to django and sometimes the syntax really confuses me,Any help is appreciated!
from django.shortcuts import render
from django import forms
from django.http import HttpResponseRedirect
from django.urls import reverse
# Create your views here.
class NewTaskForm(forms.Form):
task = forms.CharField(label = "New Task",min_length=8,max_length=16)
priority = forms.IntegerField(label="Priority",min_value=1,max_value=5)
def index(request):
if "tasks" not in request.session:
request.session["tasks"] = []
return render(request,"index.html",
{
"tasks":request.session["tasks"]
})
def add(request):
if request.method == "POST":
vari = NewTaskForm(request.POST)
if vari.is_valid():
task = vari.cleaned_data["task"]
request.session["tasks"] += [task]
return HttpResponseRedirect(reverse("index"))
else:
return render(request,"other.html",
{
"form":vari
})
return render(request,"other.html",{
"form" : NewTaskForm()
})
Yes, It means an empty list named tasks has been created for that particular session. and django stores the session data in 'django_session' table.
cleaned_data is used for validating the data.
# This line is used to pass the validated data from the form input.
task = vari.cleaned_data["task"]
I'm trying to extend a Django class providing from external library in my view in order to add some things. It's the first time I'm doing this kind of thing and I need some help.
In my external module
I have this class named EdqmThreadCreateView :
class EdqmThreadCreateView(ForumPermissionMixin, ThreadCreateView):
def __init__(self):
super(EdqmThreadCreateView, self).__init__()
self.form_class.base_fields['body'].label = 'Message'
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
initial = self.initial.copy()
# Get default topic
topic_id = self.request.GET.get('topic', None)
if topic_id:
initial['topic'] = int(topic_id)
return initial
def form_valid(self, form):
""" Save form if it is valid """
thread = form.save(self.request.user)
url_redirect = get_absolute_url(thread)
return HttpResponseRedirect(url_redirect)
This class is in urls.py file of external module :
urlpatterns = [
url(r'^forum/new', EdqmThreadCreateView.as_view(), name='forum-create-thread'),
...
]
In my django app
I would like to use the previous code, but I would like to add some things : change the url, add variables, ...
In my views.py file, I wrote a very easy example to see if my class is called :
from edqm.forum.views import EdqmThreadCreateView
class KnowxThreadCreateView(EdqmThreadCreateView):
def form_valid(self, form):
print('this is the class used')
And urls.py file :
from .views import KnowxThreadCreateView
urlpatterns = [
url(r'^forum/new', KnowxThreadCreateView.as_view(), name='forum-create-thread'),
]
If I understand the inherit process, it should work right ? But where Django select the function which will be used if 2 classes called the same url ?
It's a bit unclear for me
Quite simply, you can't have two views using the same URL. If you need separate functionality provided by a separate view, define a separate URL.
I've got a basic django-haystack SearchForm working OK, but now I'm trying to create a custom search form that includes a couple of extra fields to filter on.
I've followed the Haystack documentation on creating custom forms and views, but when I try to view the form I can only get the error:
ValueError at /search/calibration/
The view assetregister.views.calibration_search didn't return an HttpResponse object. It returned None instead.
Shouldn't basing this on SearchForm take care of returning a HttpResponse object?
forms.py
from django import forms
from haystack.forms import SearchForm
class CalibrationSearch(SearchForm):
calibration_due_before = forms.DateField(required=False)
calibration_due_after = forms.DateField(required=False)
def search(self):
#First we need to store SearchQuerySet recieved after / from any other processing that's going on
sqs = super(CalibrationSearch, self).search()
if not self.is_valid():
return self.no_query_found()
#check to see if any date filters used, if so apply filter
if self.cleaned_data['calibration_due_before']:
sqs = sqs.filter(calibration_date_next__lte=self.cleaned_data['calibration_due_before'])
if self.cleaned_data['calibration_due_after']:
sqs = sqs.filter(calibration_date_next__gte=self.cleaned_data['calibration_due_after'])
return sqs
views.py
from .forms import CalibrationSearch
from haystack.generic_views import SearchView
from haystack.query import SearchQuerySet
def calibration_search(SearchView):
template_name = 'search/search.html'
form_class = CalibrationSearch
queryset = SearchQuerySet().filter(requires_calibration=True)
def get_queryset(self):
queryset = super(calibration_search, self).get_queryset()
return queryset
urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
....
url(r'^search/calibration/', views.calibration_search, name='calibration_search'),
....
]
Haystack's SearchView is a class based view, you have to call .as_view() class method when adding a urls entry.
url(r'^search/calibration/', views.calibration_search.as_view(), name='calibration_search'),
This helped me.
"removing the "page" prefix on the search.html template did the trick, and was a good temporary solution. However, it became a problem when it was time to paginate the results. So after looking around, the solution was to use the "page_obj" prefix instead of "page" and everything works as expected. It seems the issue is that the haystack-tutorial assumes the page object is called "page", while certain versions of django its called "page_obj"? I'm sure there is a better answer - I'm just reporting my limited findings."
See this: Django-Haystack returns no results in search form
I am working on my first django project and i am having problems displayin 'categories' from my database onto a webpage as a list. I am getting the error "object has no attribute 'Name'. My code so far is:
Model:
class Category(models.model):
name = models.Charfield(max_length=128)
def __unicode__(self):
return self.Name + ": " +str(self.id)
Views:
from django.shortcuts import render_to_response, redirect
from forms.models import Form, Group, Flow, Gate, Field, Event, Category
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
def homepage (request):
CatName = Category.objects.order_by('id')
output = {
'category_name': CatName.Name,
}
return render_to_response('forms/formsummary.html', output)
HTML:
<div>{{ category_name }}</div>
Can anybody point me in the right direction?
In Django, when you use the ORM to query for objects, there are two possibilities (excluding each case returning nothing):
Query returns just one objects: if so, you queried using the get() method of the manager.
Query returns a collection: if so, you queried by using an all(), filter() or any method like those.
In this case, your query returned a collection of Category objects, you can do a couple of things about this, you can either generate a list with only the names by using a list comprehension:
cnames = [c.name for c in Category.objects.all()]
Or you can iterate the list using a for loop and do whatever you need to do with each object.
Django already orders your data by the id field, so, I guess there is no need to specify an ordering in this case.
Later, when your view is returning, you can deliver the list to your template and iterate it to extract what you need, for example.
In your view:
def get_categories(request):
categories = Category.objects.all()
context = {'categories': categories}
return render_to_response('template.html', RequestContext(request, context))
Then, in your template:
{% for c in categories %}
<p>{{c.name}}</p>
{% endfor %}
Here's some useful documentation
Django Templates
Django Querysets
Hope this helps.
It seems like case sensitive,
def__unicode__(self):
return self.Name + ": " +str(self.id)
^
name
CatName is a collection of Category instances. The CatName object does not have a name property because it is not a Category object. It contains Category objects.
you can iterate through your collection and display each categories name:
for category in CatName:
print category.name
It is good to at least read through QuerySet documentation even if you don't fully grasp it yet.
if you want just the most recent category you could do something like:
def homepage (request):
most_recent_category = Category.objects.order_by('-id')[0]
output = {
'category_name': most_recent_category.name
}
return render_to_response('forms/formsummary.html', output)