Conditionally showing a button with DJANGO template language - html

I have a page that should show a button if the user is marked as "facturable" (billable), otherwise, the button should not appear. I tried the following code:
{% if form_experfil.facturable %}
<a href="{% url 'incid:xtodo' %}?pagref=factdatshow" type="button"
class="btn btn-primary waves-effect"> Consultar datos de facturación</a>
{% endif %}
But it keeps showing. This and other fails make me think that the {% if %} tag behaviour isnh't as straightforward as I thought, and it does not just clip the html code down to the endif tag, but something gets rendered first. Is there somewhere where this is formally documented without mystical references?. Is there a way to just show this button when the customer has this data and not show it otherwise?.
This is the view:
def perfil_view(request):
perfil = ExUserProfile.objects.get(user=request.user)
facturar = perfil.facturable
if facturar:
factdat = Factdat.objects.get(cliente=request.user)
if request.method == 'POST':
form_perfil = perfilEditForm(data=request.POST, instance=request.user)
form_experfil = experfilEditForm(data=request.POST, instance=perfil)
if facturar:
form_factdat = factdatEditForm(data=request.Post, instance=perfil)
if all([form_perfil.is_valid(), form_experfil.is_valid(), form_factdat.is_valid()]):
form_perfil.save()
form_experfil.save()
form_factdat.save(commit=facturar)
return HttpResponseRedirect('incid/perfil')
else:
form_perfil = perfilEditForm(instance=request.user)
form_experfil = experfilEditForm(instance=perfil)
if facturar:
form_factdat = factdatEditForm(instance=factdat)
template = "incid/perfil.html"
if facturar:
return render(request, template, {
'form_perfil': form_perfil,
'form_experfil': form_experfil,
'form_factdat': form_factdat
})
else:
return render(request, template, {
'form_perfil': form_perfil,
'form_experfil': form_experfil
})
and these are the models:
eclass ExUserProfile(models.Model):
user = models.OneToOneField(User,
primary_key=True,
on_delete=models.DO_NOTHING)
logo = ResizedImageField(size=[200, 200],
crop=['middle', 'center'],
quality=75, upload_to='static/logos/',
default='logos/no-img.jpg')
facturable = models.BooleanField(default=False)
def __str__(self):
return str(self.user)
class Factdat(models.Model):
cliente = models.OneToOneField(User,
verbose_name='cliente_fact',
primary_key=True,
default='',
on_delete=models.DO_NOTHING)
nomfact = models.CharField(max_length=240,
verbose_name='nomfact')
niffact = models.CharField(max_length=16,
verbose_name='niffact')
mailfact = models.EmailField(max_length=254,
verbose_name='mailfact')
telfact = models.CharField(max_length=24,
verbose_name='telfact')
persfact = models.CharField(max_length=128,
verbose_name='persfact')
class Meta:
verbose_name = "Fact_dat"
verbose_name_plural = "Fact_datos"
def __str__(self):
return str(self.cliente)
and just in case, here is the full page:
def perfil_view(request):
perfil = ExUserProfile.objects.get(user=request.user)
facturar = perfil.facturable
if facturar:
factdat = Factdat.objects.get(cliente=request.user)
if request.method == 'POST':
form_perfil = perfilEditForm(data=request.POST, instance=request.user)
form_experfil = experfilEditForm(data=request.POST, instance=perfil)
if facturar:
form_factdat = factdatEditForm(data=request.Post, instance=perfil)
if all([form_perfil.is_valid(), form_experfil.is_valid(), form_factdat.is_valid()]):
form_perfil.save()
form_experfil.save()
form_factdat.save(commit=facturar)
return HttpResponseRedirect('incid/perfil')
else:
form_perfil = perfilEditForm(instance=request.user)
form_experfil = experfilEditForm(instance=perfil)
if facturar:
form_factdat = factdatEditForm(instance=factdat)
template = "incid/perfil.html"
if facturar:
return render(request, template, {
'form_perfil': form_perfil,
'form_experfil': form_experfil,
'form_factdat': form_factdat
})
else:
return render(request, template, {
'form_perfil': form_perfil,
'form_experfil': form_experfil
})

Related

Data not saving in database in Django

I am trying to save data into the database from the website. My web page is taking the data (image from my system) but in the database, it's not showing up. If I add manually then it's creating a new user entry and storing it.
Here are my files:
models.py
class Details(models.Model):
name = models.CharField(max_length=122)
username = models.CharField(max_length=122)
email = models.EmailField(max_length=122)
password = models.CharField(max_length=20)
def __str__(self):
return self.name
class Image_Data(models.Model):
img_User = models.ForeignKey(
Details, blank=True, null=True, on_delete=models.CASCADE)
img_password = models.ImageField(null=True, blank=True)
def __str__(self):
return str(self.img_password)
forms.py
class ImageForm(ModelForm):
class Meta:
model = Image_Data
fields = ('img_password',)
labels = {
'img_password': 'Add your image ',
}
widgets = {
'img_password': forms.FileInput(attrs={'class': 'form-control', 'placeholder': 'Upload from device'})
}
views.py
def register_new_b(request):
saved = False
if request.method == "POST":
# take whatever is posted to the Details Form
form = ImageForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Your message has been sent!')
return HttpResponseRedirect('/register_new_b?saved=True')
else:
form = ImageForm()
if 'saved' in request.GET: # sends saved var in GET request
saved = True
return render(request, 'register2.html', {'form': form, 'saved': saved})
Here is what I get in database upon saving the image
In the line:
form = ImageForm(request.POST)
you need to add request.FILES:
form = ImageForm(request.POST, request.FILES)
*Edit
An working example inside my own code:
in views.py
def change_profile_pic(request):
context = dict()
if request.method == 'POST':
form = ProfilePictureForm(request.POST, request.FILES)
if form.is_valid():
form.store(request.user.id)
form = ProfilePictureForm()
context['success_message'] = 'Picture changed'
request.user.employee.refresh_from_db()
else:
context['error_message'] = 'Unable to change picture'
else:
form = ProfilePictureForm()
context['form'] = form
return render(request, 'template.html', context)
in forms.py
class ProfilePictureForm(forms.Form):
image = forms.ImageField(required=True)
def store(self, user_id):
user = User.objects.get(id=user_id)
user.employee.profile_picture = self.cleaned_data['image']
user.employee.save()
in models.py
class Employee(models.Model):
user = models.OneToOneField(User, blank=False, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='profile_pictures', max_length=200, null=True, blank=True)
But I have also experimented with ModelForm, and this also saves the file correcly

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.

Cannot resolve keyword

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

__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)