How do i solve field error for querying my model? - django

Cannot resolve keyword 'username_contains' into field. Choices are: bio, id, username
#api_view(['GET'])
def endpoints_list(request):
query=request.GET.get('query')
if query == None:
query=''
print(query)
adv_data=Advocate.objects.filter(username_contains=query)
serializer=AdvocateSerializer(adv_data,many=True)
return Response(serializer.data)
I tried querying model but it says it cannot convert it into field

you need to use a double undersocre __
adv_data=Advocate.objects.filter(username__contains=query)

Related

Add model field to non-model serializer in Django

I'm using Django 2.x
I have a serializer for validating the request. (Not ModelSerializer)
class ExecuteSerializer(serializers.Serializer):
database = serializers.IntegerField(required=True)
query = serializers.CharField(required=True)
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
def validate(self, attrs):
user = attrs.get('user', None)
try:
database = Database.objects.get(pk=attrs.get('database', None), collection__user=user)
except Database.DoesNotExist:
raise ValidationError({
'database': ['Does not exists']
})
attrs['database'] = database
return attrs
database is reference to the Database model.
I want user to pass the database id in the database field but got is converted to database object after validation.
I tried to override the validate() method and assign the database object to the database field but it gives error
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Database'
Since you are using IntegerField for database field you shoud return int as database value in validate method, for example database.id:
def validate(self, attrs):
user = attrs.get('user', None)
try:
database = Database.objects.get(pk=attrs.get('database', None), collection__user=user)
except Database.DoesNotExist:
raise ValidationError({
'database': ['Does not exists']
})
attrs['database'] = database.id # fix is here
return attrs

Can I dynamically set field names in Django orm query?

Can I dynamically set field names in Django view?
I want this code
CategoryNick.objects.get(author=self.request.user).get(field=slug)
but error is occured
AttributeError: 'CategoryNick' object has no attribute 'get'
Is there a good way to solve this problem?
if you know solution thank you for let me know
total code
def get_context_data(self, *, object_list=None, **kwargs):
context = super(type(self), self).get_context_data(**kwargs)
context['posts_without_category'] = MyShortCut.objects.filter(category=None,author=self.request.user).count()
context['category_list'] = Category.objects.all()
slug = self.kwargs['slug']
if slug == '_none':
context['category'] = 'no_category'
else:
category = Category.objects.get(slug=slug)
context['category'] = category
context['category_nick'] = CategoryNick.objects.get(author=self.request.user).get(field=slug)
return context
Instead of doing like this CategoryNick.objects.get(author=self.request.user).get(field=slug) you can do like this CategoryNick.objects.get(author=self.request.user, field=slug)
If you want to retrieve the field of the object, you can use .values_list(..., flat=True) [Django-doc] here, like:
CategoryNick.objects.values_list('slug', flat=True).get(author=self.request.user)
So here you will retrieve the slug value for that CategoryNick. If you use 'pk' instead, you will get the primary key.
It is however a bit "odd" to just query for a given field name.

How can I validate if Django model has field given via GET parameter?

How can I validate if Django model has field given via GET parameter?
FieldError: Cannot resolve keyword 'item_typea' into field. Choices are:
item_type, name, id...
order_by = self.request.GET.get('order_by', None) # item_typea
Item.objects.all().order_by(order_by)
Note that GET parameter can has value with minus sign (it's for sorting purposes), for example:
-item_type or item_type
You can simply catch the exception:
order_by = self.request.GET.get('order_by', None) # item_typea
try:
queryset = Item.objects.order_by(order_by)
# evaluate the queryset - that's when the exception will be thrown
except FieldError:
# deal with error
You should just check:
order_by = self.request.GET.get('order_by', None)
if order_by:
Item.objects.all().order_by(order_by)
You can do it like this using get_field:
from django.core.exceptions import FieldDoesNotExist
order_by = self.request.GET.get('order_by', 'id')
try:
if order_by.startswith('-'):
Item._meta.get_field(order_by[1:])
else:
Item._meta.get_field(order_by)
except FieldDoesNotExist:
# field does not exist
FYI, this solution will not work with foreignkey/m2m__field_name expressions.

Django / DRF - How can I view a list of all validators for a model / model serializer field?

This is my UserExtendedSerializer:
class UserExtendedSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
super(UserExtendedSerializer, self).__init__(*args, **kwargs) # call the super()
for field in self.fields: # iterate over the serializer fields
self.fields[field].error_messages['required'] = 'Enter a valid %s.'%field # set the custom error message
self.fields[field].error_messages['invalid'] = 'Select a valid %s.'%field # set the custom error message
class Meta:
model = UserExtended
fields = ('country',)
and this is the UserExtended model:
class UserExtended(models.Model):
user = models.OneToOneField(User)
country = models.ForeignKey(Country)
Now, when I try to create a user without entering a valid country, Django gives an error to the front end saying "Incorrect type. Expected pk value, received list". Where is this error message coming from? Because in my init function, I overrode the "invalid" error message to say "Select a valid country.", but that is not the message I receive.
Also, I opened up the shell and did
repr(UserExtendedSerializer())
and the output was:
UserExtendedSerializer():\n country = PrimaryKeyRelatedField(queryset.Country.objects.all())
So no Django validators were listed here either. How do I view all the validators for a specific model / model serializer field?
Getting Validators for a particular serializer field:
To get the validators for a particular serializer field, you can do:
my_field_validators = UserExtendedSerializer().fields['my_field'].validators
Getting Validators for all the serializer fields:
To get the validators for all the serializer fields in a dictionary, we can use dictionary comprehension.
{x:y.validators for x,y in UserExtendedSerializer().fields.items()}
Getting serializer-level validators:
To get the validators defined at the serializer level i.e. in the Meta class of the serializer, you can do:
UserExtendedSerializer().validators
But this is not where the error comes from.
None of the validators are generating this error message. The error is occurring because of passing invalid data to UserExtendedSerializer for the country field.
DRF source code for PrimaryKeyRelatedField
class PrimaryKeyRelatedField(RelatedField):
default_error_messages = {
'required': _('This field is required.'),
'does_not_exist': _("Invalid pk '{pk_value}' - object does not exist."),
'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'), # error message
}
def to_internal_value(self, data):
try:
return self.get_queryset().get(pk=data)
except ObjectDoesNotExist:
self.fail('does_not_exist', pk_value=data)
except (TypeError, ValueError): # here error message is being generated
self.fail('incorrect_type', data_type=type(data).__name__)
So this error message is coming from the default incorrect_type error message. You can use this key to change the error message if you want.

Primary key check in django

I have this custom primary key in a model:
class Personal(models.Model):
name = models.CharField(max_length=20,primary_key=True)
email = models.EmailField(blank=True,null=True)
Now the thing i m not getting is, how can i create my view so that no duplicate record is entered? I searched this over online, but could find any technique to get the view created.
here is the code for views
def uregister(request):
errors = []
if request.method == 'POST':
if not request.POST.get('txtName', ''):
errors.append('Enter a Name.')
if not errors:
n = request.POST['txtName']
e = request.POST['txtEmail']
try:
per_job = Personal(name=n, email=e)
per_job.save()
except IntegrityError:
return render_to_response('gharnivas/register.html', {'exists': true}, context_instance=RequestContext(request))
return HttpResponseRedirect('/')
else:
return render_to_response('register.html', {'errors': errors}, context_instance=RequestContext(request))
How can i tel the user that, the name already exists?
Catch the inevitable exception upon saving, and tell them.
Use:
per_job.save(force_insert=True)
What you are looking for is Form and Form Validation:
http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#customizing-the-form-template
Define a PersonalForm class, move your validation checks in form field definitions or clean*() methods, then show error fields from form in template.
Django book link for form processing:
http://www.djangobook.com/en/2.0/chapter07/