This piece of code gets me the required output in my python terminal
views.py
from django.contrib.auth.models import User
userList =User.objects.all()
print(userList)
outputs this in the terminal
<QuerySet [<User: brad>, <User: john>]>
I know I have to iterate through the QuerySet but I am not able to link this view to my main page.
So how can I get this on my main HTML page?
In your views.py create view as
from django.views.generic.list import ListView
from django.contrib.auth.models import User
class UserListView(ListView):
model = User
template_name = 'your_template_name.html'
Then in your urls.py
from django.urls import path
from yourapp.views import UserListView
urlpatterns = [
path('userlists', UserListView.as_view(), name='user-list'),
]
Then in your html loop through object_list as
<h1>User List</h1>
<ul>
{% for user in object_list %}
<li>{{ user.username }}</li>
{% empty %}
<li>No users yet.</li>
{% endfor %}
</ul>
Here is pseudo code you can try,
from django.contrib.auth.models import User
from django.shortcuts import render
def index(request):
userList =User.objects.all()
return render(request, 'users.html', {'users': userList})
And users.html like,
<h1>USERS</h1>
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% endfor %}
</ul>
urls.py is like,
from django.contrib import admin
from django.urls import path
from app1.views import *
urlpatterns = [
path('', index),
path('admin/', admin.site.urls),
]
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 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
I am trying to create a contact form for my Django site but it's not working properly. There are three steps to the contact form. Step 1 has a box where you input the subject of the email. Step 2 has a box where you input the sender's email address. At this point, there are three buttons- "first step", "prev step", and "submit". If I click "submit", the site doesn't take me to step 3, which is supposed to be where you input the body of the email. Instead, it reroutes me back to the Step 1 page.
I did my research and I can't find anything online related to this particular problem.
Here is my views.py file, which is located in the django_test/django_test directory:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from forms import MyRegistrationForm
from django.contrib.formtools.wizard.views import SessionWizardView
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
#import logging
#logr = logging.getLogger(__name__)
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html',
{'full_name': request.user.username})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return render_to_response('logout.html')
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
class ContactWizard(SessionWizardView):
template_name = "contact_form.html"
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('done.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
logr.debug(form_data[0]['subject'])
logr.debug(form_data[1]['sender'])
logr.debug(form_data[2]['message'])
send_mail(form_data[0]['subject'],
form_data[2]['message'], form_data[1]['sender'],
[(my email address], fail_silently=False)
return form_data
This my forms.py file, also located in the django_test/django_test directory:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
class ContactForm1(forms.Form):
subject = forms.CharField(max_length=100)
class ContactForm2(forms.Form):
sender = forms.EmailField()
class ContactForm3(forms.Form):
message = forms.CharField(widget=forms.Textarea)
And my contact_form.html file, located in the django_test/templates directory:
{% extends "base.html" %}
{% block content %}
<h2>Contact Us</h2>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
{% for field in form %}
{{field.error}}
{% endfor %}
<form action="/contact/" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">"first step"</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</buttom>
{% endif %}
<input type="submit" value="submit" />
</form>
{% endblock %}
And this is my urls.py file:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from django_test.api import ArticleResource
from django_test.forms import ContactForm1, ContactForm2, ContactForm3
from django_test.views import ContactWizard
article_resource = ArticleResource()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', 'django_test.views.login'),
url(r'^accounts/auth/$', 'django_test.views.auth_view'),
url(r'^accounts/loggedin/$', 'django_test.views.loggedin'),
url(r'^accounts/invalid/$', 'django_test.views.invalid_login'),
url(r'^accounts/logout/$', 'django_test.views.logout'),
url(r'^accounts/register/$', 'django_test.views.register_user'),
url(r'^accounts/register_success/$', 'django_test.views.register_success'),
url(r'^articles/all/$', 'article.views.articles'),
url(r'^articles/create/$', 'article.views.create'),
url(r'^articles/get/(?P<article_id>\d+)/$', 'article.views.article'),
url(r'^articles/like/(?P<article_id>\d+)/$', 'article.views.like_article'),
url(r'^articles/add_comment/(?P<article_id>\d+)/$', 'article.views.add_comment'),
url(r'^articles/search/', 'article.views.search_titles'),
url(r'^articles/api/', include(article_resource.urls)),
url(r'^contact/', ContactWizard.as_view([ContactForm1, ContactForm2, ContactForm3])),
)
I'm not getting any error messages either, which is frustrating, so I don't know what I'm doing wrong. Thank you.
All I had to do was view the page source on the site. It turned out
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</buttom>
in contact_form.html had a typo: </buttom>. I fixed the error and now I get the comment page.
The line should be:
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</button>