'AgencyRegistration' object has no attribute 'get' - django

I'm trying to create an endpoint using Django REST framework, but when I'm trying to get the data from the endpoint I'm getting the following error: AttributeError: 'AgencyRegistration' object has no attribute 'get'. Here's my code
models.py
`class AgencyRegistration(models.Model):
agency_name = models.CharField(max_length=200)
tax_id_number = models.IntegerField(max_length=12)
address_street = models.CharField(max_length=220)
city = models.CharField(max_length=50)
county = models.CharField(max_length=50)
state = models.CharField(max_length=100)
zip_code = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
title = models.CharField(max_length=200)
email = models.CharField(max_length=200)
phone = models.CharField(max_length=50)
children_amount = models.CharField(max_length=100)
age_range = models.CharField(max_length=100)
program_benefit = models.CharField(max_length=200)
organization_type = models.CharField(max_length=200)
how_did_you_hear = models.CharField(max_length=200)
def __str__(self):
return self.agency_name`
views.py
`def agency_registration(request):
agency_data = AgencyRegistration.objects.all()
serializer = AgencyRegistrationSerializer(agency_data, many=True)
return render(JsonResponse(serializer.data, safe=False))`
serializers.py
`class AgencyRegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = AgencyRegistration
fields = [
'id',
'agency_name',
'tax_id_number',
'address_street',
'city',
'county',
'state',
'zip_code',
'first_name',
'last_name',
'title',
'email',
'phone',
'children_amount',
'age_range',
'program_benefit',
'organization_type',
'how_did_you_hear'
]`
urls.py
`urlpatterns = [
path('agency-registration/', views.AgencyRegistration),
]`

You cannot use Model as a path in urlpatterns. You can put there only views, like your agency_registration. It should be:
urlpatterns = [
path('agency-registration/', views.agency_registration),
]

Related

Get a list of all the field values from a Foreign Key Table in Django

am new to Django and currently trying the Foreign Key concept. I have three models as shown below.
class Basket(models.Model):
basket_name = models.CharField(max_length=5, unique=True)
def __str__(self):
return self.basket_name
class Product(models.Model):
Grams = 'GM'
Kilograms = 'KG'
WeightBased = 'WPG'
QuantityBased = 'CPG'
PRODUCT_UNIT_WT_CHOICES=[
(Grams, 'Grams'),
(Kilograms, 'Kilograms')
]
PRODUCT_TYPE_CHOICES =[
(WeightBased, 'Weight Based Product'),
(QuantityBased, 'Quantity Based Product')
]
product_name = models.CharField(max_length=30, unique=True)
product_description = models.TextField(max_length=300)
product_price = models.DecimalField(max_digits=5, decimal_places=2)
product_unit_weight = models.DecimalField(max_digits=5, decimal_places=2)
product_unit_weight_units = models.CharField(max_length=2, choices=PRODUCT_UNIT_WT_CHOICES, default=Grams)
product_type = models.CharField(max_length=3, choices=PRODUCT_TYPE_CHOICES, default=QuantityBased)
product_image = models.ImageField(upload_to=imageUploadPath, null=True, blank=True)
def __str__(self):
return self.product_name
class BasketProductMapping(models.Model):
basket_reference = models.ForeignKey(Basket, on_delete=models.CASCADE)
product_reference = models.ForeignKey(Product, on_delete=models.CASCADE)
mapped_basket_name = models.CharField(max_length=5,null=False, blank=False)
mapped_product_name = models.CharField(max_length=30, null=False, blank=False)
Here are my serializers:
class ProductSerializer(serializers.ModelSerializer):
product = serializers.CharField(read_only=True)
class Meta:
model = Product
fields = ['id', 'product_name', 'product_description', 'product_price', 'product_unit_weight',
'product_unit_weight_units', 'product_type', 'product_image']
class BasketSerializer(serializers.ModelSerializer):
basket = serializers.CharField(read_only=True)
class Meta:
model = Basket
fields = ('id', 'basket_name')
class BasketProductMappingSerializer(serializers.ModelSerializer):
basket_reference = serializers.CharField(source ='basket.basket_name', read_only=True)
product_reference = serializers.CharField(source='product.product_name', read_only=True)
class Meta:
model = BasketProductMapping
fields = ['id', 'basket_reference', 'product_reference', 'mapped_basket_name', 'mapped_product_name']
What I am trying to achieve is get a list of all the values in 'basket_name' and 'product_name' when I call the BasketProductMappingSerializer. But the output I am getting is this:
{
"status": 1,
"message": "Basket Product Mapping List",
"data": [
{
"id": 1,
"mapped_basket_name": "A1",
"mapped_product_name": "XYZ"
}
]
}
This is my views.py code:
class BasketProductViewSet(APIView):
def get(self, request):
if request.GET.get('id'):
print('Basket Product Mapping Details')
basketProductMappingData = BasketProductMapping.get(id = request.GET.get('id'))
serializer = BasketProductMappingSerializer(basketProductMappingData)
else:
basketProductMappingData = BasketProductMapping.objects.all().values('id', 'basket_reference__basket_name', 'product_reference__product_name', 'mapped_basket_name', 'mapped_product_name')
serializer = BasketProductMappingSerializer(basketProductMappingData, many=True)
response = {'status':1, 'message':"Basket Product Mapping List", 'data':serializer.data}
Where am I going wrong? Sorry if my question is very trivial. Thanks for your help in advance.
i see that there is an error in your views BasketProductMapping.get(id = request.GET.get('id')) should be BasketProductMapping.objects.get(id = request.GET.get('id'))
i don't know if it gonna work but can you try
basket_reference = serializers.ReadOnlyField(source ='basket.basket_name')
product_reference = serializers.ReadOnlyField(source='product.product_name')
instead of
basket_reference = serializers.CharField(source ='basket.basket_name', read_only=True)
product_reference = serializers.CharField(source='product.product_name', read_only=True)

How to get a non-pk value to be the value by which a post request is made in django rest framework

As the question states, I'd like to be able to instead of having to pass a PK inside my JSON request in the post request I could pass a different value, like a username "bob" instead of 1.
so the idea is that instead of my request containing:
{
"client": 1,
"urgent": true,
"article": 1,
"quantity": 1,
"order_to": 1
}
it should contain:
{
"client": "bob",
"urgent": true,
"article": 234,
"quantity": 1,
"order_to": 1
}
here are my relevant models:
class UserModel(models.Model):
MEMBERSHIP_TYPE = [
('NM', 'NORMAL'),
('PT', 'PLATA'),
('OR', 'ORO'),
('PL', 'PLATINO'),
]
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=100, unique=True)
photo = models.ImageField(upload_to='images/', blank=True)
address = models.TextField()
client_type = models.CharField(max_length=2,
choices=MEMBERSHIP_TYPE,
default= 'NM')
def __unicode__(self):
return self.name
class ArticleModel(models.Model):
id = models.AutoField(primary_key=True)
code = models.IntegerField(unique=True)
description = models.TextField()
def __str__(self):
return str(self.code)
class SupplierModel(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
address = models.TextField()
articles = models.ManyToManyField(ArticleModel)
def __str__(self):
return self.name
class OrderModel(models.Model):
id = models.AutoField(primary_key=True)
client = models.ForeignKey('UserModel', on_delete=models.CASCADE)
gen_time = models.DateTimeField(auto_now_add=True)
gen_supplied = models.DateTimeField(null=True, blank=True)
urgent = models.BooleanField()
order_to = models.ForeignKey('OrderToModel', on_delete=models.CASCADE)
article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE)
quantity= models.IntegerField()
and Serializer:
class OrderCreateSerializer(serializers.ModelSerializer):
# order_to = OrderToPolymorphicSerializer()
class Meta:
model = OrderModel
fields = ('client', 'urgent', 'article', 'quantity', 'order_to')
Help is much appreciated.
Thank you in advance.
you can do this
class OrderCreateSerializer(serializers.ModelSerializer):
client = serializers.SlugRelatedField(
slug_field='username',
queryset=UserModel.objects.all()
)
article = serializers.SlugRelatedField(
slug_field='code',
queryset=ArticleModel.objects.all()
)
class Meta:
model = OrderModel
fields = ('client', 'urgent', 'article', 'quantity', 'order_to')

KeyError Post DjangoRestFramework

I'm new on Django Rest Framework and when I want to POST data I get a error: KeyError: 'id_area' I do not know what I'm doing wrong. Here's my code:
in my models.py
class Area(models.Model):
id_area = models.AutoField(primary_key=True)
APM = 'apm'
BUSINESS = 'business'
DESARROLLO = 'desarrollo'
SISTEMAS = 'sistemas'
ATENTUSIANOS_CHOICES = (
(APM, 'Apm'),
(BUSINESS, 'Business'),
(DESARROLLO, 'Desarrollo'),
(SISTEMAS, 'Sistemas'),
)
nombre = models.CharField(max_length=255, choices=ATENTUSIANOS_CHOICES)
class Meta:
verbose_name = 'Área'
verbose_name_plural = 'Áreas'
def __str__(self):
return self.nombre
class Atentusiano(models.Model):
id_atentusiano = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=255, blank=False, null=False)
apellido = models.CharField(max_length=255, blank=False, null=False)
correo = models.CharField(max_length=255, blank=False, null=False, unique=True)
anexo = models.CharField(max_length=255, blank=True, null=True)
area = models.ForeignKey(Area, related_name='areas', on_delete=models.CASCADE)
class Meta:
verbose_name = 'Atentusiano'
verbose_name_plural = 'Atentusianos'
ordering = ['nombre']
def __str__(self):
return self.nombre + ' ' + self.apellido
in my serializers.py
class AreaSerializer(serializers.ModelSerializer):
areas = serializers.CharField(read_only=True)
class Meta:
model = Area
fields = ('id_area', 'nombre', 'areas')
class AtentusianoSerializer(serializers.ModelSerializer):
atentusianos = serializers.CharField(read_only=True)
area = serializers.CharField(source='area.nombre', read_only=True)
id_area = serializers.CharField(source='area.id_area')
class Meta:
model = Atentusiano
fields = ['id_atentusiano', 'nombre', 'apellido', 'correo', 'anexo', 'id_area', 'area', 'atentusianos']
def create(self, validated_data):
area_data = validated_data.pop('id_area')
area = models.Area.objects.create(**area_data)
atentusiano = models.Atentusiano.objects.create(area=area, **validated_data)
return atentusiano
And in my views.py
class AtentusianoView(viewsets.ModelViewSet):
queryset = Atentusiano.objects.all()
serializer_class = AtentusianoSerializer
class AreaView(viewsets.ModelViewSet):
queryset = Area.objects.all()
serializer_class = AreaSerializer
The problem is that when I want to Post data, for example:
{
"nombre": "name",
"apellido": "lastname",
"correo": "email#gmail.com",
"anexo": "1364",
"id_area": "1"
}
i got this error area_data = validated_data.pop('id_area')
KeyError: 'id_area'
I need help please
you should pop like this,
class AtentusianoSerializer(serializers.ModelSerializer):
.....
.....
class Meta:
model = Atentusiano
fields = ['id_atentusiano', 'nombre', 'apellido', 'correo', 'anexo', 'id_area', 'area', 'atentusianos']
def create(self, validated_data):
id_area = validated_data.pop('area')['id_area'] # here the correction
area = Area.objects.create(id_area=id_area) # an additional correction
atentusiano = Atentusiano.objects.create(area=area, **validated_data)
return atentusiano
EDIT: As id_area value, you are passing a string instead of an integer which will through another error. Also not,
area = models.Area.objects.create(**area_data)
it should be,
area = Area.objects.create(id_area=id_area)

How to include a manytomany field in a postgres full text search in django

I am trying to do a full text search in postgres using these models
class CustomUser(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
password2 = models.CharField(max_length=128)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
active = models.BooleanField(default=True) # Able to login
practitioner = models.BooleanField(default=False) # has access to a clinc
admin = models.BooleanField(default=False) # superuser
staff = models.BooleanField(default=False) # staff
timestamp = models.DateTimeField(auto_now_add=True)
class Modalities(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User,
related_name='prof_user',
on_delete=models.CASCADE)
bio = models.TextField(max_length=5000)
mods = models.ManyToManyField(Modalities)
phone = PhoneNumberField()
clinics = models.ManyToManyField(Clinic)
personnummer = models.CharField(max_length=12)
street = models.CharField(max_length=50)
city = models.CharField(max_length=50)
consent = models.BooleanField()
class Clinic(models.Model):
practitioner = models.OneToOneField(User,
related_name='prac_user',
on_delete=models.CASCADE)
lat = models.FloatField(null=True, blank=True)
lng = models.FloatField(null=True, blank=True)
name = models.CharField(max_length=128, )
phone = PhoneNumberField()
description = models.TextField(max_length=5000)
street = models.CharField(max_length=128, )
city = models.CharField(max_length=128, )```
So far I am able return search results with
def search(request):
search_vector = SearchVector('practitioner__first_name', 'name',
'description', 'street', 'city')
results = Clinic.objects.annotate(search=search_vector).filter(
search='Göteborg').values_list('name',
'street',
'city',
'lat',
'lng',
'pk',
flat=False)
def list_of_results(results):
key_list = ['name', 'street', 'city', 'lat', 'lng', 'clinic_id']
r_list = []
object = []
for p in results:
r_list.append([p[0], p[1], p[2], p[3], p[4], p[5]])
for array in r_list:
object.append(dict(zip(key_list, array)))
return object
search_result = list_of_results(results)
I would also like to be able to include Profile.mods in search_vector to be able to return results for matching Modalities.
I have tried adding profile__mods like so;
def list_of_results(results):
key_list = [
'name', 'street', 'mods', 'city', 'lat', 'lng', 'clinic_id'
]
r_list = []
object = []
for p in results:
r_list.append([p[0], p[1], p[2], p[3], p[4], p[5], p[6]])
for array in r_list:
object.append(dict(zip(key_list, array)))
return object
But I get the error "Cannot resolve keyword 'mods' into field. Choices are: city, description, id, lat, lng, name, phone, practitioner, practitioner_id, profile, street"
How am I able to include this in my search?

Django REST Framework: define fields in nested object?

I got events that happen at locations:
class Event(models.Model):
title = models.CharField(max_length=200)
date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
date_start = models.DateTimeField('start date')
date_end = models.DateTimeField('end date')
def __unicode__(self):
return self.title
description = models.TextField()
price = models.IntegerField(null=True, blank=True)
tags = TaggableManager()
location = models.ForeignKey(Location, blank=False)
class Location(models.Model):
location_title = models.CharField(max_length=200)
location_date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
location_latitude = models.CharField(max_length=200)
location_longitude = models.CharField(max_length=200)
location_address = models.CharField(max_length=200)
location_city = models.CharField(max_length=200)
location_zipcode = models.CharField(max_length=200)
location_state = models.CharField(max_length=200)
location_country = models.CharField(max_length=200)
location_description = models.TextField()
def __unicode__(self):
return u'%s' % (self.location_title)
I can get the results of all via:
class EventSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field()
class Meta:
model = Event
depth = 2
fields = ('url','id','title','date_start','date_end','description', 'price', 'location')
Which outputs:
{
"url": "http://localhost:8000/api/event/3/",
"id": 3,
"title": "Testing",
"date_start": "2013-03-10T20:19:00Z",
"date_end": "2013-03-10T20:19:00Z",
"description": "fgdgdfg",
"price": 10,
"location": {
"id": 2,
"location_title": "Mighty",
"location_date_published": "2013-03-10T20:16:00Z",
"location_latitude": "37.767475",
"location_longitude": "-122.406878",
"location_address": "119 Utah St, San Francisco, CA 94103, USA",
"location_city": "San Francisco",
"location_zipcode": "94103",
"location_state": "California",
"location_country": "United States",
"location_description": "Some place"
}
},
However, I don't want it to grab all fields, as I don't need all of them. How can I define what fields should be retrieved from my nested object? Thanks!
Serializers can be nested, so do something like this...
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = (...)
class EventSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field()
location = LocationSerializer()
class Meta:
model = Event
fields = ('url','id','title','date_start','date_end','description', 'price', 'location')
I have been to this and did not get a perfect solution, But I did something you may check for it.
This method will not create nested serializers
**class LocationSerializer(serializers.ModelSerializer):**
class Meta:
model = Location
fields = (...) #does not matter
exclude = (...) #does not matter
class EventSerializer(serializers.ModelSerializer):**
loc_field_1 = serializers.CharField(required=False,*source='location.loc_field_1'*)
loc_field_2 = serializers.CharField(required=False,*source='location.loc_field_2'*)
***#ADD YOUR DESIRE FIELD YOU WANT TO ACCESS FROM OTHER SERIALIZERS***
class Meta:
model = Event
fields =('url','id','title','date_start','date_end','description', 'price', 'location')
I found this question when I was trying to figure out how to exclude certain fields from a serializer only when it was being nested. Looks like Tasawer Nawaz had that question as well. You can do that by overriding get_field_names. Here's an example based on Tom Christie's answer:
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = (...)
exclude_when_nested = {'location_title', 'location_date_published'} # not an official DRF meta attribute ...
def get_field_names(self, *args, **kwargs):
field_names = super(LinkUserSerializer, self).get_field_names(*args, **kwargs)
if self.parent:
field_names = [i for i in field_names if i not in self.Meta.exclude_when_nested]
return field_names
class EventSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field()
location = LocationSerializer()
class Meta:
model = Event
fields = ('url','id','title','date_start','date_end','description', 'price', 'location')