Cannot resolve keyword - html

I recevied an error when I request any page in the blog project I am working on, and I have no idea what is going wrong. Please help!
views.py
def post(request, id):
post = get_object_or_404(Post, id=id)
PostView.objects.get_or_create(user=request.user, post=post)
form = CommentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.instance.user = request.user
form.instance.post = post
form.save()
return redirect(reverse("post-detail", kwargs={
'id': post.id
}))
context = {
'post': post,
'form': form,
}
return render(request, 'post.html', context)
here is the model.py:
class Post(models.Model):
title = models.CharField(max_length=50)
overview = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = HTMLField()
author = models.ForeignKey(Author, on_delete=models.CASCADE)
#thumbanail = models.ImageField()
#comment_count = models.IntegerField(default= 0)
#view_count = models.IntegerField(default= 0)
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
def get_absolute_url(self):
return reverse('post-detail', kwargs={
'id': self.id
})
def get_update_url(self):
return reverse('post-update', kwargs={
'id': self.id
})
def get_delete_url(self):
return reverse('post-delete', kwargs={
'id': self.id
})
class Meta:
verbose_name_plural = 'Posts'
def __str__(self):
return f'{self.title}'
#property
def get_comments(self):
return self.comments.all().order_by('-timestamp')
#property
def comment_count(self):
return Comment.objects.filter(post=self).count()
#property
def view_count(self):
return PostView.objects.filter(post=self).count()
This is the I am receiving:
FieldError at /
Cannot resolve keyword 'comment_count' into field. Choices are: author, author_id, categories, comments, content, featured, id, overview, postview, timestamp, title
*

Like Hisahm__Pak said
remove #comment_count = models.IntegerField(default= 0)
comment_count = models.IntegerField(default= 0)
then save and make migrations
python manage.py makemigrations
python manage.py migrate
then run the server
python manage.py runserver

Related

How can I change the color on the like button in django?

I did create (like and dislike) in my project and I need it when someone clicks on the button. the color will change to blue
I saw something like that where I could create a variable called something like: is_liked = False, and I can place that in HTML by context to trigger it in (if condition) but it's not working with me so, How can I run the color on the like button?
views.py
# Detail question and Create comment
class QuestionDetail(DetailView, SingleObjectMixin):
template_name = 'community/question_view.html'
slug_field = 'ask_slug'
slug_url_kwarg = 'user_slug'
model = UserAsking
queryset = UserAsking.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['my_question'] = UserAsking.objects.get(title=self.object)
self_post = UserAsking.objects.get(title=self.object)
post_slug = UserAsking.objects.get(ask_slug=self_post.ask_slug)
context['summation'] = post_slug.likes.count() - post_slug.dislikes.count()
context['comment_form'] = CommentForm
comments_count = Comment.objects.filter(userasking=UserAsking.objects.get(title=self.object))
context['comments_count'] = comments_count.count()
# liked_post = User.objects.get(username=self.request.user.username).likes.exists()
# context['liked_post'] = liked_post
# disliked_post = User.objects.get(username=self.request.user.username).dislikes.exists()
# context['disliked_post'] = disliked_post
return context
def post(self, request, user_slug, *args, **kwargs):
my_question = UserAsking.objects.get(ask_slug=user_slug)
userprof = UserProfile.objects.get(userasking__ask_slug=user_slug)
comment_form = CommentForm(request.POST, instance=request.user)
name = "%s %s" % (self.request.user.first_name, self.request.user.last_name)
username = self.request.user.username
logo = self.request.user.userprofile.logo.url
c = CommentForm(self.request.POST).add_error('comment', 'error')
if comment_form.is_valid():
comment_form = Comment.objects.create(comment=self.request.POST.get('comment', None),
userasking_id=my_question.id,
userprofile_id=userprof.id,
name=name,
username=username,
logo=logo,
comment_slug=my_question.ask_slug
)
comment_form.save()
return redirect('community:question_view', comment_form.userasking.ask_slug)
return render(request, 'community/question_view.html', {'comment_form': comment_form,
'c': c})
# Like post function
class LikePost(View, SingleObjectMixin):
template_name = 'community/question_view.html'
def post(self, request, *args, **kwargs):
post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_slug'))
if post.dislikes.filter(username=request.user).exists():
post.dislikes.remove(request.user)
post.likes.add(request.user)
models.py
class UserAsking(models.Model):
userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')
date = models.DateTimeField(auto_now_add=True)
ask_slug = models.SlugField(max_length=100)
likes = models.ManyToManyField(User, related_name='likes', blank=True)
dislikes = models.ManyToManyField(User, related_name='dislikes', blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('community:question_view', kwargs={'user_slug': self.ask_slug})
def save(self, *args, **kwargs):
self.ask_slug = slugify(self.title)
super().save(*args, **kwargs)
elif post.likes.filter(username=request.user).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
return redirect(post.get_absolute_url())
# Dislike post function
class DisLikePost(View, SingleObjectMixin):
def post(self, request, *args, **kwargs):
post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_dislike_slug'))
if post.likes.filter(username=request.user).exists():
post.likes.remove(request.user)
post.dislikes.add(request.user)
elif post.dislikes.filter(username=request.user).exists():
post.dislikes.remove(request.user)
else:
post.dislikes.add(request.user)
return redirect(post.get_absolute_url())
how can I put the condition in the HTML page to check if is_liked is True or False?
In Django Html use template like this
{% if query_set.is_like %}
...do something
change back color like <h1 style:background:''blue></h1>
{% else %}
No change... <h1></h1>
{% endif%}
I had to add a condition to get_context where that way did work with me. this way I didn't see before but it works perfectly:
views.py
class QuestionDetail(DetailView, SingleObjectMixin):
template_name = 'community/question_view.html'
slug_field = 'ask_slug'
slug_url_kwarg = 'user_slug'
model = UserAsking
queryset = UserAsking.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['my_question'] = UserAsking.objects.get(title=self.object)
self_post = UserAsking.objects.get(title=self.object)
post_slug = UserAsking.objects.get(ask_slug=self_post.ask_slug)
context['summation'] = post_slug.likes.count() - post_slug.dislikes.count()
context['comment_form'] = CommentForm
comments_count = Comment.objects.filter(userasking=UserAsking.objects.get(title=self.object))
context['comments_count'] = comments_count.count()
context['is_liked'] = False
context['is_dislike'] = False
# context to like the post
if LikePost.as_view():
if post_slug.dislikes.filter(username=self.request.user).exists():
context['is_liked'] = False
elif post_slug.likes.filter(username=self.request.user).exists():
context['is_liked'] = True
else:
context['is_liked'] = False
# context to dis-like the post
if DisLikePost.as_view():
if post_slug.likes.filter(username=self.request.user).exists():
context['is_dislike'] = False
elif post_slug.dislikes.filter(username=self.request.user).exists():
context['is_dislike'] = True
else:
context['is_dislike'] = False
return context
def post(self, request, user_slug, *args, **kwargs):
my_question = UserAsking.objects.get(ask_slug=user_slug)
userprof = UserProfile.objects.get(userasking__ask_slug=user_slug)
comment_form = CommentForm(request.POST, instance=request.user)
name = "%s %s" % (self.request.user.first_name, self.request.user.last_name)
username = self.request.user.username
logo = self.request.user.userprofile.logo.url
c = CommentForm(self.request.POST).add_error('comment', 'error')
if comment_form.is_valid():
comment_form = Comment.objects.create(comment=self.request.POST.get('comment', None),
userasking_id=my_question.id,
userprofile_id=userprof.id,
name=name,
username=username,
logo=logo,
comment_slug=my_question.ask_slug
)
comment_form.save()
return redirect('community:question_view', comment_form.userasking.ask_slug)
return render(request, 'community/question_view.html', {'comment_form': comment_form,
'c': c})
# Like post function
class LikePost(View, SingleObjectMixin):
template_name = 'community/question_view.html'
def post(self, request, *args, **kwargs):
post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_slug'))
if post.dislikes.filter(username=request.user).exists():
post.dislikes.remove(request.user)
post.likes.add(request.user)
elif post.likes.filter(username=request.user).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
return redirect(post.get_absolute_url())
# Dislike post function
class DisLikePost(View, SingleObjectMixin):
def post(self, request, *args, **kwargs):
post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_dislike_slug'))
if post.likes.filter(username=request.user).exists():
post.likes.remove(request.user)
post.dislikes.add(request.user)
elif post.dislikes.filter(username=request.user).exists():
post.dislikes.remove(request.user)
else:
post.dislikes.add(request.user)
return redirect(post.get_absolute_url())
at this moment, I add a condition on the view I already handle as you see above in the QuestionDetail model.

__init__() got an unexpected keyword argument 'use_required_attribute'

I don't know why in some pages give me this error, and in others dosen't show me the error
I try to add a requiered attrbute but dosen't work, I don't how to add it
Model
class Vehicle(models.Model):
registration = models.CharField(max_length=200, default='')
vehicle_type = models.ForeignKey(VehicleType, on_delete=models.CASCADE)
def __str__(self):
return self.registration
class Meta:
verbose_name_plural = "Vehicles"
Form
class VehicleForm(ModelForm):
class Meta:
model = Vehicle
fields = ['registration', 'vehicle_type']
View
def vehicles(request):
vehicles = Vehicle.objects.all()
context = {
'title' : 'Vehicles',
'generic_objects' : vehicles
}
return render(request, 'vehicle/index.html',context)
def vehicle(request, id):
VehicleFormSet = modelformset_factory(Vehicle, exclude=(), extra=0)
#Add a vehicle
if request.method == 'POST':
formset = VehicleFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/favorita/vehicles')
#Edit the vehicle
else:
vehicles_search = Vehicle.objects.filter(id = id)
if vehicles_search:
formset = VehicleFormSet(queryset=vehicles_search)
else:
formset = formset_factory(VehicleForm)
return render(request, 'vehicle/details.html', {'formset': formset, 'id':id, 'title':"Vehicle"})
def delete_vehicle(request, id):
Vehicle.objects.filter(id=id).delete()
return HttpResponseRedirect('/favorita/vehicles')
The error image

how do i get the username variable from a user to use it in models.py django

I want to get the username variable of the logged in user to use it as the default value of create a Post form
in html i can access that by doing {{ user.username}}but when i do that as a default value in my models.py i get the default value as {{ user.username}} just as a text not a variable and when i remove the two curly braces it saids that user is not defined
models.py
class Payment(models.Model):
Author = models.CharField(max_length=255)
Product = models.CharField(max_length=255)
Payment_ID = models.BigIntegerField(default=0)
Status = models.CharField(max_length=5, default="X")
Review_result = models.CharField(max_length=255, default="Not yet reviewed")
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __unicode__(self):
return u'%s'% self.Status
def __str__(self):
return self.Status
and for the login i use the default form of django
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Payment
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
class PayForm(forms.ModelForm):
class Meta:
model = Payment
fields = ['Author', 'Product', 'Price', 'Payment_ID']
views.py
from django.shortcuts import render, render_to_response , get_object_or_404, redirect
from .models import Post
from django.contrib.auth import authenticate, login
from .forms import RegistrationForm, PayForm
# Create your views here.
def index(request):
posts=Post.objects.all()
return render(request, 'Index.html', {"posts": posts})
def post(request, slug):
return render(request, 'post.html', {'post': get_object_or_404(Post, slug=slug)})
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('index')
else:
form = RegistrationForm()
context = {'form' : form}
return render(request, 'registration/register.html', context)
def new_payment(request):
template ='payment.html'
form = PayForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('index')
else:
form = PayForm()
context = {
'form' : form,
}
return render(request, template, context)
In your view, you can override the initial values of form:
def new_payment(request):
template ='payment.html'
if request.method == 'POST'
form = PayForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
print('form invalid')
else:
form = PayForm({'Author':request.user.username})
context = {
'form' : form,
}
return render(request, template, context)

Column 'user_id' cannot be null django

I seek to create a post with a form where a registered user creates and inserts the primary key id in the db but this does not give me the following error Column 'user_id' can not be null
This is my models.py
class posts(models.Model):
titulo = models.CharField(max_length=180, unique=True)
slug = models.SlugField(max_length=180, editable=False)
contenido = models.TextField()
categoria = models.ForeignKey(categorias)
user = models.ForeignKey(User)
tags = models.CharField(max_length=200)
creado = models.DateTimeField(auto_now_add=True)
modificado = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.titulo)
super(posts, self).save(*args, **kwargs)
def __str__(self):
return self.titulo
This is my view.py
def addPosts(request):
if request.method == "POST":
form = addPostForm(request.POST)
if form.is_valid():
add = form.save(commit=False)
#add.user = User.objects.get(id=request.user)
add.save()
form.save_m2m()
return HttpResponseRedirect('/')
else:
form = addPostForm ()
ctx = {'form': form}
return render_to_response('posts/add.html', ctx, context_instance=RequestContext(request))
This is forms.py
class addPostForm(forms.ModelForm):
class Meta:
model = posts
exclude = {'slug','user', 'creado'}
some solution to this problem?
Request.user returns the current user object. No need to do a lookup.
add.user = request.user
in your view
If tying to the Django built-in user, you're going to want to do it differently from your model:
user = models.ForeignKey(User)
Consider defining this in your settings and instead, use:
user = models.ForeignKey(settings.AUTH_USER_MODEL)
See the documentation here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#referencing-the-user-model
This will also future-proof you if you decide to extend the Django base user model in the future.

Django IntegrityError: (1048, "Column 'user_id' cannot be null")

This is my models.py
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
class Meta:
db_table = 'CfitUser'
def __str__(self):
return "%s's profile" % self.user
#receiver(post_save, sender=User)
def create_cfituser(sender, instance, created, **kwargs):
if created:
Cfituser.objects.get_or_create(user=instance)
This is my views.py
#api_view(['GET', 'POST'])
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username = serializer.data['socialid'])
cfituser = Cfituser.objects.get(user = user)
cfituser.accesstoken = serializer.data['accesstoken']
cfituser.socialid = serializer.data['socialid']
cfituser.save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Whenever there is a HTTP Post request, my database tables are filled in as expected but this error keeps popping up. I've tried almost every solution available on SO but I'm stuck with this.
I have tried user = models.OneToOneField(User, null = True) but this leads to two entries in my database table, one with user_id = NULL and one with user_id = actualvalue.
Any suggestions on how to fix this?
Saving by default commits the entry to the database, to prevent that, pass commit=False to save(), and then do your customizations.
serializer = serializer.save(commit=False)
user, created = User.objects.get_or_create(username = serializer.socialid)
cfituser, created = Cfituser.objects.get_or_create(user = user)
# cfituser.user = user This line is unnecessary
cfituser.accesstoken = serializer.accesstoken
cfituser.socialid = serializer.socialid
cfituser.save()
serializer.save()
You are also duplicating your efforts because your signal will also attempt to create a user. If you are on django 1.5, use customized user model; and for social registration/oauth, use django-social-auth.
OneToOneField means, in Cfituser.user the reverse side of the relation will directly return a single object(user.cfituser gives Cfituser). SO Cfituser.user must be unique through out the table(one and only one).
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
def __unicode__(self):
return "%s's profile" % self.user.username
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username = serializer.data['socialid'])
Cfituser(user = user,accesstoken = serializer.data['accesstoken'],socialid = serializer.data['socialid']).save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)