I think this is something simple but I cannot find the error at all.
The code inside the for loop is not executing. When I look up the database and the admin site the content displays fine but trying to display on the HTML is not working:
Views
from django.shortcuts import render
from django.utils import timezone
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now())
return render(request, "blog/bloglist.html", {'posts': posts})
Urls:
from django.conf.urls import url
import views
urlpatterns = [
url(r'^blog/$', views.post_list),
]
Base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>Base</h1>
{% block content %}
{% endblock %}
</body>
</html>
bloglist.html
{% extends "base.html" %}
{% block content %}
<h1>Blog </h1>
{% for post in posts %}
<h3>{{ post.title }}</h3>
{% endfor %}
{% endblock %}
and just to be sure the model is included as well
Models:
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
content = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
I know its pretty simple but I just cannot find the error. Thanks in advance
Related
im trying to add to my html a button that appears only on certain events, that works for me but i want to add a onclick script/function that will invoke a backend view.py function that deletes the specific room on click, the room model is : owner(fk), name, slug.
and the user model is : username password1 password2.
i just need to know how to invoke an onclick event that will call the backend function in my views.
rooms.html
{% extends 'core/base.html' %}
{% block title %} Rooms | {% endblock %}
{% block content %}
<div class="main">
<h1>Rooms</h1>
</div>
<div class="rooms-container">
{% for room in rooms %}
<div class="room">
<div class="room-info">
<h1 class="room-title">{{ room.name }}</h1>
Join Room
{% if request.user == room.owner %}
<button class="room-delete" id="roomDelete">Delete Room</button>
{% endif %}
</div>
</div>
{% endfor %}
</div>
{% endblock %}
{% block scripts %}
<!-- todo: add delete room button functionality. -->
{% endblock %} ```
views.py
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.contrib import messages
from .models import Room, Message
#login_required
def rooms(request):
if request.method == 'POST':
room_owner = request.user
room_name = request.POST['room-name']
if not Room.objects.filter(slug = room_name).exists():
if room_name == '' or room_name.isspace() or room_name.startswith(' '):
messages.info(request, 'Invalid room name, spaces-only or string that starts with spaces is invalid.')
else:
new_room = Room(owner = room_owner,name = room_name,slug = room_name)
new_room.save()
else:
messages.info(request, 'That room already exists!, try a different name.')
rooms = Room.objects.all()
return render(request, 'room/rooms.html', {'rooms': rooms})
#login_required
def room(request, slug):
room = Room.objects.get(slug=slug)
messages = Message.objects.filter(room=room)[0:25]
return render(request, 'room/room.html', {'room': room, 'messages': messages})
#csrf_exempt
def delete_room(request): ## <<------ invoke this from html call.
print("hey")
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.rooms, name='rooms'),
path('<slug:slug>/', views.room, name='room'),
path('', views.delete_room, name='delete_room'),
]
now i have more 2 urls.py, the project has 3 folders, 1 main (livechatapp) with settings and all, one for core htmls (core) and one for rooms html (room)
core/urls
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('', views.frontpage, name='frontpage'),
path('signup/', views.signup, name='signup'),
path('login/', auth_views.LoginView.as_view(template_name='core/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
and finally
livechatapp/urls
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('core.urls')),
path('rooms/', include('room.urls')),
path('admin/', admin.site.urls),
]
and this is the projects overview folders and files :
this is the project
IF you want do it in standard html:
% extends 'core/base.html' %}
{% block title %} Rooms | {% endblock %}
{% block content %}
<div class="main">
<h1>Rooms</h1>
</div>
<div class="rooms-container">
{% for room in rooms %}
<div class="room">
<div class="room-info">
<h1 class="room-title">{{ room.name }}</h1>
Join Room
{% if request.user == room.owner %}
<form method="POST" action="{% url 'delete_room' room.slug %}>
<button type="submit" class="room-delete">Delete Room</button></form>
{% endif %}
</div>
</div>
{% endfor %}
</div>
{% endblock %}
{% block scripts %}
<!-- todo: add delete room button functionality. -->
{% endblock %} ```
urls:
urlpatterns = [
path('', views.rooms, name='rooms'),
path('<slug:slug>/', views.room, name='room'),
path('delete/<slug:slug>/', views.delete_room, name='delete_room'),
]
views:
#csrf_exempt
def delete_room(request,slug):
if request.method == 'POST':
try:
room = Room.objects.get(slug=slug, owner=request.user)
room.delete()
except ObjectDoesNotExist:
print('there is no room with this slug or you are not owner')
return redirect('rooms')
i advice to use csrf. allways try to use POST when manipulatind data in db.
If you want to work it without redirect you need to think of ajax call or maby htmx
I am using MVT in django. I am using generic CBV (listview, detailview). here are my codes
Here is model.py
from django.db import models
class Singers(models.Model):
name= models.CharField(max_length=256)
age= models.IntegerField()
gender= models.CharField(max_length=10)
class Albums(models.Model):
name= models.CharField(max_length=256)
singer=models.ForeignKey(Singers, on_delete=models.CASCADE)
view.py
from django.views import generic
from core.models import Albums, Singers
#in generic view instead of functions, we use classes
class AlbumView(generic.ListView):
model = Albums
template_name = 'index.html'
paginate_by = 10
def get_queryset(self):
return Albums.objects.all()
class DetailView(generic.DetailView):
model = Albums
template_name = 'detailview.html'
Here are urls.py
from django.urls import path
from core.views import AlbumView, DetailView
urlpatterns = [
path('album/', AlbumView.as_view()),
path('album/detail/<pk>/', DetailView.as_view())
]
Here is index.html
{% block content %}
<h2>Albums</h2>
<ul>
{% for albums in object_list %}
<li>{{ albums.name }}</li>
{% endfor %}
</ul>
{% endblock %}
here is detailview.html
{% block content %}
<h1>name: {{Albums.name}}</h1>
<p><strong>Singer: {{Albums.Singer}}</strong></p>
{% endblock %}
The detail view is not working fine. It is not fetching the respective name of the album and singer details.
Suggest me what should i do?
Try this
{% block content %}
<h1>name: {{object.name}}</h1>
<p><strong>Singer: {{object.singer.name}}</strong></p>
{% endblock %}
class DetailView(generic.DetailView):
model = Albums
template_name = 'detailview.html'
This is not working you have to get first context like this
def get_context_data(self, **kwargs):
// Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
// Add in a QuerySet of all the books
context['Album_list'] = Albums.objects.all()
return context
And you can do as well
context_object_name = 'publisher'
queryset = Publisher.objects.all()
after researching for hours I cannot get rid of this error, I hope someone can help me.
Models:
class Puja(models.Model):
seller = models.OneToOneField(Seller, on_delete=models.CASCADE)
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True,null=True)
title = models.CharField(max_length=100)
video = models.FileField(blank=True)
photo = models.ImageField(blank=True)
published_date = models.DateTimeField("Published: ",default=timezone.now())
bidding_end = models.DateTimeField()
starting_price = models.IntegerField(default=1)
#slug = models.SlugField(null=True)
def __str__(self):
return str(self.title)
#def get_absolute_url(self):
# return reverse('bidding_list_detail', args=[str(self.id)])
#slug time
def get_absolute_url(self):
return reverse('bidding_list_detail',args={'id': self.id})
Views:
class bidding_list(ListView):
model = Puja
template_name = 'bidding_templates/bidding_list.html'
"""return render(request= request,
template_name='bidding_templates/bidding_list.html',
context = {"Pujas": Puja.objects.all})"""
class bidding_list_detail(DetailView):
model = Puja
template_name = 'bidding_templates/bidding_list_detail.html'
urls:
path('admin/', admin.site.urls),
path("bidding_list/", bidding_list.as_view(), name="bidding_list"),
path('<int:pk>', bidding_list_detail.as_view(), name='bidding_list_detail'),
admin:
class PujaAdmin(admin.ModelAdmin):
list_display = ('seller','title','video','photo','published_date','bidding_end','starting_price')
admin.site.register(Puja,PujaAdmin)
template 1:
{% extends 'header.html' %}
{% block content %}
<h1>Pujas</h1>
{% for Puja in object_list %} <!--object_list-->
<ul>
<li> {{ Puja.title }} </li>
</ul>
{% endfor %}
{% endblock %}
template 2:
{% extends 'header.html' %}
{% block content %}
<div>
<h2>{{ object.title }}</h2>
<p>{{ object.seller }}</p>
</div>
{% endblock %}
Note that, whenever I remove <a href="{{ Puja.get_absolute_url }}"> from the first template, the objects "puja" in the model get properly displayed on the template, but I cannot access them. They normally exist on the admin panel, but not displayed on the website directly.
Thank you very much on advance and stay healthy.
edit 1: Here is the urls.py directly from the app created by django. To be more specific, I created after the project a new app called "main" in which I programmed all the project, including all the code on this question except the edit.
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
#from django.config import settings
#from django.config.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
#path('', include('model.urls')),
#path('', include('blog.urls')),
#path('', include('photo.urls')),
#path('', include('video.urls')),
] # +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I guess the problem is this line - return reverse('bidding_list_detail',args={'id': self.id}), you are passing id as a string but trying to match with int in url.Try following return reverse ('bidding_list_detail',args=[self.id])
I have a working HTML view and a working detail API RUD view for some simple model objects. Within the HTML view, elements are listed that have their own API RUD view. I'd like to be able to link each list element in the HTML to it's own API RUD view.
Below is my models.py:
class Hints(models.Model):
text = models.TextField(max_length=255)
author = models.CharField(max_length=20)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.text)
def timestamp_pretty(self):
return self.timestamp.strftime('%b %d %Y')
def get_api_url(self, request=None):
return api_reverse("api-hints1:hints-rud", kwargs={'pk': self.pk}, request=request)
Below is my views.py:
class HTMLAPIView(viewsets.ViewSet):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'base.html'
serializer_class = HTMLSerializer
def list(self, request):
queryset = Hints.objects.order_by('pk')
paginator = Paginator(queryset, 5) # Show 5 items per page
page = request.GET.get('page')
queryset1 = paginator.get_page(page)
return Response({'queryset1': queryset1})
class HintsListApiView(mixins.CreateModelMixin, generics.ListAPIView):
lookup_field = 'pk'
serializer_class = HintsSerializer
def get_queryset(self):
qs = Hints.objects.all()
query = self.request.GET.get("q")
if query is not None:
qs = qs.filter(
Q(text__icontains=query)|
Q(author__icontains=query)
).distinct()
return qs
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def get_serializer_context(self, *args, **kwargs):
return {"request": self.request}
class HintsRudView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'
serializer_class = HintsSerializer
def get_queryset(self):
return Hints.objects.all()
def get_serializer_context(self, *args, **kwargs):
return {"request": self.request}
My urls.py:
from .views import HintsRudView, HintsListApiView, HTMLAPIView
from . import views
from django.contrib import admin
from django.conf.urls import url, include
from rest_framework import routers, serializers, viewsets
urlpatterns = [
url(r'^(?P<pk>\d+)$', HintsRudView.as_view(), name='hints-rud'),
url(r'^$', HintsListApiView.as_view(), name='hints-list'),
url(r'^html/', HTMLAPIView.as_view({'get': 'list'}), name='html' )
]
And my relevant HTML code:
As you can see this was my attempt <li>{{ query }}</li>. Unfortunately, I get the following error:
Reverse for 'hints-rud' not found. 'hints-rud' is not a valid view function or pattern name.
{% load staticfiles %}
{% load static %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'hints1/style.css' %}">
<link href="https://fonts.googleapis.com/css?family=Fjalla+One|Montserrat|Noto+Serif|Nunito|Oswald|Teko" rel="stylesheet">
</head>
<body>
<h1>Handy Dev Hints</h1>
<ul>
{% for query in queryset1 %}
<li>{{ query }}</li>
{% endfor %}
</ul>
<br/>
<br/>
<div class="pagination">
<span class="step-links">
<center>
{% if queryset1.has_previous %}
« First
Previous
{% endif %}
{% if queryset1.has_next %}
Next
Last »
{% endif %}
<br/>
<br/>
<span class="current">
Page {{ queryset1.number }} of {{ queryset1.paginator.num_pages }}
</span>
</center>
</span>
</div>
</body>
</html>
Not sure where to go from here. This doesn't seem like it should be a difficult problem. I've tried removing some $ from the urls.py but it made little difference. I've also tried other views and patterns besides hints-rud but all come back with the same error.
You need to use the namespace, exactly as you do in the get_api_url method.
<a href="{% url 'api-hints1:hints-rud' pk=pk %}">
Why is the form not showing in the browser?
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ structure.name }} - Details</title>
</head>
<body>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<h3>Structure: {{ structure }}</h3>
<h3>Ajouter enregistrement</h3>
<form action="{% url 'Structure:addrecord' structure.id %}" method="post">
{% csrf_token %}
{% for structure in all_structures %}
<input type="radio" id="record{{ forloop.counter }}" name="record" value="record.id">
<label for="record{{ forloop.counter }}">
Nom de l'enregistrement: {{ record.record_name }}
</label>
{% endfor %}
</form>
</body>
</html>
When I test this in my browser, and inspect it, it gives me a form of this size: 1340px * 0 px.
I even explicitly gave a style="height: 500px", but it still gives me an empty form.
Here's a screenshot
Thanks for the help guys!
Edit:
Views.py:
from django.shortcuts import render, get_object_or_404
from .models import Structure, Record
def index(request):
all_structures = Structure.objects.all()
return render(request, 'Structures/index.html', {'all_structures': all_structures})
def detail(request, structure_id):
#structure = Structure.objects.get(pk=structure_id)
structure = get_object_or_404(Structure, pk=structure_id)
return render(request, 'Structures/details.html', {'structure': structure})
def addRecord(request, structure_id, record.name, record.type, record.pos, record.long):
r = Record(structure='structure_id', name='record.name', type='record.type', pos='str(record.pos)', long='str(record.long)')
r.save()
return render(request, 'Structures/details.html', {'structure': structure})
Also, I do not quite understand this yet because I am using a video tutorial series by thenewboston's channel, the variables I am using in addRecord are not known, and I want to use them from the model. Here are the models and urls files as well:
models.py:
from django.db import models
class Structure(models.Model):
name = models.CharField(max_length=120)
path = models.CharField(max_length=200)
def __str__(self):
return self.name
class Type(models.Model):
typename = models.CharField(max_length=50)
def __str__(self):
return self.typename
class Record(models.Model):
structure = models.ForeignKey(Structure, on_delete=models.CASCADE) #each structure has many records, each per line
name = models.CharField(max_length=200)
type = models.ForeignKey(Type)
pos = models.IntegerField()
long = models.IntegerField()
def __str__(self):
return self.name
urls.py:
from django.conf.urls import url
from . import views
app_name = 'Structure'
urlpatterns = [
# /structures/
url(r'^$', views.index, name='index'),
# /structures/id
url(r'^(?P<structure_id>[0-9]+)/$', views.detail, name='detail'),
# /structures/addrecord
url(r'^(?P<structure_id>[0-9]+)/addrecord/$', views.addRecord, name='addrecord'),
]
Look for the value of all_structures that you are passing in context from views.
If it is empty or not passed, form fields won't be displayed as per your template code.
Try to print its value either in the console or in template. That's how to Debug.
Hope this helps.