I found a code that the urls in django can contain a model, so it can display a db values directly to html, but when i tried it, i got some error in the urls because this code still using patterns, is it possible doing this thing in a newer django?
The Url
from django.views.generic import ListView
from django.conf.urls import patterns, url
urlpatterns = patterns("myapp.views",
url(r'^dreamreals/', ListView.as_view(
template_name = "dreamreal_list.html")),
model = Dreamreal, context_object_name = ”dreamreals_objects” ,)
The HTML
{% extends "main_template.html" %}
{% block content %}
Dreamreals:<p>
{% for dr in object_list %}
{{dr.name}}</p>
{% endfor %}
{% endblock %}
I'm pretty sure all you've entered are kwargs of ListView.as_view() method.
So instead of doing
ListView.as_view(
template_name = "dreamreal_list.html")),
model = Dreamreal, context_object_name = ”dreamreals_objects” ,)
Which is actually syntaxly incorrect, do :
ListView.as_view(
template_name = "dreamreal_list.html",
model = Dreamreal,
context_object_name = ”dreamreals_objects”
)
Second error, you're setting the context_object_name to dreamreals_objects, but in your template you're iterating over object_list.
But this method is not really "pretty" and you should really make a views.py with your views and then the urls.py should only care about making a route.
As pointed in comments, django 2.1+ no longer use urlpatterns but path : https://docs.djangoproject.com/en/2.1/topics/http/urls/#example
Related
I am writing a simple app to track sales leads based on the Django tutorial "Writing your first Django app" (https://docs.djangoproject.com/en/4.0/intro/tutorial01/). Everything works well except for displaying a ListView of the existing leads.
Here are the relevant python snippets:
Leads/models.py
class Leads(models.Model):
id = models.IntegerField(primary_key=True)
last = models.CharField(max_length=32)
first = models.CharField(max_length=32)
config/urls.py
urlpatterns = [
# Django admin
path('admin/', admin.site.urls),
# User management
path('accounts/', include('allauth.urls')),
# Local apps
path('leads/', include('leads.urls'))
leads/urls.py
app_name = 'leads'
urlpatterns = [
path('', LeadsListView.as_view(), name='list'),
path('<int:pk>/', LeadsDetailView.as_view(), name='detail'),
]
leads/views.py
class LeadsListView(ListView):
model = Leads
template_name = 'leads/list.html'
context_object_name = 'leads_list'
def get_queryset(self):
return Leads.objects.order_by('id')
class LeadsDetailView(DetailView):
model = Leads
template_name = 'leads/detail.html'
The link in the 'home.html' template, which displays a menu option correctly:
Leads
And finally, the 'list.html' template that does not display at all. Instead of showing the list of leads, it remains on the home page.
{% block content %}
{% for lead in lead_list %}
<div class="lead-entry">
<h2>{{ lead.fname }} {{ lead.lname }}</h2>
</div>
{% endfor %}
{% endblock content %}
I'm missing something fundamental here....
There are some minor mistakes such as:
Issue
The context_object_name='leads_list, and you have defined in your template file as lead_list, missed the s.
Your Model field's name is first and last, not fname and lname.
Solution:
Try this out in your template:
{% block content %}
{% for lead in leads_list %}
<div class="lead-entry">
<h2>{{ lead.first }} {{ lead.last }}</h2>
</div>
{% endfor %}
{% endblock content %}
I have changed lead.fname to lead.first and lead.lname to lead.last and also add s to lead_list, it is now leads_list.
Note: Models in django doesn't require its name in plural form, it would be better if you only give name model name Lead rather than Leads, as django itself adds s as the suffix.
Note: If you are overriding the default AutoField generated by django which is id, so you must override it with AutoField[django-doc] rather than making IntegerField primary key.
I am creating a stock portfolio app. The user has a list of stocks each of which has a link which looks something like 'http://127.0.0.1:8000/search/symbol=TSLA'. What I want to do is pass the stock symbol 'TSLA' to one of my views and simply print that string on the next page (for now).
What I have done so far (did not include it in the code below) is to simply have some method in my SearchPageView called get_symbol and I tried to get the url from there and in my search.html template, I tried accessing that via {{ view.get_symbol }}. But this displays nothing.
My set-up:
views.py:
class SearchPageView(TemplateView):
template_name = 'search.html'
urls.py:
from django.urls import path, re_path
from .views import SearchPageView
urlpatterns = [
path('search/<string>', SearchPageView.as_view(), name='search_stock'),
]
search.html:
{% extends 'base.html' %}
{% block content %}
{% endblock content %}
I know there's nothing above, all i'm asking for is how to pass the string 'TSLA' to my view then to 'search.html' then I can do what I need to do with it. I appreciate any help.
Change your urls.py by this
path('search/<symbol>', SearchPageView.as_view(), name='search_stock'),
In views.py
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
class SearchPageView(ListView):
template_name = 'your_template.html'
def get_queryset(self):
self.publisher = get_object_or_404(YOUR_MODEL_NAME, name=self.kwargs['symbol'])
return YOUR_MODEL_NAME.objects.filter(symbol=self.symbol)
I consider your model field name is symbol.
You can try like this:
from django.shortcuts import render
def page_view(request):
# recheck how to get data you want pass in html from this view
return render(request, 'search.html', {
'symbol': request.DATA.get('symbol'),
})
and in url change to this:
urlpatterns = [
path('search/<string>', page_view, name='search_stock'),
]
and in search.html you will have {{ symbol }} variable from def page_view
I am a newbie to django and need some help. I have a created a vaguely functioning website. I have a model which looks as follows;
from django.db import models
class InductiveSensors(models.Model):
Part_No = models.CharField(max_length=250)
Manufacturer = models.CharField(max_length=250)
Sn = models.CharField(max_length=250)
AssuredSn = models.CharField(max_length=250)
def __str__(self):
return InductiveSensors.Manufacturer
There are a couple of pages. one which gives me a list of all items in the database
{% extends "ESensFind/header.html" %}
{% block content %}
{% for InductiveSensors in object_list %}
<h5>{{ InductiveSensors.Manufacturer}}<a
href="/Inductive_Search/{{InductiveSensors.id}}">
{{InductiveSensors.Part_No}}</a></h5>
{% endfor %}
{% endblock %}
When the {{InductiveSensors.Part_No}} link is clicked it opens up another page. On which I would like to display this database entry in a table with the information of
Part_No = models.CharField(max_length=250)
Manufacturer = models.CharField(max_length=250)
Sn = models.CharField(max_length=250)
AssuredSn = models.CharField(max_length=250)
my urls look like:
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from Inductive_Search.models import InductiveSensors
urlpatterns = [
url(r'^$',ListView.as_view(queryset=InductiveSensors.objects.all().order_by
("Manufacturer") #THIS PAGE IS THE LIST OF ALL DATABASE ENTRIES#
[:25],template_name="Inductive_Search/Inductive_Search.html")),
url(r'^(?P<pk>\d+)$', ListView.as_view(model= InductiveSensors,
template_name = 'Inductive_Search/SensorInfo.html')) #THIS OPENS UP A NEW
INDEX PAGE AFTER A PARTICULAR DATABASE ENTRY LINK IS CLICKED#
is the 2nd url code correct to work in conjunction with "SensorInfo.html"? In "SensorInfo.html" i have this code, which I would think should display even just the manufacturer information in a header but it displays nothing.
{% extends "ESensFind/header.html" %}
{% block content %}
<h5>{{ InductiveSensors.Manufacturer}}</h5>
{% endblock %}
Essentially what I am trying to do is get SensorInfo.html to display the values from my model, relating to that particular index in a table on my webpage. Any help would be appreciated. Thanks
The "right" solution is to write detail view (by deriving from DetailView), when in the template you can access the underlying object using get_object() or .object.
If you want to implement it quick and dirty, you have to access the pk argument and using it get the model instance, and pass it as part of the context data.
I suggest you dig into documentation, the django tutorial is good place to start (https://docs.djangoproject.com/en/2.0/intro/tutorial01/#writing-your-first-django-app-part-1) or read on class based views here https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/
So would a solution be something like the following to urls.py?
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from Inductive_Search.models import InductiveSensors
urlpatterns = [
url(r'^$',
ListView.as_view(queryset=InductiveSensors.objects.all().order_by
("Manufacturer")
[:25],template_name="Inductive_Search/Inductive_Search.html")),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model= InductiveSensors,
template_name = 'Inductive_Search/SensorInfo.html'))
]
and in the template
{% extends "ESensFind/header.html" %}
{% block content %}
<h5>{{ get_object() }}</h5>
{% endblock %}
I am trying to use the UpdateView of django but for some reason it does not work.
(URL.py)
from django.conf.urls import url
from . import views
app_name='profiles'
urlpatterns = [
url(r'^$', views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)$',views.DetailView.as_view(),name='detail'),
url(r'^task/add/$',views.TaskCreate.as_view(),name='task-add'),
url(r'^task/(?P<pk>[0-9]+)$',views.TaskUpdate.as_view(), name='task-update'),
url(r'^task/(?P<pk>[0-9]+)/delete/$',views.TaskDelete.as_view(), name='task-delete'),]
Below is my Html file in which I am trying to add a "Edit" link which will redirect to the UpdateView.
(Details.PY this already has the second url mapped)
{% extends 'profiles/base.html' %}
{% block body %}
<H3>The total efforts are {{datamain.efforts}} {{datamain.status}} hours.</H3>
Edit
{% endblock %}
Below is the Views.py
class IndexView(generic.ListView):
template_name = 'profiles/index.html'
def get_queryset(self):
return Datamain.objects.all()
class DetailView(generic.DetailView):
model = Datamain
template_name = 'profiles/details.html'
class TaskCreate(CreateView):
model=Datamain
fields=['main_task','date_time','efforts','status']
class TaskUpdate(UpdateView):
model=Datamain
fields=['main_task','date_time','efforts','status']
class TaskDelete(DeleteView):
model=Datamain
success_url = reverse_lazy('profiles:index')
fields=['main_task','date_time','efforts','status']
When I run it and go to the page , it shows error "no reverse match"
You forget to pass url argument pk try this:
Edit
from django.views import generic
from .models import Inspectionfile
from .models import posts
class IndexView(generic.ListView):
template_name = "posts/index.html"
def get_queryset(self):
return Inspectionfile.objects.all()
class DetailView(generic.DetailView):
model = Inspectionfile
template_name = "posts/detail.html "
#index template
<ul>
{% for o in object_list %}
<li>{{o.document_title}} </li>
{% endfor %}
</ul>
#detail template
<h1>{{ o.document_title }}</h1>
My Index template works but the detail template does not seem to take the value so just appears blank . So is the 'o' not being passed to detail ?? I have not been able to solve this. BTW document_title is one of the field of my inspectionfile model. I checked my url regex and it seems to work fine.
o is an object which only exists within the for loop in your list view template. It isn't passed anywhere.
The detail view has its own context; there the object that is identifued by the url argument is called just object.