I am writing my first views in Django. I have spent countless hours trying to figure this out. One of my views appears in the web page, but the other one that I am trying to retrieve data from the database is not. I've used the python shell to see if the code works and it does. The following is my model, view, my urls, and template. Additionally, any documentation websites would be great too - or books. thanks all.
models.py
from django.db import models
class Bee_hive(models.Model):
gid = models.IntegerField(primary_key=True)
hive_title = models.CharField(max_length=50)
date_hive_death = models.DateField()
date_hive_created = models.DateField()
description = models.TextField()
def __str__(self):
return self.hive_title
views.py
from django.shortcuts import render
import datetime
from inventory.models import Bee_hive
def index(request):
now = datetime.datetime.now()
context = {'current_date': now}
return render(request, 'inventory/index.html', context)
def hive_names(request):
titles = Bee_hive.objects.all()
context = {'titles': titles}
return render(request, 'inventory/index.html', context)
My template contains the following:
<html>
<body>
<p>Hello, David!</p>
It is now {{ current_date }}.
<p>The hive name is: {{ titles }} </p>
</body>
</html>
urls.py
from django.conf.urls import patterns, url
from inventory import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.hive_names, name='hive_names'),
)
This is my result:
Hello, David!
It is now Jan. 18, 2015, 7:08 a.m..
The hive name is:
You should set different urls to different views:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^hive-names/$', views.hive_names, name='hive_names'),
)
Related
I'm trying to make a simple page with Django where posts are being displayed using primary keys. However, the DetailView page with my posts can't be displayed.
This is my model:
class Post(models.Model):
author = models.CharField(max_length=100)
title = models.CharField(max_length=100)
posted_date = timezone.now()
text = models.TextField()
def get_absolute_url(self):
return reverse("postdetail", kwargs={"pk": self.pk})
def __str__(self):
return self.title
and here is my url pattern list:
urlpatterns = [
url(r'^posts/(?P<pk>\d+)$', views.PostDetail.as_view(), name="postdetail"),
url(r'^$', views.index, name="index"),
url(r'^thanks/$', views.Thanks.as_view(), name="thanks"),
url(r'^postlist/$', views.PostList.as_view(), name="postlist"),
]
The template is in my templates folder under the name "post_detail.html".
Here is the DetailView:
class PostDetail(DetailView):
context_object_name = 'post_details'
model = Post
I can't see where I might have a mistake. I have a ListView that shows my posts including the primary keys. But when I try to open the URL http://127.0.0.1:8000/posts/1/
I get:
`Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/posts/1/
Using the URLconf defined in myproj.urls, Django tried these URL patterns, in this order:
admin/
^posts/(?P<pk>\d+)$ [name='postdetail']
^$ [name='index']
^thanks/$ [name='thanks']
^postlist/$ [name='postlist']
The current path, posts/1/, didn’t match any of these.
Do you have a clue why the URL cannot be found? Thank you very much.`
Instead of url() use path()
from django.urls import path
urlpatterns = [
path('', views.index, name = "index"),
path('posts/<int:pk>', views.PostDetail.as_view(), name = "postdetail"),
path('postlist/', views.PostList.as_view(), name="postlist"),
path('thanks', views.Thanks.as_view(), name = "thanks"),
]
NB: url() been deprecated since version 3.1 and removed in 4.0
You are trying to access : http://127.0.0.1:8000/posts/1/ when you define the following http://127.0.0.1:8000/posts/1 without the backlash.
Try : http://127.0.0.1:8000/posts/1
First Things Is Your Views. You can send your database data with return it to the HTML.
views.py
def post(request,id):
post = Post.objects.get(id=id)
return render(request,'blog/index.html',{'post':post})
and before sending data into the HTML you should get the post id in your urls.py
urls.py
path('post/<int:id>', views.post, name='post.blog')
then in your HTML you can handle that data comes from your views.py
index.html
<div class="post-content content">{{ post.body|safe }}</div>
I have a DB hat hs some values in it. I want to display these values on my index.html. i want to display them on the standard html path path('', views.index, name = "index"),
I currently displaying them at path('this_is_the_path/', my_db_class.as_view()),
The problem is that i am pulling the values from a class. and i can't figure out how to set the class to the original index.html path.
Models.py
from django.db import models
class Database(models.Model):
text = models.TextField()
Views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Database
# Create your views here.
def index(request):
return render(request,"index.html",{})
class my_db_class(ListView):
model = Database
template_name = 'index.html'
URLS.PY
from django.urls import path
from . import views
from .views import my_db_class
urlpatterns = [
path('', views.index, name = "index"),
path('this_is_the_path/', my_db_class.as_view()),
]
HTML.PY
<ul>
{% for post in object_list %}
<li> {{ post.text }}</li>
{% endfor %}
</ul>
So my problem is that the above code will only show my DB values at the this_is_the_path path, but i want to show it at the '' path.
just modify your index function like this.
views.py
def index(request):
object_list = Database.objects.all()
return render(request,"index.html",{'object_list':object_list})
I reused similar code twice but on one occasion it doesn't add anything to database, can anyone tell me why? Lack of form validation is the problem?
I'm trying to increase some user model fields by certain integer every time form is sent to server. One of them working, one doesn't.
Code below increase amount_comments by one every time:
def add_comment(request, pk):
ticket = get_object_or_404(Ticket, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.ticket = ticket
comment.author = request.user
comment.save()
user = CustomUser.objects.get(username=request.user)
user.amount_comments += 1
user.save()
messages.success(request, ('Comment added!'))
return redirect('show_single', pk=pk)
else:
form = CommentForm()
return render(request, 'add_comment.html', {'form': form})
...and this one doesn't increase contributions for some reason:
def show(request, pk):
if request.method == "POST":
user = CustomUser.objects.get(username=request.user)
user.contributions += 5
user.save()
return redirect('checkout', pk=pk)
ticket = Ticket.objects.get(pk=pk)
comment_list = Comment.objects.select_related().filter(
ticket_id=pk).order_by('-date')
paginator = Paginator(comment_list, 4)
page = request.GET.get('page')
comments = paginator.get_page(page)
key = settings.STRIPE_PUBLISHABLE_KEY
return render(request, 'single_ticket.html', {'ticket': ticket, 'comments':
comments, 'key': key})
I don't get any errors just checking admin panel and user doesn't get his contributions field changed by 5 when amount_comments goes up every time.
CustomUser extends AbstractUser with two fields added:
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
contributions = models.IntegerField(default='0')
amount_comments = models.IntegerField(default='0')
On second occasion checkout.js is the library used for the form:
<form action="{% url 'checkout' ticket.id %}" method="post">
{% csrf_token %}
<script src="https://checkout.stripe.com/checkout.js"
class="stripe-button"
data-key={{ key }}
data-description="Payment"
data-amount="500"
data-currency="gbp"
data-locale="auto">
</script>
</form>
urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('blog/', include('blog.urls')),
path('ticket/', include('ticket.urls')),
path('checkout/', include('checkout.urls')),
path('login/', views.login_user, name='login'),
path('sign_up', views.sign_up, name='sign_up'),
path('logout/', views.logout_user, name='logout'),
path('all_tickets/', views.all_tickets, name='all_tickets')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
checkout app urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('<int:pk>', views.checkout, name='checkout'),
]
tickets app urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('delete/<ticket_id>', views.delete, name='delete'),
path('show/<int:pk>', views.show, name='show_single'),
path('show/<int:pk>/comment/', views.add_comment, name='add_comment'),
path('add', views.add_ticket, name='add_ticket'),
]
You're posting to {% url 'checkout' ticket.id %} which is linked here path('<int:pk>', views.checkout, name='checkout') to views.checkout, not show. So this code (show) was never executed for given form. Change URL pattern name in this template tag to the correct one:
{% url 'show_single' ticket.id %}
How to load multiple models in one template in Django 2?
i've read Django Pass Multiple Models to one Template but, i'm lost in the answer and there is no specific answer there to get that view into the template,
Im trying to pass 3 models in views to template, which is Info, Slogan & Berita.
My views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Artikel, Berita, Data, Galeri, Info, Slogan, Profil
from django.views.generic import ListView, DetailView
def home(request):
extra_context : {"info" : Info.objects.all(),
"slogan": Slogan.objects.all(),
"berita": Berita.objects.all(),
#and so on for all the desired models...
}
return render (request, 'blog/home.html')
class HomeListView(ListView):
context_object_name = 'slogan'
template_name = 'blog/home.html'
queryset = Info.objects.all()
def get_context_data(self, **kwargs):
context = super(HomeListView, self).get_context_data(**kwargs)
context['slogan'] = Slogan.objects.all()
context['berita'] = Berita.objects.all()
# And so on for more models
return context
my template home.html looks like:
{% for slogans in slogan %}
<p>{{ slogans.konten }}</p>
<p>{{ slogans.author }}</p>
{% endfor %}
my url urls.py looks like:
from blog.views import HomeListView
urlpatterns = [
url(r'^$', HomeListView.as_view(), name="home"),
]
and page source on browser shows nothing.
Im stuck on this, i found at least 3 similar result on this site but not works for me.
I have the following model and url routes. There is one Post model that I want to route to different URLs based on the category. Is there a way to do this by passing in extra information in app/urls.py?
In app/posts/models.py
class Post(models.Model):
author = ...
title = ...
body = ...
category = models.CharField()
In app/urls.py
urlpatterns = patterns(
'',
(r'^blog/', include('posts.urls'), {'category': 'blog'}),
(r'^school/', include('posts.urls'), {'category': 'school'}),
)
My understanding is that the extra info from app/urls.py is included in each url route in app/posts/urls.py. Is there a way to use that information? What can I put in place of the exclamation points below?
In app/posts/urls.py
from models import Post
queryset = Post.objects.order_by('-pub_date')
urlpatterns = patterns(
'django.views.generic.list_detail',
url(r'^$', 'object_list',
{'queryset': queryset.filter(category=!!!!!!)}
name="postRoot"),
url(r'^(?P<slug>[-\w]+)/$', 'object_detail',
{'queryset': queryset.filter(category=!!!!!!)},
name="postDetail")
)
Thanks, joe
I am not aware of a way to use the URL parameters the way you have indicated. If anyone knows better, do correct me.
I faced a similar situation some time ago and made do with a thin wrapper over the list_detail view.
# views.py
from django.views.generic.list_detail import object_list
def object_list_wrapper(*args, **kwargs):
category = kwargs.pop('category')
queryset = Post.objects.filter(category = category)
kwargs['queryset'] = queryset
return object_list(*args, **kwargs)
#urls.py
urlpatterns = patterns('myapp.views',
url(r'^$', 'object_list_wrapper', {}, name="postRoot"),
...