I am trying to convert my current project(It is developed in Django) to DRF. So, I set up DRF in my project then I wrote an endpoint for after user login on the session I need to get the response when I test the my-reviews API.
models.py
class customer(models.Model):
cust_id = models.IntegerField(null="true")
email = models.CharField(max_length=100)
# reemail = models.CharField(max_length=100, null='true')
password = models.CharField(max_length=500)
repassword = models.CharField(max_length=500, null='true')
firstname = models.CharField(max_length=225)
lastname = models.CharField(max_length=225, null=True)
state = models.CharField(max_length=64, null=True)
city = models.CharField(max_length=64, null=True)
location = models.CharField(max_length=225, null=True)
Zip = models.CharField(max_length=64)
mailing = models.CharField(max_length=1000)
added_date = models.DateTimeField(editable=False)
modified_date = models.DateTimeField(null=True, blank=True)
last_loggedin = models.DateField()
views.py
#api_view(['GET'])
def myservicereviewAPI(request):
# If a user session is logged out it will redirect to the home page.
if ((request.session.get('email') is None) or (request.session.get('email') == "")):
# redirecting the user after logging out to the home page.
return HttpResponseRedirect("/home")
if request.method == 'GET':
students = services_review.objects.all().order_by('-added_date')
serializer = ServicesReviewSerializer(students, many=True)
return Response(serializer.data)
urls.py
path('myservicereviewAPI', views.myservicereviewAPI, name='myservicereviewAPI'),
Results of Postman when I run 'myservicereviewAPI'
After login Browser results of 'myservicereviewAPI'
Please Help me to achieve this.
Related
I'm trying to get object from db.
That's my model:
class Employee(models.Model):
class EmployeeRole(models.TextChoices):
DEFAULT = 'Default'
PM = 'PM'
ADMINISTRATOR = 'Administrator'
name = models.CharField(max_length=127, blank=False, null=False)
surname = models.CharField(max_length=127, blank=False, null=False)
login = models.CharField(max_length=127, blank=False, null=False)
password = models.CharField(max_length=1023, blank=False, null=False)
email = models.EmailField()
employee_role = models.CharField(max_length=31, choices=EmployeeRole.choices,
blank=False, null=False)
salary = models.DecimalField(max_digits=10, decimal_places=2)
department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True,
blank=True)
last_login_date = models.DateField(auto_now=True)
created_date = models.DateField(auto_now_add=True)
def __str__(self):
return f"{self.name} {self.surname} - {self.employee_role}"
That's my urls:
urlpatterns = [
path('employees/<int:pk>', views.employee_details),
path('employees/', views.employee_list_or_add),
]
And that's my views:
#csrf_exempt
def employee_list_or_add(request):
if request.method == 'GET':
employees = Employee.objects.get(id=4)
serializer = EmployeeSerializer(employees)
print(serializer)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = EmployeeSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
I'm learning with REST documentation, I'm on first chapter - serialization. But I can't get any objects from db.
No matter if I use Employee.objects.all() (with many=True in serializer) like in documentation or Employee.objects.get(pk=4) like currently in my code - I'm always getting error
invalid literal for int() with base 10: b'17 21:19:04.767380'
That's the time of last_login_date of first record in Employee db. But in .get() function I specified 'pk' so why it's trying to filter it by datetime?
I would be very grateful for any help.
hi am working on a project where am using multiple user data a user did a post onto the site and when driver see that post he adds their offer to that post but when driver submit the post ...at the admin level the particular is selected automatically but the post is not selected on which he adds price this is my post model.py
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
this is my second model of adding price to a particular post
class price(models.Model):
my_post = models.ForeignKey(Loader_post, related_name='prices')
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='')
driver_price = models.CharField(max_length=150, null=True)
driver_name = models.CharField(max_length=150, null=True)
status = models.BooleanField(default=False)
this is my adding price to the post views.py
#login_required
def add_price_to_post(request, pk):
post = get_object_or_404(Loader_post, pk=pk)
user = request.user
if request.method == "POST":
form = price_form(request.POST)
if form.is_valid():
ps = form.save(commit=False)
ps.user = request.user
ps.status = True
ps.post = post
ps.save()
return redirect('Driver:Driverview')
else:
form = price_form()
return render(request, 'price_form.html', {'form': form})
this is my html add post button
{% for loader in Loader %}
this is loop and this is button
add price
you can see my_post is select automatically
In your model the field name is my_post while in the add_price_to_post you are adding ps.post. change that to ps.my_post.
I have a model Reservation with two custom permissions reservation_can_view and reservation_can_edit:
class Reservation(models.Model):
UNCONFIRMED = 'UNCONFIRMED'
CONFIRMED = 'CONFIRMED'
CANCELED = 'CANCELED'
NO_SHOW = 'NO SHOW'
GO_SHOW = 'GO SHOW'
STATUS_CHOICES = (
(UNCONFIRMED, _('Unconfirmed')),
(CONFIRMED, _('Confirmed')),
(CANCELED, _('Canceled')),
(NO_SHOW, _('No show')),
(GO_SHOW, _('Go show')),
)
booking = models.CharField(max_length=15, verbose_name=_('Booking'))
agency = models.ForeignKey(Agency, on_delete=models.PROTECT, related_name='reservations', verbose_name=_('Agency'))
comment = models.TextField(null=True, blank=True, verbose_name=_('Comment'))
status = models.CharField(max_length=15, choices=STATUS_CHOICES, default=UNCONFIRMED, verbose_name=_('Status'))
confirmation_date = models.DateTimeField(null=True, blank=True, verbose_name=_("Confirmation Date"))
arrival_date = models.DateField(verbose_name=_('Arrival Date'))
departure_date = models.DateField(verbose_name=_('Departure Date'))
confirmation = models.CharField(max_length=15, null=True, blank=True, verbose_name=_('Confirmation Code'))
is_invoiced = models.BooleanField(default=False, verbose_name=_('Is invoiced?'))
euroamerica = models.BooleanField(default=False, verbose_name=_("Is Euroamerica sale"))
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT, related_name='reservations')
timestamp = models.DateTimeField(null=True, blank=True, auto_now_add=True)
handle_fee = models.FloatField(null=True, blank=True, verbose_name=_("Handle Fee"))
class Meta:
verbose_name = _('Reservation')
verbose_name_plural = _('Reservations')
permissions = (
('reservation_can_edit', 'Can Edit Reservation'),
('reservation_can_view', 'Can View Reservation')
)
And a ModelViewSet that validates such permissions:
class ReservationCompositionPermission(permissions.BasePermission):
def has_permission(self, request, view):
user_permissions = Permission.objects.filter(user=request.user)
print(str(user_permissions))
if request.method == 'GET':
return request.user.has_perm('reservation_can_view')
elif request.method in ('POST', 'PUT', 'PATCH'):
return request.user.has_perm('reservation_can_edit')
return False
class ReservationCompositionViewSet(viewsets.ViewSet):
permission_classes = (ReservationCompositionPermission,)
def list(self, request, pk):
reservation = models.Reservation.objects.filter(booking=pk).order_by('timestamp').last()
if reservation == None:
raise CustomValidation(_('There is not such Reservation: {}'.format(pk)), 'booking', status.HTTP_400_BAD_REQUEST)
result_set = serializers.ReservationSerializer(reservation).data
result_set['pax'] = self.get_reservation_people(reservation)
result_set['itinerary'] = self.get_reservation_composition(reservation)
return Response(result_set)
I can see in the console that current user has both permissions:
<QuerySet [<Permission: ReservationsManagerApp | Reservación | Can Edit Reservation>, <Permission: ReservationsManagerApp | Reservación | Can View Reservation>]>
But I still get False when the custom permission class evaluates request.user.has_perm('reservation_can_view'), unless the user is a super-user.
I guess I am missing something, but I can't find what.
Take a look at the has_perm documentation (link is for Django 2.1). Looks like the method expects the permission to be in the form <app label>.<permission codename>.
So I need to filter posts, posted by users, who the user currently logged in is following.
Here's my models:
class ProfileDetails(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
provider = models.CharField(max_length=20, null=True, blank=True)
firstname = models.CharField(max_length=25, null=True, blank=True)
lastname = models.CharField(max_length=25, null=True, blank=True)
username = models.CharField(max_length=24, null=True, blank=True, unique=True)
def __str__(self):
return str(self.user)
class Posts(models.Model):
post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(ProfileDetails, on_delete=models.CASCADE, null=True)
text = models.TextField(max_length=280, null=True, blank=True)
video = models.CharField(max_length=24, null=True, blank=True)
timestamp = models.DateTimeField(default=datetime.datetime.now, blank=True)
def __str__(self):
return str(self.user)
class Connection(models.Model):
follower = models.ForeignKey(ProfileDetails, related_name='follower', on_delete=models.SET_NULL, null=True)
following = models.ForeignKey(ProfileDetails, related_name='following', on_delete=models.SET_NULL, null=True)
# follower = models.ManyToManyField(ProfileDetails, related_name='follower')
# following = models.ManyToManyField(ProfileDetails, related_name='following')
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return str(self.follower)
And then in my views, my bit of Python / Django knowledge kind of directed me to write something like this (take a look particularly at the last bit, where I try to filter it so it only gets details from the users I follow.
def index(request):
checkuser = request.user
print(checkuser)
if ProfileDetails.objects.filter(user=checkuser):
print("user previously logged in")
sns = get_object_or_404(SocialAccount, user=checkuser)
autoupdateprofile = get_object_or_404(ProfileDetails, user=checkuser)
autoupdateprofile.lastlogin = datetime.datetime.now()
autoupdateprofile.save(update_fields=["lastlogin"])
# print(sns.provider)
details = get_object_or_404(ProfileDetails, user=checkuser)
videos = Posts.objects.filter(media=True, imade=True).order_by("-timestamp")[0:6]
followercount = Connection.objects.filter(follower=details).count()
follows = Connection.objects.filter(follower=details)
followerposts = Posts.objects.filter(user=follows)
for a in followerposts:
print(a)
return render (request, 'index.html', context)
However, this doesn't seem to work. I'm greeted with this lovely error trying to get me to use the data from the model ProfileDetails - which would obviously make no sense, cause how else can I indicate the users I'm following in Connections.
Exception Value:
Cannot use QuerySet for "Connection": Use a QuerySet for "ProfileDetails".
Been struggling with this for a few days and no longer sure what to search for.
If it makes any difference, I'm using Python 3.6 and Django 2.0.4 on Postgresql.
Suggestions would be appreciated. :)
Thanks in advance.
Ronald
This code goes in and fetches all posts from users whom the current user follows (ie, for whom the current user is a follower):
Posts.objects.filter(user__following__follower=ProfileDetails.objects.get(user=self.request.user))
I created models called Interview, Users, Interview_interviewer like wise...
Interview_interviewer table has foreign keys from other models.
I just want to save data from both 2 tables to Interview_interviewer(Without django forms) table which is many to many table. So I just created the views and template for it. When button clicks it save the Interviewers to table along side with the interview. But when do it, It gave me and error called "User matching query does not exist".
/home/govinda/DMG/test3/myapp/views.py in hod_inter_interviewer_2
usr = User.objects.get(id=pid)
What should I do?
class Interview(models.Model):
Time = models.TimeField()
Date = models.DateField()
Venue = models.ForeignKey('Venue')
HOD = models.ForeignKey(User)
Vacancy = models.ForeignKey('Vacancy', on_delete=models.CASCADE)
Department = models.ForeignKey(Department, on_delete=models.CASCADE)
InterviewType = models.ForeignKey(InterviewType, on_delete=models.CASCADE)
Interviewer_Review = models.TextField(blank=True, null=True)
HOD_Review = models.TextField(blank=True, null=True)
HR_Review = models.TextField(blank=True, null=True)
NoOfPasses = models.PositiveIntegerField(blank=True, null=True)
NoOfFails = models.PositiveIntegerField(blank=True, null=True)
NoOfOnHolds = models.PositiveIntegerField(blank=True, null=True)
InterviewNo = models.IntegerField(blank=True, null=True)
Post = models.ForeignKey(Post, on_delete=models.CASCADE)
and
class Users(models.Model):
User = models.OneToOneField(User)
FullName = models.CharField(max_length=100)
Post = models.ForeignKey(Post)
UPhoto = models.FileField(upload_to=User_directory_path,null = True,blank=True)
Department = models.ForeignKey(Department)
UserRole = models.ForeignKey(UserRole)
def __str__(self):
return u'{}'.format(self.User)
and
class Interview_Interviewer(models.Model):
Interview = models.ForeignKey(Interview)
Interviewer = models.ForeignKey(User)
def __str__(self):
return u'{}'.format(self.Interviewer)
views are...
def hod_pre_interviwer_list(request, iid):
inter = Interview.objects.get(id=iid)
a = UserRole.objects.get(Role="Interviewer")
viewer = Users.objects.filter(UserRole=a.id)
return render(request, 'hod_inter_create_2.html', {'viewer': viewer, 'inter': inter, 'a':a})
def hod_inter_interviewer_2(request, iid, pid):
inter = Interview.objects.get(id=iid)
usr = User.objects.get(id=pid)
a = UserRole.objects.get(Role="Interviewer")
viewer = Users.objects.filter(UserRole=a.id)
usr_id = Users.objects.get(User=a.id)
inter_id = inter
person_id = usr_id
form = Interview_Interviewer(Interview=inter_id, Interviewer=person_id)
form.save()
return render(request, 'hod_inter_create_2.html', {'viewer': viewer, 'inter': inter})
urls are...
urlpatterns = [
url(r'^hod/hod_vacancy/test/part2/inter_list/(\d+)/$', hod_pre_interviwer_list, name="inter1"),
url(r'^hod/hod_vacancy/test/part2/inter_list/(\d+)/(\d+)/$', hod_inter_interviewer_2, name="inter2"),
]
template is...
<a type="submit" class="btn btn-primary" href="/hod/hod_vacancy/test/part2/inter_list/{{ inter.id }}/{{ viewer.id }}">Add</a>
Try using named groups in your url patterns
urlurl(r'^hod/hod_vacancy/test/part2/inter_list/?P<iid>[0-9]+)/?P<pid>[0-9]+/$', hod_inter_interviewer_2, name="inter2"),
If that doesn't work then i suggest trying User.object.get(pk=pid) as in most doc examples.
And make sure that there is a user with that id (iid) in the url.
You should also use get_object_or_404 for getting any single object from a model in the view as it gives a more user friendly and appropriate error.