I am fairly new to Django and am following the try django 1.10 series by CodingEntrepreneurs on youtube and therefore, am unable to solve the problem. I am only seeing the submit button, while the input field is not showing. Below is the code that I am working on.
forms.py
from django import forms
class SubmitUrlForm(forms.Form):
url = forms.CharField(label="Submit Url")
views.py
from .forms import SubmitUrlForm
def home_view_fbv(request, *args, **kwargs):
if request.method == 'POST':
print(request.POST)
return render(request, "app/home.html", {})
class HomeView(View):
def get(self, request, *args, **kwargs):
the_form = SubmitUrlForm()
context = {
"title": "Submit Url",
"form": the_form
}
return render(request, "app/home.html", context)
def post(self, request, *args, **kwargs):
form = SubmitUrlForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
return render(request, "app/home.html", {})
app/home.html
<div style= 'width: 800px; margin: 0 auto;'>
<h1> {{ title }} </h1>
<form method = 'POST' action = '.'> {% csrf_token %}
{{form.as_p}}
<input type= 'submit' value= 'Shorten' >
</form>
</div>
models.py
from django.db import models
from .utils import code_generator, create_shortcode
from django.conf import settings
SHORTCODE_MAX = getattr(settings, "SHORTCODE_MAX", 15)
class surlShortManager(models.Manager):
def all(self, *args,**kwargs):
qs_main = super(surlShortManager,self).all(*args, **kwargs)
qs = qs_main.filter(active = True)
return as
def refresh_shortcodes(self, items= 100):
qs = surlShort.objects.filter(id__gte = 1)
if items is not None and isinstance(items, int):
qs = qs.order_by('-id')[:items]
new_codes = 0
for q in qs:
q.shortcode = create_shortcode(q)
print(q.id)
q.save()
new_codes += 1
return "New codes made: {i}".format(i = new_codes)
class surlShort(models.Model):
url = models.CharField(max_length = 500)
shortcode = models.CharField(max_length = SHORTCODE_MAX, unique = True, null
= False, blank = True)
updated = models.DateTimeField(auto_now = True)
timestamp = models.DateTimeField(auto_now_add = True)
active = models.BooleanField(default = True)
objects = surlShortManager()
def save(self, *args, **kwargs):
if self.shortcode is None or self.shortcode == '':
self.shortcode = code_generator()
super(surlShort, self).save(*args, **kwargs)
def __str__(self):
return str(self.url)
Change your HomeView to this
from django.views import View
from django.http import HttpResponseRedirect
from .forms import SubmitUrlForm
class HomeView(View):
form_class = SubmitUrlForm
context = {
"title": "Submit Url",
"form": form_class
}
template_name = 'app/home.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
print(form.cleaned_data)
return HttpResponseRedirect('/success/')
return render(request, self.template_name, context)
Related
i am working on a project .
i use crispy_form in my project.
it is my cars urls.py::
from django.urls import path
from . import views
app_name = 'cars'
urlpatterns = [
path('', views.CarsListView.as_view(), name='cars'),
path('add-car/', views.AddCarView.as_view(), name='add_car'),
path('car/', views.RepairsListView.as_view(), name='car_detail'),
path('car/<int:pk>/update/', views.UpdateCarView.as_view(), name='update_car'),
path('car/<int:pk>/delete/', views.DeleteCarView.as_view(), name='delete_car'),
path('car/<int:pk>/new-repair/', views.AddRepairView.as_view(), name='add_repair'),
]
it is my cars views.py ::
from .models import Car, Repair
from django.views.generic import ListView, UpdateView, DeleteView, CreateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.contrib import messages
class CarsListView(LoginRequiredMixin, ListView):
model = Car
template_name = 'cars/cars.html'
context_object_name = 'cars'
paginate_by = 10
def get_queryset(self):
if self.request.GET.get('q'):
q = self.request.GET.get('q')
make_results = self.model.objects.filter(
user=self.request.user, make=q).order_by('-pk')
model_results = self.model.objects.filter(
user=self.request.user, model=q).order_by('-pk')
if make_results.exists():
return make_results
elif model_results.exists():
return model_results
else:
return self.model.objects.none()
return self.model.objects.filter(user=self.request.user).order_by('-pk')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['q'] = self.request.GET.get('q', '')
return context
class AddCarView(LoginRequiredMixin, CreateView):
model = Car
fields = ['make', 'model', 'vrn', 'year']
success_url = '/'
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
class DeleteCarView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Car
success_url = '/'
def test_func(self):
if self.get_object().user == self.request.user:
return True
return False
def delete(self, request, *args, **kwargs):
success_message = f'Car {self.get_object()} has been deleted'
messages.success(self.request, success_message)
return super().delete(request, *args, **kwargs)
class UpdateCarView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Car
fields = ['make', 'model', 'vrn', 'year']
success_message = 'Car info has been updated'
def get_success_url(self, **kwargs):
row = self.request.GET.get('row')
p = self.request.GET.get('p')
q = self.request.GET.get('q')
options = '?p=' + p + '&row=' + row
options += '&q=' + q
messages.success(self.request, self.success_message)
return reverse_lazy('car_detail') + options
def test_func(self):
if self.get_object().user == self.request.user:
return True
return False
class AddRepairView(LoginRequiredMixin, CreateView):
model = Repair
fields = ['date', 'description']
success_message = 'New repair has been added'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['car'] = Car.objects.get(id=self.kwargs['pk'])
return context
def form_valid(self, form, **kwargs):
form.instance.car = Car.objects.get(id=self.kwargs['pk'])
return super().form_valid(form)
def get_success_url(self, **kwargs):
row = self.request.GET.get('row')
p = self.request.GET.get('p')
q = self.request.GET.get('q')
options = '?p=' + p + '&row=' + row
options += '&q=' + q
return reverse_lazy('car_detail') + options
class RepairsListView(LoginRequiredMixin, ListView):
model = Repair
paginate_by = 10
def __get_car(self):
cars = Car.objects.filter(user=self.request.user).order_by('-pk')
if self.request.GET.get('q'):
q = self.request.GET.get('q')
make_results = Car.objects.filter(
user=self.request.user, make=q).order_by('-pk')
model_results = Car.objects.filter(
user=self.request.user, model=q).order_by('-pk')
if make_results.exists():
cars = make_results
elif model_results.exists():
cars = model_results
id = int(self.request.GET.get('row')) - 1
page = int(self.request.GET.get('p')) - 1
id = id + page * 10
return cars[id]
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['car'] = self.__get_car()
context['row'] = self.request.GET.get('row')
context['p'] = self.request.GET.get('p')
context['q'] = self.request.GET.get('q')
return context
def get_queryset(self, **kwargs):
return self.model.objects.filter(car=self.__get_car()).order_by('-pk')
and it is my users views.py ::
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm
from django.contrib.auth import login, authenticate
from django.views.generic import CreateView
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
class RegisterUser(CreateView):
form_class = UserCreationForm
def get(self, request, *args, **kwargs):
return render(request, 'users/register-user.html', {'form': UserCreationForm()})
def post(self, request, *args, **kwargs):
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, f'Welcome, {username}!')
return redirect('cars')
return render(request, 'users/register-user.html', {'form': form})
class ChangePassword(LoginRequiredMixin, CreateView):
form_class = PasswordChangeForm
template_name = 'users/change-password'
def get(self, request, *args, **kwargs):
form = PasswordChangeForm(request.user)
return render(request, 'users/change-password.html', {'form': form})
def post(self, request, *args, **kwargs):
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user)
messages.success(request, 'Password changed!')
return redirect('cars')
return render(request, 'users/change-password.html', {'form': form})
and when i want to cars page i have error :: ((NoReverseMatch at /cars/))
and
(Reverse for 'login' not found. 'login' is not a valid view function or pattern name.)
can anyone help me??
please help me guys!!!!!!
Try to include your cars and user Url into your base urls.py.
from yourproject.cars import urls as car_urls
from yourproject.users import urls as users_urls
and then add the following to your base urlpatterns
url(r"^cars/", include((car_urls)),
url(r"^users/", include((user_urls)),
I have two apps, here we will call them blog and comments.
Comments has a Comment model. Blog has a blog Model. Comments has a CommentForm. Blog has a DetailView.
I want my CommentForm to appear on by Blog DetailView, so people can submit comments from the blog detail page.
The form renders OK - it makes a POST request, it redirects to get_success_url() but (I've added a couple of prints to views.py - see below) in testing in views.py to see if the form data is received I see the form.is_valid() path is not met, and I don't understand why.
I'm essentially trying to follow this, the 'alternative better solution':
https://docs.djangoproject.com/en/2.2/topics/class-based-views/mixins/#using-formmixin-with-detailview
blog/views.py
class CommentLooker(SingleObjectMixin, FormView):
template_name = 'blogs/blog_detail.html'
form_class = CommentForm
model = blog
def get_object(self):
#self.team = get_object_or_404(team, team_id=self.kwargs['team_id'])
#queryset_list = blog.objects.filter(team = self.team)
team_id_ = self.kwargs.get("team_id")
blog_id_ = self.kwargs.get("blog_id")
return get_object_or_404(blog, blog_id=blog_id_, team=team_id_)
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
return super(CommentLooker, self).post(request, *args, **kwargs)
def get_success_url(self):
return reverse('blogs:teams')
class blogDisplay(View):
def get(self,request,*args,**kwargs):
view = blogFromteamContentView.as_view()
return view(request, *args, **kwargs)
def post(self,request,*args,**kwargs):
view = CommentLooker.as_view()
return view(request,*args,**kwargs)
class blogFromteamContentView(LoginRequiredMixin, DetailView):
model = blog
template_name = 'blogs/blog_detail.html'
# override get_object so we can use blog_id when we use this class in urls.py
# otherwise DetailViews expect 'pk' which defaults to the primary key of the model.
def get_object(self):
team_id_ = self.kwargs.get("team_id")
blog_id_ = self.kwargs.get("blog_id")
return get_object_or_404(blog, blog_id=blog_id_, team=team_id_)
def get_context_data(self, **kwargs):
context = super(blogFromteamContentView, self).get_context_data(**kwargs)
team_id_ = self.kwargs.get("team_id")
blog_id_ = self.kwargs.get("blog_id")
# get the list of blogs for a given blog id and team id combination.
context['queryset'] = get_object_or_404(blog, blog_id=blog_id_, team=team_id_)
# get and set things related to ability to associate comments to a blog.
initial_data = {
"content_type": blog.get_content_type,
"object_id": blog.blog_id
}
comments = blog.comments # uses the #property set in this class.
comment_form = CommentForm(self.request.POST or None, initial=initial_data)
if comment_form.is_valid():
print(comment_form.cleaned_data)
else:
print('invalido!')
context['comment_form'] = comment_form
return context
blog/models.py
class Blog(models.Model):
team= models.ForeignKey(Team, on_delete=CASCADE)
blog_id = models.AutoField(primary_key=True)
blog_name = models.CharField(
max_length=100, verbose_name='Blog Name')
blog/urls.py
path('teams/<int:team_id>/blogs/<int:blog_id>/', blog.blogDisplay.as_view(), name='detail'),
blog_detail.html
<div>
<p class="lead"> Comments </p>
<form method="POST" action="."> {% csrf_token %}
{{ comment_form}}
<input type="submit" value="Post Comment" class="btn btn-primary">
</form>
<hr/>
{% for comment in blog.comments.all %}
<blockquote class="blockquote">
<p>{{ comment.content }}</p>
<footer class="blockquote-footer"> {{ comment.user }} | {{ comment.timestamp|timesince }} ago </footer>
</blockquote>
<hr/>
{% endfor %}
comments/forms.py
from django import forms
class CommentForm(forms.Form):
content_type = forms.CharField(widget=forms.HiddenInput)
object_id = forms.IntegerField(widget=forms.HiddenInput)
parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False)
content = forms.CharField(widget=forms.Textarea)
edit:
after using print(comment_form.errors): object_idEnter a whole number.
suggesting my initial_data might be the problem. In fact both content_type and object_id in my initial_data were problems. I was asking for blog.blog_id - I.e. using the class, not an instance. So I changed
get_context_data:
def get_context_data(self, **kwargs):
context = super(blogFromteamContentView, self).get_context_data(**kwargs)
team_id_ = self.kwargs.get("team_id")
blog_id_ = self.kwargs.get("blog_id")
# get the list of blogs for a given blog id and team id combination.
context['queryset_list_recs'] = get_object_or_404(blog, blog_id=blog_id_, team=team_id_)
instance = get_object_or_404(blog, blog_id=blog_id_, team=team_id_)
initial_data = {
"content_type": instance.get_content_type,
"object_id": blog_id_
}
and to my views.py:
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
comment_form = CommentForm(self.request.POST)
if comment_form.is_valid():
print('valido')
c_type = comment_form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = comment_form.cleaned_data.get('object_id')
content_data = comment_form.cleaned_data.get("content")
new_comment, created = Comment.objects.get_or_create(
user = self.request.user,
content_type = content_type,
object_id = obj_id,
content = content_data
)
else:
print('postinvalido!')
return super(CommentLooker, self).post(request, *args, **kwargs)
This (inappropriate print statements aside) now appears to give intended behaviour.
after using print(comment_form.errors):
object_id
List item
Enter a whole number.
suggesting my initial_data might be the problem. In fact both content_type and object_id in my initial_data were problems. I was asking for blog.blog_id - I.e. using the class, not an instance. So I changed
get_context_data:
def get_context_data(self, **kwargs):
context = super(blogFromteamContentView, self).get_context_data(**kwargs)
team_id_ = self.kwargs.get("team_id")
blog_id_ = self.kwargs.get("blog_id")
# get the list of blogs for a given blog id and team id combination.
context['queryset_list_recs'] = get_object_or_404(blog, blog_id=blog_id_, team=team_id_)
instance = get_object_or_404(blog, blog_id=blog_id_, team=team_id_)
initial_data = {
"content_type": instance.get_content_type,
"object_id": blog_id_
}
and to my views.py:
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
comment_form = CommentForm(self.request.POST)
if comment_form.is_valid():
print('valido')
c_type = comment_form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = comment_form.cleaned_data.get('object_id')
content_data = comment_form.cleaned_data.get("content")
new_comment, created = Comment.objects.get_or_create(
user = self.request.user,
content_type = content_type,
object_id = obj_id,
content = content_data
)
else:
print('postinvalido!')
return super(CommentLooker, self).post(request, *args, **kwargs)
This (inappropriate print statements aside) now appears to give intended behaviour. I'm unclear why an instance of CommentForm needs to be created inside the post method - it feels like I'm doing something wrong here.
im only student so please bear with me. I already posted another topic about this but in function view. now i want to how do i convert this try exception to a class view and also add that comment form.
here's my views.py def
def BookDetail(request, id):
most_recent = Book.objects.order_by('-timestamp')[:3]
book= get_object_or_404(Book, id=id)
form = CommentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.instance.user = request.user
form.instance.post = book
form.save()
return redirect(reverse("book-detail", kwargs={
'id': book.pk
}))
if request.user.is_anonymous:
user_membership = None
else:
try:
user_membership = Customer.objects.get(user=request.user)
except Customer.DoesNotExist:
user_membership = None
context = {
'user_membership': user_membership,
'form': form,
'book': book,
'most_recent': most_recent,
}
return render(request, 'catalog/book_detail.html', context)
here is my new class view
class BookDetailView(NeverCacheMixin, generic.DetailView):
model = Book
UPDATE POST
here's my models.py..
class Book(models.Model):
slug = models.SlugField(unique=True, help_text="Enter BIC Code", null=True)
title = models.CharField(max_length=200) #more fields after this
timestamp = models.DateTimeField(default=timezone.now)
activeReference = models.ManyToManyField(Membership)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('book-detail', kwargs={'slug': self.slug})
#property
def get_comments(self):
return self.comments.all().order_by('-timestamp')
#property
def pages(self):
return self.page_set.all()
class Page(models.Model):
slug = models.SlugField(max_length=50)
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
preview = models.FileField(upload_to='book_content', validators=[pdf_file_extension], help_text="PDF File Only")
def __str__(self):
return self.slug
def get_absolute_url(self):
return reverse('page-detail',
kwargs={
'book_slug': self.book.slug,
'page_slug': self.slug
})
here's my URL pattern
urlpatterns = [
path('', views.index, name='index'),
path('books/', views.BookListView.as_view(), name='book-list'),
path('book-detail/<slug>', views.BookDetailView.as_view(), name='book-detail'),
path('book-detail/<book_slug>/<page_slug>', views.PageDetailView.as_view(), name='page-detail'),
path('search/', views.Search, name='search'),
]
and my book_detail.html
{% for content in book.pages %}
Read
{% endfor %}
{% else %}
CBV are good when you need inheritance or need to deal with different HTTP methods to have the same route. If that is not the case, a FBV is a better choice. That being said, for what you are trying to do, you should just a FormView that will handle everything about a post and forms.
Something like:
class BookViewSet(FormView):
form = CommentForm
template_name = 'catalog/book_detail.html'
def form_valid(self, form):
self.send_mail(form.cleaned_data)
return super(BookViewSet, self).form_valid(form)
If you are handling forms, you should be using CreateView or FormView not DetailView. Here is an implementation example, as you can see is a little complex for someone new to Django:
from django.views.generic import CreateView
class BookDetailView(NeverCacheMixin, CreateView):
form_class = CommentForm
template_name = 'catalog/book_detail.html'
def dispatch(self, request, *args, **kwargs):
book_slug = self.kwargs.get('slug') # url variables are stored in self.kwargs
self.book = get_object_or_404(Book, slug=book_slug) # attach book to your view
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
# context data passed to template
kwargs['book'] = self.book
kwargs['most_recent'] = Book.objects.order_by('-timestamp')[:3]
if request.user.is_anonymous:
user_membership = None
else:
try:
user_membership = Customer.objects.get(user=self.request.user)
except Customer.DoesNotExist:
user_membership = None
kwargs['user_membership'] = user_membership
return super().get_context_data(**kwargs)
def form_valid(self, form):
instance = form.save(commit=False)
instance.user = self.request.user
instance.post = self.book
instance.save()
return redirect(self.book.get_absolute_url())
I am trying to have users delete and edit post they create. I was told "Post.user needs to be an object instance what you wrote is incorrect." but I am still newer to django and would like to know the steps to do this as I created this project with some help.
here is my models
from django.db import models
from django.db.models import Count, QuerySet, F
from django.utils import timezone
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
from markdown_deux import markdown
from django.utils.safestring import mark_safe
from taggit.managers import TaggableManager
from comments.models import Comment
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 )
title = models.CharField(max_length=75)
slug = models.SlugField(unique=True)
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
description = models.TextField()
tags = TaggableManager()
public = models.BooleanField(default=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
class Meta:
ordering = ["-created", "-updated" ]
def get_markdown(self):
description = self.description
markdown_text = markdown(description)
return mark_safe(markdown_text)
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
Here is my views
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.core.exceptions import PermissionDenied
from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post
def post_main(request):
return render(request, "base2.html")
#login_required
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
#login_required
def post_update(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Post Saved")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form":form
}
return render(request, "post_form.html", context)
def post_user(request):
return HttpResponse("<h1>Users Post</h1>")
#login_required
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user = request.user,
content_type= content_type,
object_id = obj_id,
content = content_data,
parent = parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"comments": comments,
"comment_form":form,
}
return render(request, "post_detail.html", context)
#login_required
def post_feed(request):
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query)|
Q(tags__icontains=query)|
Q(content__icontains=query)|
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
}
return render(request, "post_feed.html", context)
#login_required
def post_delete(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if request.user == Post.user:
instance.delete() # or save edits
messages.success(request, "Successfully Deleted")
return redirect("posts:feed")
else:
raise PermissionDenied # import it from django.core.exceptions
return redirect("posts:feed")
def privacy(request):
return render(request, "privacy.html")
def post_about(request):
return HttpResponse("<h1>About Page</h1>")
def home(request):
return render(request, "base2.html")
Let me know if any other information is needed.
You are almost there.
in delete, your check should be:
request.user == instance.user
instead of
request.user == Post.user
Similarly in post_update, you could do:
if instance.user == request.user:
#Now, allow update
Also, it might be a good idea to check for the request type. Example:
if request.method == "POST":
This way, this check would only happen if it is a POST type
I am attempting to save simple data based on a button submission. But i keep getting following error:
TypeError at /exercise/1/
save() got an unexpected keyword argument 'commit'
models.py:
class StrategyHistory(models.Model):
user = models.ForeignKey(User)
strategy = models.ForeignKey(Strategies)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = datetime.datetime.today()
self.modified = datetime.datetime.today()
return super(StrategyHistory, self).save(*args, **kwargs)
def __unicode__(self):
return self.strategy.name
views.py:
def exercise_view(request, pk):
template_name = 'mobileApp/page/exercise.html'
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('mobile_user_login'))
strategy = Strategies.objects.get(pk=pk)
context = {
'strategy':strategy,
}
if request.method == 'POST':
strategyhistory = StrategyHistory()
entry = strategyhistory.save(commit=False)
entry.user = self.request.user
entry.strategy = Strategies.objects.get(id=pk)
entry.save()
if pk < 5:
return HttpResponseRedirect(reverse('mobile_exercise', kwargs={'pk':pk+1}))
else:
return HttpResponseRedirect(reverse('mobile_comeback_later'))
return render_to_response(template_name,
context,
context_instance = RC( request, {} ))
html-file:
<form action="" method="post">{% csrf_token %}
Prøv igen
<button type="submit" value="submit" data-inline="true" data-transition="flow" data-icon="check" data-theme="b">Fortsæt</button>
</form>
I am running Django 1.6.2
Your view use StrategyHistory model incorrect. That is the use of forms. This is correct.
def exercise_view(request, pk):
template_name = 'mobileApp/page/exercise.html'
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('mobile_user_login'))
strategy = Strategies.objects.get(pk=pk)
context = {
'strategy':strategy,
}
if request.method == 'POST':
strategyhistory = StrategyHistory.objects.create(
user=request.user,
strategy=strategy)
if pk < 5:
return HttpResponseRedirect(reverse('mobile_exercise', kwargs={'pk': pk + 1}))
else:
return HttpResponseRedirect(reverse('mobile_comeback_later'))
return render_to_response(template_name,
context,
context_instance = RC( request, {} ))
Also you cannot use self.request in that view. There is no self declared.
May be this is what you want:
class StrategyHistory(models.Model):
user = models.ForeignKey(User)
strategy = models.ForeignKey(Strategies)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.strategy.name