Django model.objects.get() isn't looking by param that I specify - python

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.

Related

Error when trying to save a form in django

I am new to django and I am working on a project whereby users fill a form from frontend and the data is saved to a gig model where the writer extends from a profile foreignkey. The error says
ValueError at /seller_profile/ The Gig could not be created because
the data didn't validate.
Here is the models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(default='avatar.jpg', null=True, blank=True)
about = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Gig(models.Model):
writer = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False)
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500, null=True, blank=True)
image = models.ImageField(null=False, blank=False)
gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Views.py:
def createGig(request):
gig = request.user.profile
form = CreateGigForm()
if request.method == 'POST':
form = CreateGigForm(request.POST, request.FILES)
if form.is_valid:
gig = form.save(commit=False)
gig.writer = gig
gig.save()
messages.info(request, 'Profile Succesfully Created')
return redirect('create')
else:
messages.error(request, 'Gig Not Created! Try Again Later')
context = {'form':form}
return render(request, 'starter/create_gig.html', context)
And here is a screenshot of the error message: Error message screenshot
I found the solution to this. The problem was with checking if form is valid there was an error with missing brackets. if form.is_valid: should be if form.is_valid:.

Django,update the same row field in model getting data from serializer

I have this model:
class AgentDetail(MethodID):
first_name = models.CharField(max_length=50, blank=True, null=True, unique=True)
last_name = models.CharField(max_length=50, unique=True, null=True)
email = models.EmailField(null=False)
authen_method = models.ForeignKey(AuthMethodID, on_delete=models.CASCADE)
country_code = models.BigIntegerField(default=1)
mobile_number = models.BigIntegerField(null=False)
sms_provider = models.CharField(max_length=50, null=True)
active_status = models.BooleanField(default=True)
created_time = models.DateTimeField(default=now, editable=False)
created_by = models.CharField(max_length=50)
updated_time = models.DateTimeField(auto_now=True)
updated_by = models.CharField(max_length=50)
and this serializer:
class AgentSerializer(serializers.ModelSerializer):
class Meta:
model = AgentDetail
fields = [
"first_name",
"last_name",
"email",
"authen_method",
"mobile_number",
"sms_provider",
]
and this views.py:
#api_view(["POST"])
def create_agent(request):
if request.method == "POST":
serializer = AgentSerializer(data=request.data, many=False)
if serializer.is_valid():
serializer.save()
request_data = serializer.data
# AgentDetail.objects.update_or_create(
# created_by=request_data["first_name"] + request_data["last_name"],
# updated_by=request_data["first_name"] + request_data["last_name"],
# )
return Response(status=status.HTTP_200_OK)
error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return error
As in serializer I'm not passing created_by field and I need that field gets value of first_name+last_name which are coming from serializer data.I'm new to DRF.
as said in docs you can pass additional attributes to save method.
views.py
#api_view(["POST"])
def create_agent(request):
if request.method == "POST":
serializer = AgentSerializer(data=request.data, many=False)
if serializer.is_valid():
request_data = serializer.validated_data
serializer.save(
created_by=request_data["first_name"] + request_data["last_name"],
updated_by=request_data["first_name"] + request_data["last_name"],
)
return Response(status=status.HTTP_200_OK)
error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return error
you can access the validated_data in create method, and add any extra data you want.
serializer.py
class AgentSerializer(serializers.ModelSerializer):
...
def create(self, validated_data):
first_name = validated_data.get('first_name', '')
last_name = validated_data.get('last_name', '')
validated_data.update(dict(
created_by=first_name+last_name,
updated_by=first_name+last_name
))
return super().create(validated_data)

How to use Authentication in DRF

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.

How to filter a User model with a ForeignKey using custom URL format

Intended URL format:
api/v1/users?applicant={applicantId}
Current (working) URL format:
path('users/applicant/<int:pk>/')
How do I check if an applicant has already setup an account on the system as User using the applicantID (which has a foreignkey relationship with the Users table)?
models.py:
class Applicant(models.Model):
APPLICATION_STATUS = (
(1, 'Pending'),
(2, 'Accept'),
(3, 'Reject'),
)
first_name = models.CharField(max_length=200, blank=False,
null=False)
last_name = models.CharField(max_length=200, blank=False,
null=False)
email = models.EmailField(max_length=200, blank=False, null=False,
unique=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'.
Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex],
max_length=17, blank=True, null=False, unique=True) # validators
should be a list
linkedin_url = models.URLField(max_length=255, unique=True,
blank=True, null=True) #make sure diff users cant use two same
profile
twitter_url = models.URLField(max_length=255, unique=True) #make
sure diff users cant use two same profile
articles = ArrayField(models.URLField(), blank=False, null=False,
unique=True, size=3)
country = models.ForeignKey(Country, on_delete=models.CASCADE,
blank=False, related_name="applicant")
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name="applicant", blank=False)
status = models.CharField(max_length=200,
choices=APPLICATION_STATUS, default=1)
def __str__(self):
return self.first_name
class User(AbstractUser):
USER_TYPE_CHOICES = (
(1, 'Journalist'),
(2, 'Admin'),
)
GENDER = (
(1, 'Male'),
(2, 'Female')
)
first_name = models.CharField(max_length=200, blank=False)
last_name = models.CharField(max_length=200, blank=False)
# is_active = models.BooleanField(default=True)
password = models.CharField(max_length=200)
email = models.EmailField(max_length=250, unique=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format:
'+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex],
max_length=17, unique=True, blank=False) # validators should be a
list
user_type = models.CharField(max_length=200,
choices=USER_TYPE_CHOICES, default=1)
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name="users")
# posts_url = ArrayField(models.URLField(), size=3)
country = models.ForeignKey(Country, on_delete=models.CASCADE,
blank=True, related_name="users")
gender = models.CharField(max_length=200, choices=GENDER)
image_url = models.URLField(max_length=255)
about = models.TextField()
applicant = models.ForeignKey(Applicant,
on_delete=models.CASCADE, blank=True, null=True,
related_name="users")
def __str__(self):
return self.username
class Meta:
ordering = ("-date_joined",)
views.py:
class IdentifyUserApplicantID(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = ApplicantSerializer
permission_classes = (IsAuthenticated,)
# def get_queryset(self, pk):
# return Applicant.objects.get(id=pk)
def get(self, request):
data = request.data.get('pk')
admin_user = User.objects.get(user_type=2)
if request.user == admin_user:
try:
queryset = User.objects.get(applicant=data)
serializer = UserSerializer(queryset)
return Response(jsend.success({'users':
serializer.data}))
except User.DoesNotExist:
return Response(jsend.success({'users': '[]'}))
else:
return Response((jsend.error("You are not authorized to
perform this action")),
status=status.HTTP_404_NOT_FOUND)
P.S: I checked out django-filter module but the docs isn't clearly written and a bit hard to understand. Would be glad if more clarification is made in that regard if django-filter is the recommended way of implementing the solution.
I don't know if I understand your question, but do you mean something like this:
if User.objects.filter(applicant__id=pk).exists():
path('api/v1/users', views.YOURVIEW.as_view())
and in the view
applicantId = request.GET.get('applicant', None)
The key was to filter against query parameter, which was done here: http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters
Using request.query_params.get() to get the users query via URL in your .get_queryset() method...and pass it as your queryset when creating a response object.
My updated views.py:
class IdentifyUserApplicantID(generics.ListAPIView):
serializer_class = UserSerializer
permission_classes = [IsAuthenticated,]
queryset = User.objects.all()
def get_queryset(self):
queryset = User.objects.all()
applicant = self.request.query_params.get("applicant", None)
if applicant is not None:
queryset = queryset.get(applicant=applicant)
return queryset
def get(self, request):
if request.user.user_type == "2":
try:
queryset = self.get_queryset()
serializer = UserSerializer(queryset)
return Response(jsend.success({'user': serializer.data}))
except User.DoesNotExist:
return Response(jsend.success({'user': '[]'}))
else:
return Response((jsend.error("You are not authorized to perform
this action")),status=status.HTTP_403_FORBIDDEN)
My updated urls.py
re_path(r'^users$', IdentifyUserApplicantID.as_view(), name="identify-
applicant"),
Example Query:
http://example.com/api/v1/users?applicant=2
Hope this helps. Thanks everyone for your answers.

image not saving on django models

I created an album with a photos as foreign key but somehow when i add a photo it does not save probably in my database or admin site
Here are my models:
class AlbumPluginModel(CMSPlugin):
name = models.CharField(max_length=255,
help_text=_('e.g: Zuerich city, or Zuerich Hoengg'))
slug = models.SlugField(_('Slug'), blank=True, null=True, unique=True, db_index=True)
description = HTMLField(blank=True, null=True)
cover_photo = models.ImageField(verbose_name=_('Add cover photo'), null=True, blank=True)
is_active = models.BooleanField(_('active'), blank=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
sort = models.IntegerField(_("Sort Order"), null=True, blank=True, default=0)
def __str__(self):
if self.name:
return u"File for %s" % self.name
else:
return u"%s" % self.name
def get_absolute_url(self):
return "/album_detail%i/" % self.id
class Meta:
ordering = ['sort']
verbose_name = "Album"
verbose_name_plural = "Albums"
class Photo(models.Model):
photo = models.ForeignKey(AlbumPluginModel, verbose_name=_('choose album'), null=True, blank=True)
image1 = models.ImageField(verbose_name=_('Photo'), null=True, blank=True, upload_to="/static/img/")
sort = models.IntegerField(_("Sort Order"), null=True, blank=True, default=0)
def __unicode__(self):
return u"%s" % self.image1
def __str__(self):
return u"%s" % self.image1
class Meta:
ordering = ['sort']
verbose_name = _("photo")
verbose_name_plural = _("Photos")
forms.py
class AlbumPluginForm(forms.ModelForm):
class Meta:
model = AlbumPluginModel
fields = ['name', 'description', 'cover_photo', 'is_active',]
class PhotoPluginForm(forms.ModelForm):
photo = forms.ModelChoiceField(label='select album',aqueryset=AlbumPluginModel.objects.all(), required=False)
class Meta:
model = Photo
fields = ('photo', 'image1', )
views.py
def add_photo(request, id=None, **kwargs):
if request.method == 'POST':
all_photos = Photo.objects.all
form = PhotoPluginForm(request.POST, request.FILES, initial={'photo': id})
template_name = 'photo_create.html'
context = {
"form": form,
"all_photos": all_photos,
}
if form.is_valid():
all_photos = form.save(commit=False),
form.save()
messages.success(request, "Photo was added.")
return redirect('/photos')
else:
print("error: form nicht valid")
return render(request, template_name, context)
You should add upload_to parameter for field in which you want to upload some file in server. In your case, in AlbumPluginModel your cover_photo will be
cover_photo = models.ImageField(verbose_name=_('Add cover photo'), null=True, blank=True, upload_to='path_where_you_want_to_save')
If you call save() with commit=False, then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save() on the resulting model instance. You should change your view like this
all_photos = form.save(commit=False),
all_photos.save()
after a long try i finally found the answer:
in views.py
i chnaged this line from
form = PhotoPluginForm(request.POST or None)
to:
form = PhotoPluginForm(request.POST, request.FILES)
and in my template i forgot this:
enctype="multipart/form-data"

Categories

Resources