I am using django 1.11.6 and python 3.6.2
I'm new to django and there is no one to help me where i live so you guys are all my hope
in my django application in the add song section i faced an error
error message =
IntegrityError at /music/album/5/AddSong/ NOT NULL constraint failed:
music_song.album_id
here is my views file:
from django.views import generic
from django.views.generic import View
from .forms import UserForm
from django.views.generic.edit import CreateView,UpdateView,DeleteView
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login
from .models import Album, Song
from django.core.urlresolvers import reverse_lazy
class IndexView(generic.ListView):
template_name = 'music/index.html'
context_object_name = 'all_albums'
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DetailView):
model = Album
template_name = 'music/detail.html'
context_object_name = 'album'
class AlbumCreate(CreateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class SongCreate(CreateView):
model = Song
fields = ['song_title', 'file_type']
class AlbumUpdate(UpdateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class AlbumDelete(DeleteView):
model = Album
success_url = reverse_lazy('music:index')
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form.html'
#display a blank form
def get(self,request):
form = self.form_class(None)
return render(request,self.template_name, {"form": form})
#procces form data
def post(self,request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
#cleaned (normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
#returns User objects if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request,user)
return redirect('music:index')
return render(request,self.template_name, {"form": form})
and here is my models.py :
from django.db import models
from django.core.urlresolvers import reverse
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.FileField()
def get_absolute_url(self):
return reverse('music:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.album_title + ' - ' + self.artist
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
is_favorite = models.BooleanField(default=False)
# song_file = models.FileField(null=True)
def __str__(self):
return self.song_title
def get_absolute_url(self):
return reverse('music:detail', kwargs={'pk': self.album.id})
urls.py:
from django.conf.urls import url
from . import views
app_name = 'music'
urlpatterns = [
# /music/
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^register/$', views.UserFormView.as_view(), name='register'),
# /music/album/54
url(r'^album/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# music/album/add
url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'),
# music/album/3/AddSong
url(r'album/(?P<pk>[0-9]+)/AddSong/$', views.SongCreate.as_view(), name='song-add'),
# music/album/2/update/
url(r'album/(?P<pk>[0-9]+)/AlbumUpdate/$', views.AlbumUpdate.as_view(), name='album-update'),
# music/album/2/delete/
url(r'album/(?P<pk>[0-9]+)/AlbumDelete/$', views.AlbumDelete.as_view(), name='album-delete'),
]
For creating forms I used Django built-in forms,I had to create one for adding albums and another for adding the album's songs
Here is my album_form.html screenshot
and here is my form-template.html screenshot:
and here is my song_form.html screenshot
In the form_valid method, you should fetch the album pk from the url kwargs and set the album on the form instance.
from. django.shortcuts import get_object_or_404
class SongCreate(CreateView):
model = Song
fields = ['song_title', 'file_type']
def form_valid(self, form):
album = get_object_or_404(Album, pk=self.kwargs['pk']
form.instance.album = album
return super(SongCreate, self).form_valid(form)
Related
how can I fix this issue?
the page runs perfectly. when I do post the post. it posts but when I want to type the comment and send by 'GET' I get this error. so, how can I ignore this error this my first question?
- also, I need anyone to give me the best way to make a relationship between post and comment
models.py
from django.db import models
from django.contrib.auth.models import User
class Publication(models.Model):
title = models.CharField(max_length=30)
class Meta:
ordering = ['title']
def __str__(self):
return self.title
class Article(models.Model):
publications = models.ManyToManyField(Publication)
headline = models.CharField(max_length=100)
class Meta:
ordering = ['headline']
def __str__(self):
return self.headline
class Post(models.Model):
users = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
question = models.TextField(max_length=500)
def __str__(self):
return self.title
class Comment(models.Model):
posts = models.ForeignKey(Post, on_delete=models.CASCADE)
comment = models.TextField(max_length=500)
def __str__(self):
return self.comment
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Post, Comment
from .forms import PostForm, CommentForm
def index(request):
# All questions
posts = Post.objects.all()
return render(request, 'community/index.html', {'posts': posts})
def post_view(request):
post_form = PostForm
context = {'posted': post_form}
# Create post
if request.method == 'GET':
post_form = PostForm(request.GET)
if post_form.is_valid():
user_post = post_form.save(commit=False)
user_post.title = post_form.cleaned_data['title']
user_post.question = post_form.cleaned_data['question']
post = Post.objects.create(users=User.objects.get(username=request.user), title=user_post.title, question=user_post.question)
post.save()
return redirect('community:index')
return render(request, 'community/post.html', context)
def answers(request, post_id):
# Specific post
posts = Post.objects.get(id=post_id)
# Create comment
comment_form = CommentForm
context = {'posts': posts, 'comment_form': comment_form}
if request.method == 'GET':
comment_form = CommentForm(request.GET)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.comment = comment_form.cleaned_data['comment']
user_comment.save()
return render(request, 'community/answers.html', context)
urls.py
from django.urls import path
from . import views
app_name = 'community'
urlpatterns = [
path('', views.index, name='index'),
path('post/', views.post_view, name='post'),
path('answers/<int:post_id>', views.answers, name='answers'),
]
forms.py
from .models import Post, Comment
from django import forms
from django.contrib.auth.models import User
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__'
exclude = ['users']
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = '__all__'
exclude = ['users', 'posts']
You forgot to assign the post, or the post_id of the comment you created:
def answers(request, post_id):
# Specific post
posts = Post.objects.get(id=post_id)
# Create comment
comment_form = CommentForm
context = {'posts': posts, 'comment_form': comment_form}
if request.method == 'GET':
comment_form = CommentForm(request.GET)
if comment_form.is_valid():
comment_form.instance.post_id = post_id
user_comment = comment_form.save()
# …
That being said, the above view does not really respect the HTTP assumptions. A view that makes a GET request is not supposed to change entities, so if you want to create a comment, you need to do that through a POST request. Furthemore in order to implement the Post/Redirect/Get pattern [wiki] a successful POST request should return a redirect response.
I'm creating a blog by django, when I want to open http://127.0.0.1:8000/accounts/login I get the error:
init() takes 1 positional argument but 2 were given
Exception Location:
C:\ProgramData\Miniconda3\envs\myDjanEnv\lib\site-packages\django\core\handlers\base.py
in _get_response, line 124
And this is the 124th line of the code from base.py:
if response is None:
wrapped_callback = self.make_view_atomic(callback)
try:
<!-- line 124 --> response = wrapped_callback(request, *callback_args, **callback_kwargs)
except Exception as e:
response = self.process_exception_by_middleware(e, request)
VIEWS.PY CODES:
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from blog.models import Post,Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse,reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView,)
# Create your views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
# form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
# form_class = PostForm
model = Post
class PostDeleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__isnull=True,).order_by('created_date')
###############################################
###############################################
#login_required
def post_publish(request,pk):
post = get_object_or_404(Post,pk=pk)
post.publish
return redirect('post_detail',pk=pk)
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail',pk=post.pk)
else:
form = CommentForm()
return render(request,'blog/comment_form.html',{'form':form})
#login_required
def comment_approve(request,pk):
comment = get_object_or_404(Comment,pk=pk)
comment.approve()
return redirect('post_detail',pk=comment.post.pk)
#login_required
def comment_remove(request,pk):
comment = get_object_or_404(Comment,pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail',pk=post_pk)
FORMS.PY CODES:
from django import forms
from blog.models import Post,Comment
class PostForm(forms.ModelForm):
class Meta():
model = Post
fields = ('author','title','text')
widgets = {
'title':forms.TextInput(attrs={'class':'textinputclass'}),
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent'})
}
class CommentForm(forms.ModelForm):
class Meta():
model = Comment
fields = ('author','text')
widgets = {
'author':forms.TextInput(attrs={'class':'textinputclass'}),
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea'})
}
MODELS.PY CODES:
from django.db import models
from django.utils import timezone
from django.urls import reverse,reverse_lazy
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User',on_delete=models.PROTECT)
title = models.CharField(max_length=200)
text = models.TextField()
create_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 approve_comments(self):
return self.comments.filter(approve_comment=True)
def get_absolute_rul(self):
return reverse("post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.Post',related_name='comments',on_delete=models.PROTECT)
author = models.CharField(max_length=200)
text = models.TextField()
create_date = models.DateTimeField(default=timezone.now)
approve_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def get_absolute_rul(self):
return reverse('post_list')
def __str__(self):
return self.text
URLS.PY (in the same folder that setting.py is in):
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from django.contrib.auth import views
from django.contrib.auth.views import LoginView
urlpatterns = [
path('admin/', admin.site.urls),
url(r'',include('blog.urls')),
url(r'accounts/login/$',views.LoginView,name='login'),
url(r'accounts/logout/$',views.LogoutView,name='logout',kwargs={'next_page':'/'}),
]
URLS.PY (in the same folder that VIEWS.PY is in)
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(),name='post_list'),
url(r'^about/$',views.AboutView.as_view(),name='about'),
url(r'^post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'),
url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),
url(r'^post/(?P<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
url(r'^post/(?P<pk>\d+)/remove/$',views.PostDetailView.as_view(),name='post_remove'),
url(r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),
url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
url(r'^post/(?P<pk>\d+)/approve/$',views.comment_approve,name='comment_approve'),
url(r'^post/(?P<pk>\d+)/remove/$',views.comment_remove,name='comment_remove'),
url(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
]
What is the problem?
In your urls, you are not using as_view() at the end of class based views. You need to use it like this:
path('about/', AboutView.as_view(), name='about')
Update
Problem is in your LoginView and LogoutView which is imported from django.contrib.auth.views. They are class Based Views. So you need to add as_view at the end of them when declaring in the class.
url(r'accounts/login/$',views.LoginView.as_view(),name='login'),
url(r'accounts/logout/$',views.LogoutView.as_view(),name='logout',kwargs={'next_page':'/'})
I am very new to Django so don't judge me :). I am making a blog project and everything works well except one thing. When creating a post, the user can choose any other author that has previously logged in. Is there any way to set the author namespace as the currently logged in user? Here is my code:
Models.py
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
def validate_even(value):
if value == 'auth.User':
raise ValidationError(
_('%(value)s is not an even number'),
params={'value': value},
)
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = 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 approve_comments(self):
return self.comments.filter(approved_comment=True)
def get_absolute_url(self):
return reverse('post_detail', args=(), kwargs={'pk':self.pk})
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.post',related_name='comments')
author = models.ForeignKey('auth.User')
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def get_absolute_url(self):
return reverse('post_list')
def __str__(self):
return self.text
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
def __str__(self):
return self.user.username
My forms.py
from django import forms
from blog.models import Comment,Post
from django.contrib.auth.models import User
from blog.models import UserProfileInfo
class PostForm(forms.ModelForm):
class Meta():
model = Post
fields = ['author','title','text']
widgets = {
'title':forms.TextInput(attrs={'class':'textinputclass','autocomplete':'true'}),
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent'})
}
class CommentForm(forms.ModelForm):
class Meta():
model = Comment
fields = ['text']
widgets = {
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea'})
}
def __init__(self, *args, **kwargs):
from django.forms.widgets import HiddenInput
hide_condition = kwargs.pop('hide_condition',None)
super(CommentForm, self).__init__(*args, **kwargs)
if hide_condition:
self.fields['author'].widget = HiddenInput()
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput(attrs={'autocomplete':'false'}))
username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'false'}))
class Meta():
model = User
fields = ('username', 'email', 'password')
widgets = {
'password':forms.TextInput(attrs={'autocomplete':'false'}),
'username':forms.TextInput(attrs={'autocomplete':'false'}),
}
My views.py
from django.shortcuts import render, get_object_or_404,redirect
from django.utils import timezone
from django.views.generic import (TemplateView,ListView,DetailView,CreateView,UpdateView,DeleteView)
from blog.models import Comment,Post
from blog.forms import PostForm,CommentForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from blog.forms import UserForm
from django.contrib.auth import views
from django.contrib.auth.models import User
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
if registered:
views.login(request)
return redirect("/")
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request, 'registration/registration.html',{'user_form':user_form,registered:'registered'})
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
template_name = 'post_list.html'
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
def get_queryset(self):
return Post.objects.filter(author=self.request.user)
form_class = PostForm
form_class.author = self.request.user
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
model = Post
form_class = PostForm
class PostDeleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__isnull=True).order_by('created_date')
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
# comment.save()
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return redirect('post_detail',pk=post.pk)
else:
form = CommentForm
return render(request,'blog/comment_form.html',context={'form':form})
#login_required
def comment_approve(request,pk):
comment = get_object_or_404(Comment,pk=pk)
comment.approve()
return redirect('post_detail',pk=comment.post.pk)
#login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail', pk=post_pk)
#login_required
def post_publish(request,pk):
post = get_object_or_404(Post,pk=pk)
post.publish()
return redirect('post_detail',pk=pk)
I have tried absolutely everything and nothing worked. Can anyone please help me?
In your PostForm, remove author from the fields, so it cannot be edited by the user:
fields = ['title', 'text']
Then in your CreatePostView, remove the def get_queryset() method as it doesn't do anything here. You should instead override the form_valid method, that's where you get a chance to update the model that was created by the form.
def form_valid(self, form):
self.object = form.save(commit=False) # the form's save method returns the instance
self.object.author = self.request.user # here you assign the author
self.object.save()
return HttpResponseRedirect(self.get_success_url())
Alternatively, to keep as close as possible to the CreateView parent class:
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form) # this will call `CreateView`'s `form_valid()` method, which saves the form.
I will be really grateful if anyone can help to resolve the issue below.
I have the following Django project coding. The problem is: when the browser was given "/posts/remove/<post_id>/" or "/posts/edit/(<post_id>/" as the url, it will allow the second user (not owner) to perform the remove and edit jobs, respectively.
How can I allow only the owner of a new post to edit or delete the post?
account.models.py:
from django.db import models
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
posts.models.py:
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.utils.text import slugify
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='posts_created')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique_for_date='created')
image = models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True)
description = models.TextField(blank=True)
created = models.DateTimeField(default=timezone.now,
db_index=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='posts_voted',
blank=True)
status = models.CharField(max_length=10, default='published')
objects = models.Manager() # The default manager.
published = PublishedManager() # The Dahl-specific manager.
tags = TaggableManager()
class Meta:
ordering = ('-created',)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('posts:detail', args=[self.id, self.slug])
posts.view.py:
from django.views.decorators.http import require_POST
from django.shortcuts import render, redirect, get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
from django.core.context_processors import csrf
from .forms import PostCreateForm, EmailPostForm, CommentForm, SearchForm
from .models import Post
from actions.utils import create_action
#login_required
def post_create(request):
"""
View for creating a new post.
"""
if request.method == 'POST':
# form is sent
form = PostCreateForm(data=request.POST, files=request.FILES)
if form.is_valid():
cd = form.cleaned_data
new_item = form.save(commit=False)
# assign current user to the item
new_item.user = request.user
tags = form.cleaned_data['tags']
new_item.save()
for tag in tags:
new_item.tags.add(tag)
new_item.save()
create_action(request.user, 'created a post:', new_item)
messages.success(request, 'Post added successfully')
form = PostCreateForm()
else:
messages.error(request, 'Error adding new post')
else:
# build form
form = PostCreateForm(data=request.GET)
return render(request, 'posts/post/create.html', {'section': 'posts',
'form': form})
#login_required
def post_remove(request, post_id):
Post.objects.filter(id=post_id).delete()
return redirect('posts:mypost')
#login_required
def post_edit(request, post_id):
item = Post.objects.get(pk=post_id)
if request.method == 'POST':
form = PostCreateForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('posts:mypost')
else:
form = PostCreateForm(instance=item)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('posts/post/post_edit.html', args)
posts.urls.py
from django.conf.urls import url
from . import views
from .feeds import LatestPostsFeed
urlpatterns = [
url(r'^create/$', views.post_create, name='create'),
url(r'^remove/(?P<post_id>\d+)/$', views.post_remove, name='post_remove'),
url(r'^edit/(?P<post_id>\d+)/$', views.post_edit, name='post_edit'),
]
Add request.user == item.user check inside your method.
#login_required
def post_remove(request, post_id):
item = Post.objects.get(pk=post_id)
if request.user == item.user:
Post.objects.filter(id=post_id).delete()
return redirect('posts:mypost')
#login_required
def post_edit(request, post_id):
item = Post.objects.get(pk=post_id)
if request.user == item.user:
...
//write your code here
I have tried passing Album objects and song objects to my DetailView trying to get the DetailView working with both Album models and Song model. But anytime I try deleting a song my code cant seem to get the Song.objects.all(). I get a cannot find a song object in query or something like that
here are my url patterns:
urlpatterns =
[
/music/
url(r'^$', views.IndexView.as_view(), name='index'),
# /music/album_id/
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^register/$', views.UserFormView.as_view(), name='register'),
url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'),
#/music/album/2/
url(r'album/(?P<pk>[0-9]+)/$', views.AlbumUpdate.as_view(), name='album-update'),
#/music/album/add/delete/
url(r'^album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delete'),
#/music/album/album_id/add-song/
url(r'^album/(?P<pk>[0-9]+)/add-song/$', views.SongView.as_view(), name='song-add'),
# /music/album_id/song/delete/
url(r'^album/song/delete/(?P<song_id>[0-9]+)/$', views.SongDelete.as_view(), name='song-delete'),
views.py:
class IndexView(generic.ListView):
template_name = 'music/index.html'
context_object_name = 'all_albums'
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DetailView):
template_name = 'music/detail.html'
model = [Album, Song]
# context_object_name = 'all_songs'
def get_object(self, queryset=Song.objects.all()):
return queryset
def get_queryset(self):
return Album.objects.all()
class AlbumCreate(CreateView):
model = Album
fields = ['artist','album_title', 'genre', 'album_logo']
class AlbumUpdate(UpdateView):
model = Album
fields = ['artist','album_title', 'genre', 'album_logo']
class AlbumDelete(DeleteView):
model = Album
success_url = reverse_lazy('music:index')
class UserFormView(generic.View):
form_class = UserForm
template_name='music/registration_form.html'
#displays a blank form
def get(self, request):
form = self.form_class(request.GET)
return render(request, self.template_name, {'form': form})
#process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user=form.save(commit=False)
#cleand (Normalized) data
username= form.cleaned_data['username']
password=form.cleaned_data['password']
user.set_password(password)
user.save()
#Returns user object if cresentials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('music:index')
return render(request, self.template_name, {'form': form})
class SongView(CreateView):
# template_name = 'music/song_form.html'
model = Song
fields= ['title', 'album', 'audio_file', 'favorite']
class SongDelete(DeleteView):
model = Song
success_url = reverse_lazy('music:detail')
models.py:
from django.db import models
from django.core.urlresolvers import reverse
class Album(models.Model):
artist=models.CharField(max_length=250)
album_title=models.CharField(max_length=500)
genre=models.CharField(max_length=100)
album_logo=models.FileField()
def get_absolute_url(self):
return reverse('music:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.album_title + '_' + self.artist
class Song(models.Model):
title=models.CharField(max_length=250)
album=models.ForeignKey(Album, on_delete=models.CASCADE)
audio_file= models.FileField()
favorite=models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('music:detail' , kwargs={'pk': self.pk})
def __str__(self):
return self.title
please need help, been o this for a while now **wheww
If you need all songs in your DetailView you should pass them in the context; they are completely separate from the queryset of Albums you need to use to find the current object.
class DetailView(generic.DetailView):
template_name = 'music/detail.html'
model = Album
def get_context_data(self, *args, **kwargs):
context = super(DetailView, self).get_context_data(*args, **kwargs)
context['all_songs'] = Song.objects.all()
return context
(In future, please also post only relevant code and ensure that your indentation is correct.)