I've been trying to display youtube videos by passing the video id in a class and replacing the value in a template.But it doesn't seem to be happening.
My models.py
from django.db import models
class Rockinfo(models.Model):
rock_name = models.CharField(max_length=200,default="ac/dc")
rock_img = models.ImageField(upload_to="%Y/%m/%d",default="1992/08/92")
rank = models.IntegerField(default=0)
def __str__(self):
return self.rock_name
class Rockvids(models.Model):
rockername = models.ForeignKey(Rockinfo)
vid_id = models.CharField(max_length=200,default="Z7JgY9zezj4")
vid_name = models.CharField(max_length=300,default="Something Inside Me")
vid_singer_name = models.CharField(max_length=300,default="Jonathan Reyes Myers")
def __str__(self):
return self.vid_id
my admin.py
from django.contrib import admin
from .models import Rockinfo, Rockvids
class ChoiceInline(admin.TabularInline):
model = Rockvids
extra = 10
class RockinfoAdmin(admin.ModelAdmin):
fieldsets = [
('The Fucking Band', {'fields': ['rock_name']}),
('Image', {'fields': ['rock_img']}),
]
inlines = [ChoiceInline]
list_display = ('rock_name', 'rock_img')
list_filter = ['rank']
search_fields = ['rock_name']
admin.site.register(Rockinfo, RockinfoAdmin)
my application's urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]
My application's views.py file
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Rockvids, Rockinfo
class IndexView(generic.ListView):
template_name = 'rockinglist/index.html'
context_object_name = 'latest_rockinfo_list'
def get_queryset(self):
return Rockinfo.objects.order_by('-rank')[:50]
class DetailView(generic.DetailView):
model = Rockinfo
template_name = 'rockinglist/detail.html'
index.html file
{% if latest_rockinfo_list %}
<ul>
{% for rockinfo in latest_rockinfo_list %}
<h1>{{ rockinfo.rock_name }}</a></li>
<img src="img\{{ rockinfo.rock_img }}" alt="ac/dc">
{% endfor %}
</ul>
{% else %}
<p>No</p>
{% endif %}
detail.html file
<h1>{{ rockinfo.rock_name }}</h1>
{% for choice in rockinfo.rockvids_set.all %}
<img id="hide" src="http://img.youtube.com/vi/{{ rockvids.vid_id }}/hqdefault.jpg" data-video="https://www.youtube.com/embed/{{ rockvids.vid_id }}?autoplay=1" width="480" height="300"/>
{% endfor %}
I have been trying to display all the youtube videos once the user clicks on the image by using the videos id passed in Rockvidsclass but there seems to be some error in the loop. Thanks in advance.
In your template loop, you've defined the object as choice. Just refer to it that way rather than using rockvids. See below.
{% for choice in rockinfo.rockvids_set.all %}
<img id="hide" src="http://img.youtube.com/vi/{{ choice.vid_id }}/hqdefault.jpg" data-video="https://www.youtube.com/embed/{{ choice.vid_id }}?autoplay=1" width="480" height="300"/>
{% endfor %}
Since you'll have multiple images, you probably want to change id="hide" to class="hide" as well, since there should only be one element with a given id on a page.
Related
I have been working on a simple forums application for a few weeks now. The main goal of the project is to have sooner written a post and then for the post to be displayed. The project does not utilize user models. For some reason when the user completes the form for their post their post is not displayed. I was wondering if anyone knew why this is happening or if any of y'all have any tips.
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
from . import forms
# Create your views here.
class ForumForm(generic.CreateView):
template_name = 'forums_simple/forum.html'
form_class = forms.ForumForm
success_url = '/'
def form_vaild(self, form):
self.object = form.save(commit=False)
self.object.save()
return super().form_vaild(form)
urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = 'forums'
urlpatterns = [
path('', views.ForumForm.as_view(), name='forum')
]
models.py
from django.db import models
# Create your models here.
class Post(models.Model):
message = models.TextField(blank=True, null=False)
created_at = models.DateTimeField(auto_now=True)
forms.py
from django import forms
from . import models
class ForumForm(forms.ModelForm):
class Meta:
model = models.Post
fields = ('message',)
forum.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
{% for message in object_list %}
{{ post.message }}
{% endfor %}
</div>
<div class="container">
<form class="forum_class" action="index.html" method="post">
{% csrf_token %}
{% crispy form %}
<button type="submit" name="big-button"></button>
</form>
</div>
{% endblock %}
You need to add object_list to your context in the view so:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# don't forget to import Post
context['object_list'] = Post.objects.all()
return context
I'm following along a book called Django for Beginners and creating a project which displays newspaper articles. Part of the functionality is being able to edit those articles. I've followed along as closely as I could but I'm still getting an error when hitting the 'Update' button:
My urls.py
from django.urls import path
from .views import (ArticleListView,
ArticleUpdateView,
ArticleDetailView,
ArticleDeleteView)
urlpatterns = [
path('<int:pk>/edit/', ArticleUpdateView.as_view(), name = 'article_edit'),
path('<int:pk>/', ArticleDetailView.as_view(), name = 'article_detail'),
path('<int:pk>/delete/', ArticleDeleteView.as_view(), name = 'article_delete'),
path('', ArticleListView.as_view(), name = 'article_list'),
]
my views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Article
# Create your views here.
class ArticleListView(ListView):
model = Article
template_name = 'article_list.html'
class ArticleDetailView(DetailView):
model = Article
template_name = 'article_detail.html'
class ArticleUpdateView(UpdateView):
model = Article
fields = ('title', 'body')
template_name = 'article_edit.html'
class ArticleDeleteView(DeleteView):
model = Article
template_name = 'article_delete.html'
success_url = reverse_lazy('article_list')
My models.py:
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=225)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
def get_absolute_url(self):
reverse('article_detail', args=[str(self.id)])
My HTML:
<!-- templates/article_edit.html -->
{% extends 'base.html' %}
{% block content %}
<h1>Edit</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}\
<button class="btn btn-info ml-2" type="submit">Update Article {{article.pk}}</button>
</form>
{% endblock content %}
After hitting the edit button, according to the book the app is supposed to forward me to the 'article_detail' page however that is not happening.
Any assistance would be gratefully received.
Thanks
Andy
In the end it was a simple omission of a return statement in the get_absolute_url function within models.py.
I am having a post model with a user having OneToMany Relationship with inbuilt user model for authentication
my urls.py
from django.contrib import admin
from django.urls import path, include
# from views import PostView
from . import views
urlpatterns = [
path('', views.PostView.as_view(), name='blogHome'),
path('post/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'),
path('post/new/', views.PostCreateView.as_view(), name='post-create'),
path('about/', views.about, name='about')
]
my views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
from django.views.generic import (
ListView,
DetailView,
CreateView
)
# Create your views here.
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
def about(request):
return render(request, 'blog/about.html')
class PostView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_published']
class PostDetailView(DetailView):
model = Post
class PostCreateView(CreateView):
model = Post
fields = ['title', 'body']
#to add author before validation
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
Post Model
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
body = models.TextField()
date_published = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
I am using post_form.html as the template name
post_form.html
{% extends 'blog/layout.html' %}
{% load crispy_forms_tags %}
{% block body %}
<div class="content-section p-20">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group p-30">
<legend class="border-bottom mb-4">Create new post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Create</button>
</div>
</form>
</div>
{% endblock %}
I am a beginner in Django , please tell if anything more is needed to solve the problem. Also why this type of error is coming only with Createview and not with other views
Apparently the return of super().form_valid(form) is None and not a valid response. I don't know much of this design pattern in Django but seeing your other methods seems like this view is decorated by some method which returns a valid response. So you should not return something in your implementation. So, drop the return and test again.
I am building a web app in Django trying to use django-autocomplete-light(v.3.8.2) to create an auto-complete field. I have form that allows users to create a Trade record. I'm trying to add an auto-complete field for Trade.owned_game (a lookup field). I am just getting an empty dropdown field for the auto-complete field (screenshot attached at bottom of this post) Below is my code:
models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Game(models.Model):
name = models.TextField() # Unrestricted text
platform = models.CharField(max_length=100) # character field
created_date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name # return game name when game.objects.all() is called
class Trade(models.Model):
name = models.TextField() # Unrestricted text
created_date = models.DateTimeField(default=timezone.now)
is_trade_proposed = models.BooleanField(default=False)
user_who_posted = models.ForeignKey(User, on_delete=models.CASCADE)
owned_game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='owned_game', db_column='owned_game')
def __str__(self):
return self.name # return game name when game.objects.all() is called
urls.py:
from django.urls import path
from django.conf.urls import url
from .views import (
PostListView,
TradeListView,
PostDetailView,
TradeCreateView,
GameAutoComplete,
PostUpdateView,
PostDeleteView,
UserPostListView
)
from . import views
urlpatterns = [
path('', views.home, name='blog-home'),
path('post/new/', views.trade_new, name='trade-create'),
url(
r'^game-autocomplete/$',
GameAutoComplete.as_view(),
name='game-autocomplete')
,
]
views.py:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from .models import Trade, Game
def trade_new(request):
form = TradeCreateForm()
return render(request, 'blog/trade_form.html', {'form': form, 'title': 'asdf'})
class TradeCreateForm(forms.ModelForm):
game = forms.ModelChoiceField(
queryset=Game.objects.all(),
to_field_name = 'name',
widget=autocomplete.ModelSelect2(url='game-autocomplete')
)
class Meta:
model = Trade
fields = ['owned_game', 'desired_game']
class TradeCreateView(LoginRequiredMixin, CreateView):
model = Trade
fields = ["owned_game"]
class GameAutoComplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return Game.objects.none()
qs = Game.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
trade_form.html:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Propose New Trade</legend>
{{ form|crispy }}
{{ form.media }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Submit</button>
</div>
</form>
</div>
{% endblock content %}
Screenshot:
enter image description here
I have tried the solutions from these similar StackOverflow questions but they're not working:
Django-autocomplete-light showing empty dropdown instead of autocomplete widget
django-autocomplete-light displays empty dropdown in the form
I should have checked the javascript console earlier! The problem was one of the <link ...> scripts for jQuery was invalid. Once i fixed that, the auto-complete field worked
Hello I am new in Django, and I decided to do a Blog page. Problem is that my queryset is empty after I create a new aplication. any idea why ?
Tried with active and without active.
views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from django.http import Http404
from .models import BlogPost
class BlogPostListView(ListView):
queryset = BlogPost.objects.all().active()
template_name = "blog.html"
def get_queryset(self, *args, **kwargs):
request = self.request
return BlogPost.objects.all().active()
def BlogPost_list_view(request):
queryset = BlogPost.objects.all().active()
context = {
'object_blog': queryset
}
return render(request, "blog.html", context)
models.py
import random
import os
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.urls import reverse
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
def upload_image_path(instance, filename):
print(instance)
print(filename)
new_filename = random.randint(1,18341264712)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename= new_filename, ext=ext)
return "products/{new_filename}/{final_filename}".format(
new_filename= new_filename,
final_filename=final_filename
)
class BlogPostQuerySet(models.query.QuerySet):
def active(self):
return self.filter(active=True)
def featured(self):
return self.filter(featured=True, active=True)
class BlogPostManager(models.Manager):
def get_queryset(self):
return BlogPostQuerySet(self.model, using=self._db)
def all(self):
return self.get_queryset()
class BlogPost(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True)
description = models.TextField()
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
objects = BlogPostManager()
def get_absolute_url(self):
return "{slug}/".format(slug=self.slug)
# return reverse("products:detail", kwargs={"slug": self.slug})
def __str__(self):
return self.title
def __unicode__(self):
return self.title
urls.py
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from .views import BlogPostListView, BlogPostDetailSlugView
urlpatterns = [
url(r'^$', BlogPostListView.as_view(), name='list'),
url(r'^(?P<slug>[-\w]+)/$', BlogPostDetailSlugView.as_view(), name='detail'),
]
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
admin.py
from django.contrib import admin
from .models import BlogPost
class BlogPostAdmin(admin.ModelAdmin):
list_display = ['__str__', 'slug']
class Meta:
model = BlogPost
admin.site.register(BlogPost, BlogPostAdmin)
blog.html
{% for obj in object_blog %}
<!-- Blog Post -->
<div class="card mb-4 text-white bg-dark">
{% if obj.image %}
<!-- {{MEDIA_URL}} -->
<img class="card-img-top" src="{{ obj.image.url }}" alt="Card image cap">
{% else %}
<h1> No pic </h1>
{% endif %}
<div class="card-body">
<h2 class="card-title">{{ obj.title }}</h2>
<p class="card-text">{{ obj.description|slice:":255" }} ...</p>
Read More →
</div>
<div class="card-footer text-muted">
{{ obj.timestamp }}
Start Bootstrap
</div>
</div>
{% endfor %}
I am using almost the same pattern as I used in different application, where everything works. Few days ago I noticed some kind of strange bahavior from Django side, because it did want to show me images on the website, until I restarted a PC completely. If anyone needs more information / to see some different files, I can provide more. Here are few pictures from my Django admin.
Your two views BlogPostListView and BlogPost_list_view do almost exactly the same thing, I don't know why you have two of them. But note that the first one is the one that is actually used by your URL.
Now, that view is a class-based view that will send a variable called blog_list or object_list to the template. However, the template itself is iterating over a variable called object_blog, which would be sent by the (unused) second view. You should change that to object_list - or, in the view, you could add context_object_name = 'object_blog' (but I don't recommend that).