Am having tables in database like EmployerRegistration and PostJob. Am relating those tables with empid(foreign key of PostJob). Using this empid I need to PostJob at maximum of 5.I want to display alert message like number of post available while login. Some one help how to give views for this condition.
models.py
class EmployerRegistration(models.Model):
username=models.CharField(max_length=30)
password=models.CharField(max_length=30)
class PostJob(models.Model):
emp = models.ForeignKey(EmployerRegistration)
jobtitle = models.CharField(max_length=30)
jobsummary = models.TextField()
key_skills = models.CharField(max_length=30)
experince = models.IntegerField(default=0)
salary = models.IntegerField(default=0)
views.py
def your_view(request, empid):
msg=""
if request.method == "POST":
jobs = PostJob.objects.filter(emp_id=empid).count()
if jobs <= 5:
//save
else:
msg = Your not allow to add new post job.
return render(request, 'page.html', {'msg': msg})
template
<script>
$(document).ready(function(){
var msg = {{msg}}
if(msg != ""){
alert(msg);
}
});
</script>
Related
I have an app where I want to display in template last 5 comments for every message. How can I get last n comments that matches a specific message? I've tried: comments_all = Comments.objects.all().order_by('-id')[:5] but it just returns 5 last comments regardless of message.
models
class Message(models.Model):
host = models.ForeignKey(NewUser, on_delete=models.CASCADE)
body = models.TextField(max_length=1000)
created = models.DateTimeField(auto_now_add=True)
class Comments(models.Model):
message = models.ForeignKey(Message, on_delete=models.CASCADE)
publisher = models.ForeignKey(NewUser, on_delete=models.CASCADE)
body = models.TextField(max_length=300)
created = models.DateTimeField(auto_now_add=True)
views
def home(request):
messages_all = Message.objects.all()
comments_all = Comments.objects.all()
form = AddComments()
if request.method == "POST":
form = AddComments(request.POST)
if form.is_valid():
comment = form.save(commit=False)
messageid = request.POST.get('message_id')
comment.message_id = messageid
comment.publisher = request.user
comment.save()
return redirect('home')
last_five = Message.objects.all().order_by('-id')[:10]
context = {
'messages_all':messages_all,
'comments_all':comments_all,
'form':form,
'last_five':last_five
}
return render(request,'base/home.html', context)
def home(request):
messages_all = Message.objects.all()
...
# construct a dictionary where each message.id is the key
# and the value is the queryset for last 5 comments for the
# matching message
message_last_five = {
msg.id: Comments.objects.filter(message=msg).order_by('-created')[:5]
for msg in messages_all
}
# add message_last_five to your context
context = {
'messages_all': messages_all,
'comments_all': comments_all,
'message_last_five': message_last_five,
'form': form,
'last_five': last_five
}
return render(request,'base/home.html', context)
Although this perhaps can get you what you need - know that this is not an optimal solution because this is quite an expensive query to run.
And you can also achieve relatively the same thing with django templating instead too.
i have created a list in which it shows the name of all groups present when you click it redirect to another page with group id, when i create a post i need to specify which group it is, i am getting the id in url of page but i have no idea how to define group object with that url,
views
def create(request):
if request.method == "POST":
name = request.user
author = request.user
message = request.POST['message']
message = comments(user=author,message=message,name=name,group_id=2)
message.save()
return HttpResponse('')
instead of group_id=2 or hardcode it , can i automatically take the id from url of the page like we do in request.user
models
class group(models.Model):
group_name = models.CharField(max_length=100)
group_user = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return f'{self.id} group'
class comments(models.Model):
userId = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
group = models.ForeignKey(group,on_delete=models.CASCADE,null=True)
user = models.ForeignKey(User,on_delete=models.CASCADE)
message = models.TextField()
date = models.TimeField(auto_now_add=True)
def __str__(self):
return f'{self.user} comments'
i have been trying day and night and couldnt solve, all the genius programmers out there pls give me a solution
urls.py
urlpatterns = [
path('create/<int:group_id>', views.create)
]
views.py
def create(request, group_id):
if request.method == "POST":
name = request.user
author = request.user
message = request.POST['message']
message = comments(user=author,message=message,name=name,group_id=group_id)
message.save()
return HttpResponse('')
As an example if you are running your app on localhost going to localhost:8000/create/1 will make group_id = 1, going to localhost:8000/create/2 will make group_id = 2 etc..
I'm pretty new to django and working on a blog based project where user can add ratings to specific type of review post.For example giving stars are enabled for restaurant but not for tech stores.
I have created two different form for "review" and "star" model. I want to rate the restaurant using the model named "star" and do it in same template.But I'm having difficulties to do that.
Im getting this error.
"The above exception (NOT NULL constraint failed: reviews_star.post_id_id) was the direct cause of the following exception:"
How do I get the review id that I just save with "review_form.save()".
my review model kinda looks like this (Removed other attributes which aren't related to this problem):
class Review(models.Model):
review_title = models.CharField(verbose_name='Title', max_length=100)
review_body = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
restaurant_or_techstore = models.CharField(verbose_name='Foods or Travel',max_length=20)
slug = models.SlugField(null=False,unique=True,max_length = 300)
My rating model looks like this:
class Star(models.Model):
post_id = models.ForeignKey(Review, on_delete = models.CASCADE )
food = models.FloatField(verbose_name='Food',null=False)
service = models.FloatField(verbose_name='Food',null=False)
cleanliness = models.FloatField(verbose_name='Food',null=False)
and my view :
def CreateReview(request):
ImageFormSet = modelformset_factory(Image,form=ImageForm,extra=5)
if request.method == 'POST':
reviewForm = ReviewForm(request.POST)
formset = ImageFormSet(request.POST,request.FILES,queryset=Image.objects.none())
starsForm = StarsrForm(request.POST)
if reviewForm.is_valid() and formset.is_valid() and starsForm.is_valid():
review_form = reviewForm.save(commit=False)
review_form.author = request.user
review_form.post_or_discussion = 1
review_form.food_or_travel = 'Foods'
review_form.save()
reviewForm.save_m2m()
starsForm.save()
for form in formset.cleaned_data:
if form:
image = form['image']
photo = Image(review=review_form,image=image)
photo.save()
messages.success(request,'Image Uploaded Successfully')
return HttpResponseRedirect("/")
else:
print(reviewForm.errors, formset.errors)
else:
reviewForm = ReviewForm()
starsForm = StarsrForm()
formset = ImageFormSet(queryset=Image.objects.none())
return render(request,'reviews/review_form.html',{'reviewForm':reviewForm,'formset':formset,'starsForm':starsForm})
best try when you use ForeighKey is to use related_name attr for this field
class Star(models.Model):
post = models.ForeignKey(Review, related_name='post_review', on_delete = models.CASCADE )
after it you can refer to star from review by some_object_review.post_review.some_field_star
For you error above try reviews_star.post_id.id
Solve The problem.All I had to do is pass the review_form instance to the star form.
new view is:
if request.method == 'POST':
reviewForm = ReviewForm(request.POST)
formset = ImageFormSet(request.POST,request.FILES,queryset=Image.objects.none())
starsForm = StarsrForm(request.POST)
if reviewForm.is_valid() and formset.is_valid() and starsForm.is_valid():
review_form = reviewForm.save(commit=False)
review_form.author = request.user
review_form.post_or_discussion = 1
review_form.food_or_travel = 'Foods'
review_form.save()
reviewForm.save_m2m()
instance = review_form
print(instance.id)
star_form = starsForm.save(commit=False)
star_form.post_id = instance
star_form.save()
for form in formset.cleaned_data:
if form:
image = form['image']
photo = Image(review=review_form,image=image)
photo.save()
messages.success(request,'Image Uploaded Successfully')
return HttpResponseRedirect("/")
else:
print(reviewForm.errors, formset.errors)
else:
reviewForm = ReviewForm()
starsForm = StarsrForm()
formset = ImageFormSet(queryset=Image.objects.none())
return render(request,'reviews/review_form.html',{'reviewForm':reviewForm,'formset':formset,'starsForm':starsForm})
I'm trying to make a booking system (for apartments). The idea is that users can pick a start date and an end date and book the apartment if it isnt alrdy booked.
I have a Reservation model with a "start_date" and a "end_date" that I use to determine the dates for the apartment booking.
Users the JQuery Ui Date Picker (a small calendar) to pick dates. The "unavailable" dates are grayed out.
This is how I did that :
<script type="text/javascript">
var unavailableDates = ['{{ reservation.all.0.start_date|date:"d-m-Y" }}', '{{ reservation.all.0.end_date|date:"d-m-Y" }}'];
console.log(unavailableDates);
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
$(function () {
$("#datepicker").datepicker({
dateFormat: 'MM-dd-yy',
beforeShowDay: unavailable
});
});
</script>
I am using ...
{{ reservation.all.0.start_date|date:"d-m-Y" }}
...to gray out the date in the calendar.
My reservation model looks like this:
class Reservation(models.Model):
apartment = models.ForeignKey(Apartment, related_name='reservations',
on_delete=models.CASCADE, blank=True, null=True)
start_date = models.DateField(blank=True, null=True, unique=True)
end_date = models.DateField(blank=True, null=True, unique=True)
name = models.CharField(default="", max_length=200, unique=True)
def __str__(self):
return self.name
And in my view I have:
def apartment_view(request, apartment_id):
reservation = Reservation.objects.filter(apartment__pk=apartment_id)
apartment = get_object_or_404(Apartment, pk=apartment_id)
context = {'apartment': apartment, }
form = ReservationForm()
if request.method == 'GET':
form = ReservationForm()
elif request.method == 'POST':
form = ReservationForm(request.POST)
if form.is_valid():
reservation = form.save(commit=False)
reservation.apartment = apartment
reservation.save()
form.save()
return HttpResponseRedirect('/booking/')
args = {}
args['form'] = form
args['apartment'] = context
args['reservation'] = reservation
return render(request, 'booking/apartment.html', args)
Since I need my reservations to be filtered to the correct apartment.
My question is, how can I query for ALL dates related to an apartment, both start and end dates ?
So I need all dates for apartment 1, then all dates for apartment2...etc.
I'm not sure how to go on about this, I apologize if the post is confusing.
Thanks !!!
Later edit:
After looking at your JS code you might wanna do something like this in your view:
import itertools
unavailable_dates = apartment.reservations.values_list('start_date', 'end_date')
context['unavailable_dates'] = list(itertools.chain(*unavailable_dates)) # to convert _list_ of tuples to simple list
You can get start/end dates for reservations linked to an apartment like this:
apartment = get_object_or_404(Apartment, pk=apartment_id)
context['appartment_reservations_dates'] = apartment.reservations.values_list('start_date', 'end_date')
If you want to work with the entire Reservation object directly in your HTML template you can do it like this:
{% for reservation in apartment.reservation.all %}
{{ reservation.start_date }} - {{ reservation.end_date }}
{% endfor %}
Your view might look like this:
def apartment_view(request, apartment_id):
context = dict()
context['apartment'] = get_object_or_404(Apartment, pk=apartment_id)
context['reservations'] = apartment.reservations.all() # if you want all existing reservations for this specific appartment
form = ReservationForm()
if request.method == 'GET':
form = ReservationForm()
elif request.method == 'POST':
form = ReservationForm(request.POST)
if form.is_valid(): # you can add extra validation here making sure whoever tries to book is booking for an available time interval
reservation = form.save(commit=False)
reservation.apartment = apartment
reservation.save()
form.save()
return HttpResponseRedirect('/booking/')
context['form'] = form
return render(request, 'booking/apartment.html', args)
I am trying to create new users to the admin and to the app from NON Classe Based View in my django project, I have the model, the view and the template where I am getting the form as it goes in the next code I´m going to show..
models.py
class Users(models.Model):
# Fields
username = models.CharField(max_length=255, blank=True, null=True)
password = models.CharField(max_length=12, blank=True, null=True)
organization_id = models.ForeignKey('ip_cam.Organizations', editable=True, null=True, blank=True)
slug = extension_fields.AutoSlugField(populate_from='created', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
# Relationship Fields
user_id = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return u'%s' % self.user_id
def get_absolute_url(self):
return reverse('ip_cam_users_detail', args=(self.slug,))
def get_update_url(self):
return reverse('ip_cam_users_update', args=(self.slug,))
def __unicode__(self): # __str__
self.organization_id=self.request.POST.get('organization_id')
return unicode(self.user_id, self.organization_id)
# This overrides the standard save method for a user, creating a new user in the admin and getting it to the template at the same time
def save(self, *args, **kwargs):
self.password = make_password(self.password)
self.user_id, created = User.objects.get_or_create(username=self.username, password=self.password, is_staff=True)
self.user_id.groups.add(Group.objects.get(name='admin'))
self.id = self.user_id.id
super(Users, self).save(*args, **kwargs)
views.py
def UsersCreate(request):
model = Users
var = {}
var = user_group_validation(request)
userInc = Users.objects.get(id=request.user.id).organization_id.pk
request.session['userInc'] = userInc
if var['group'] == 'superuser':
object_list = Users.objects.all()
organization = Organizations.objects.all()
roles_choice = DefaultLandingPage.objects.all()
if var['group'] == 'admin' or var['group'] == 'user':
object_list = Users.objects.filter(organization_id=request.session['userInc'])
organization = Organizations.objects.filter(id=request.session['userInc'])
roles_choice = DefaultLandingPage.objects.exclude(role=1)
url = request.session['url']
tpl = var['tpl']
role = var['group']
organization_inc = Organizations.objects.filter(id=request.session['userInc'])
template = get_template(app+u'/users_form.html')
return HttpResponse(template.render(locals()))
the problem in here is that the save is not working when trying to override it, user is not created at all... can you please help me to see what am I doing wrong this time ? thanks in advance.
If you are not using the generic django class based views, you will have to implement the request's POST and GET functionality yourself. The easiest is to create a form from your user model and handle the request based on whether it's a POST request type or not.
Try this:
forms.py (https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/)
from django.forms import ModelForm
from .models import User
class UserForm(ModelForm):
class Meta:
model = Users
fields = ['username', 'organization_id']
views.py
from .models import User
from .forms import UserForm
def UsersCreate(request):
# This function can hadle both the retrieval of the view, as well as the submission of the form on the view.
if request.method == 'POST':
form = UserForm(request.POST, request.FILES)
if form.is_valid():
form.save() # This will save the user.
# Add the user's role in the User Role table below?
#
else:
# The form should be passed through. This will be processed when the form is submitted on client side via this functions "if request.method == 'POST'" branch.
form = UserForm()
var = user_group_validation(request)
userInc = Users.objects.get(id=request.user.id).organization_id.pk
request.session['userInc'] = userInc
if var['group'] == 'superuser':
object_list = Users.objects.all()
organization = Organizations.objects.all()
roles_choice = DefaultLandingPage.objects.all()
if var['group'] == 'admin' or var['group'] == 'user':
object_list = Users.objects.filter(organization_id=request.session['userInc'])
organization = Organizations.objects.filter(id=request.session['userInc'])
# The line below will ensure that the the dropdown values generated from the template will be filtered by the 'request.session['userInc']'
form.organisation_id.queryset = organization
roles_choice = DefaultLandingPage.objects.exclude(role=1)
url = request.session['url']
tpl = var['tpl']
role = var['group']
organization_inc = Organizations.objects.filter(id=request.session['userInc'])
template = get_template(app+u'/users_form.html')
return HttpResponse(template.render(locals()))
In your app+u'/users_form.html' file, you can access the UserForm fields as follows:
<!-- inside your <form> tag add: -->>
{{ form.username }}
{{ form.organisation_id }}
I haven't tested this code but this should get you on the right track.