How to reference ForeignKey objects in HTTP POST? - django

I have a RESTful API on Django and I would like to know how to reference an existing ForeignKey when using json in HTTP POST?
class Trainer(models.Model):
account = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='profiles')
username = models.CharField(max_length=30, unique=True, primary_key=True)
start_date = models.DateField(default=date(2016,7,13), null=True, blank=True)
faction = models.ForeignKey('Faction', on_delete=models.SET_DEFAULT, default=0, null=True, verbose_name="team")
has_cheated = models.BooleanField(default=False)
last_cheated = models.DateField(null=True, blank=True)
currently_cheats = models.BooleanField(default=False)
statistics = models.BooleanField(default=True)
daily_goal = models.IntegerField(null=True, blank=True)
total_goal = models.IntegerField(null=True, blank=True)
last_modified = models.DateTimeField(auto_now=True)
prefered = models.BooleanField(default=True, verbose_name="main profile")
def __str__(self):
return self.username
class Faction(models.Model):
name = models.CharField(max_length=140)
colour = RGBColorField(default='#929292', null=True, blank=True)
image = models.ImageField(upload_to=factionImagePath, blank=True, null=True)
leader_name = models.CharField(max_length=140, null=True, blank=True)
leader_image = models.ImageField(upload_to=leaderImagePath, blank=True, null=True)
def __str__(self):
return self.name
This are the relevant models, I have a list of 4 Faction objects, with their primary keys being 0, 1, 2 and 3.
I've tried many different way, but I just can't figure it out.
This was my latest try, can you advice where I'm going wrong?
{
"username": "Bob123",
"faction": "1"
}
Returned
{
"username": "Bob123",
"faction": "Teamless",
"start_date": "2016-07-13",
"has_cheated": false,
"last_cheated": null,
"currently_cheats": false,
"statistics": true,
"daily_goal": null,
"total_goal": null,
"last_modified": "2017-09-08T21:05:18.001389Z",
"prefered": true,
"account": null
}
Edit: My friend helped me with the solution, I had faction = serializers.StringRelatedField() in the serializer for Trainer, which is Read-only.

My friend helped me with the solution, I had 1faction = serializers.StringRelatedField()1 in the serializer for Trainer, which is Read-only.

Related

django add pdf to a request value

in the following request I receive a total of 10 pdfs which I must combine in one document
once this is done I have to upload it to the client model which stores the files in aws s3, once I pass the file with all the pdfs together it gives me the following error
{
"error": true,
"message": {
"documents": [
"The submitted data was not a file. Check the encoding type on the form."
]
}
}
this is mi code
merger = PdfFileMerger()
for x in request.FILES:
print(request.FILES[x])
merger.append(request.FILES[x])
merger.write(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'media/' + str(getUser.id) + '.pdf'))
merger.close()
pdf = open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'media/' + str(getUser.id) + '.pdf'), 'rb')
# set the client Data
clientData = {
'type_client': request.data['type_client'],
'type_identity': request.data['type_identity'],
'document_number': request.data['document_number'],
'first_name': request.data['first_name'] if 'first_name' in request.data else None,
'last_name': request.data['last_name'] if 'last_name' in request.data else None,
'social_reason': request.data['social_reason'] if 'social_reason' in request.data else None,
'address': request.data['address'],
'city': request.data['city'],
'email': request.data['email'],
'phone_number': request.data['phone_number'],
'ciiu': request.data['ciiu'],
'broker': request.data['broker'],
'user': getUser.id,
'documents': pdf,
'status': 0,
'income': request.data['income'],
'entered_by': request.user.id
}
# Create a new client
client = ClientSerializer(data=clientData)
this is my model
from django.db import models
# Relations
from apps.misc.models import City, TypeIdentity, TypeCLient, CIIU
from apps.clients.api.models.broker.index import Broker
from apps.authentication.api.models.user.index import User
class Client(models.Model):
id = models.CharField(max_length=255, unique=True,primary_key=True, editable=False)
type_client = models.ForeignKey(TypeCLient, on_delete=models.CASCADE, blank=True)
type_identity = models.ForeignKey(TypeIdentity, on_delete=models.CASCADE, blank=True)
document_number = models.CharField(max_length=255, blank=True, unique=True)
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
social_reason = models.CharField(max_length=255, blank=True, null=True)
city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True)
address = models.CharField(max_length=255, blank=True)
email = models.CharField(max_length=255, blank=True, unique=True)
phone_number = models.CharField(max_length=255, blank=True, unique=True)
ciiu = models.ForeignKey(CIIU, on_delete=models.CASCADE, blank=True)
broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
documents = models.FileField(upload_to='documents/')
income = models.SmallIntegerField(blank=True, default=0)
entered_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name='entered_by')
state = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True, default=None)
class Meta:
db_table = 'clients'
verbose_name = 'clients'
verbose_name_plural = 'clients'
ordering = ['created_at']
as you can see in the documents property of the clientData dict I assign the combined pdf previously, is there any way to solve this?

I receive an error while migrating my models to a database

I get such an error while migrating to a database:
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: foreign key mismatch - "user_auth_customer"
referencing "user_auth_profile"
I have checked Foreign_Keys of my models and they look good.
I have no idea why I receive that error :(
Please, help me out here.
class Customer(AbstractUser):
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
profile = models.OneToOneField("Profile", related_name="user_profile",
on_delete=models.CASCADE, null=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
username = models.CharField(max_length=30, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(validators=[validators.EmailValidator()],
unique=True)
password = models.CharField(max_length=100, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
#staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def isExists(self):
if Customer.objects.filter(email=self.email):
return True
return False
class Meta:
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
class Profile(models.Model):
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(primary_key=True, unique=True, validators=[validators.EmailValidator()])
password = models.CharField(max_length=100, null=True, blank=True)
# Add a photo field
owner = models.OneToOneField(Customer, related_name='profile_owner',
on_delete=models.SET_NULL, null=True)
username = models.CharField(max_length=30, null=True, blank=True,
validators=[UnicodeUsernameValidator()])
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
if you need any else details, I can provide you with those in the comments.
You can't have both ways OneToOneField. Choose one way.
If you delete Customer's profile field, then still you will have possibility to call relation with:
customer = Customer.objects.get(id=1)
customer.profile # that will call Customer's related Profile object
Assuming, that you will change related_name='profile_owner' to simpler related_name='profile'.
Read more about OneToOneRelationships.

django RelatedObjectDoesNotExist error while creating

models:
class FullNameMixin(models.Model):
name_id = models.BigAutoField(primary_key = True, unique=False, default=None, blank=True)
first_name = models.CharField(max_length=255, default=None, null=True)
last_name = models.CharField(max_length=255, default=None, null=True)
class Meta:
abstract = True
class Meta:
db_table = 'fullname'
class User(FullNameMixin):
id = models.BigAutoField(primary_key = True)
username = models.CharField(max_length=255, unique=True)
email = models.CharField(max_length=255, unique=True)
token = models.CharField(max_length=255, unique=True, null=True, blank=True)
password = models.CharField(max_length=255)
role = models.IntegerField(default=1)
verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
def __str__(self):
return self.username
class Meta:
db_table = 'cga_user'
class Profile(FullNameMixin):
id = models.BigAutoField(primary_key = True)
birthday = models.DateTimeField(null=True, blank=True)
country = models.CharField(max_length=255, null=True, blank=True)
state = models.CharField(max_length=255, null=True, blank=True)
postcode = models.CharField(max_length=255, null=True, blank=True)
phone = models.CharField(max_length=255, null=True, blank=True)
profession_headline = models.CharField(max_length=255, null=True, blank=True)
image = models.ImageField(upload_to=get_upload_path, null=True, blank=True)
profile_banner = models.ImageField(upload_to=get_upload_path_banner, null=True, blank=True)
cga_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name="profile")
gender = models.CharField(
max_length=255, blank=True, default="", choices=USER_GENDER_CHOICES
)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
class Meta:
db_table = 'profile'
When i am creating Profile from django admin panel getting below error.
e
filename = self.upload_to(instance, filename)
File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/api/model_utils/utils.py", line 7, in get_upload_path
instance.user,
File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__
raise self.RelatedObjectDoesNotExist(
api.models.FullNameMixin.user.RelatedObjectDoesNotExist: Profile has no user.
[24/Jul/2021 13:49:51] "POST /admin/api/profile/add/ HTTP/1.1" 500 199997
please take a look how can i fix this.
Note: User model creation working but, profile not working
I checked in drf and django admin panel .
both place not working.
The problem here is that you are declaring a User model which is in fact just a model. That's not how it works.
The User is a special type of model and if you want to change it you have to extend the AbstractUser class.
Alternatively you can connect to it via one-to-one classes in the classic user-profiles approach.
But here you are creating a user model that (besides using the reserved word 'User') has none of the requirements necessary to be treated as a user who can be authenticated and that can instantiate sessions.
> Example of a simple user-profiles architecture
> Working with User objects - Django Docs (i particularly recommend this one)
I would recommend you to read-up on django user authentication.

Search Two Django Tables once within singel query

I am really confusing about Django joins. I want to search a keyword in two tables with a single query. can anyone help me?
the app model structure like this
class Events(models.Model):
event_type = models.CharField(_("Event Type"), max_length=5, choices=event_type_choices)
webinar_title = models.CharField(_("Webinar Title"), max_length=50, blank=True, null=True)
event_name = models.CharField(_("Event Name"), max_length=50, blank=True, null=True)
banner_title = models.CharField(_("Banner Title"), max_length=50, blank=True, null=True)
added_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
status = models.BooleanField(_("Event Status"), default=True)
class Meta:
verbose_name = _('Event')
db_table = 'events'
app_label = 'events'
class WebinarSpeakers(models.Model):
event = models.ForeignKey(Events, on_delete=models.CASCADE, null=True)
speaker = models.CharField(_("Speaker Name"), max_length=100, null=True, blank=True)
job_title = models.CharField(_("Job Title"), max_length=255)
place_of_work = models.CharField(_("Place of Work"), max_length=100)
credentials = models.TextField(_("Credentials"), null=True, blank=True)
image = models.ImageField(_("Speaker Image"), upload_to=speaker_file_name, null=True, blank=True)
class Meta:
verbose_name = _('Event Webinar Speakers')
db_table = 'webinar_speakers'
app_label = 'events'
Now I want to search a keyword in webinar_title, evetn_name, banner_title, speaker, 'job_title` with a single query. how to do it in Django joins. I read the select_related document. it confusing me.
WebinarSpeakers.objects.filter(event__webinar_title="something", event__event_name="something", event__banner_title="somethng", speaker="something",job_title="something")

Django Nested Serializer does not find attribute

This are my models
class OWNER_STORE(models.Model):
_id = models.CharField(max_length=120, unique=True, default=uuid.uuid4)
MSE_STORE_TYPE = models.ForeignKey(STORE_TYPE)
MSE_OWNER_INFO = models.ForeignKey(OWNER_INFO, related_name='STORES')
STORE_NAME = models.CharField("STORE_NAME", max_length=250, null=True, blank=True)
STORE_ID = models.IntegerField("STORE_ID", null=True, blank=True)
STORE_ADDRESS_HOUSE = models.CharField("STORE_ADDRESS_HOUSE", max_length=250, null=True, blank=True)
STORE_ADDRESS_ROAD = models.CharField("STORE_ADDRESS_ROAD", max_length=250, null=True, blank=True)
STORE_ADDRESS_VILLAGE = models.CharField("STORE_ADDRESS_VILLAGE", max_length=250, null=True, blank=True)
STORE_ADDRESS_UNION = models.CharField("STORE_ADDRESS_UNION", max_length=250, null=True, blank=True)
STORE_ADDRESS_THANA = models.CharField("STORE_ADDRESS_THANA", max_length=250, null=True, blank=True)
STORE_ADDRESS_DISTRICT = models.CharField("STORE_ADDRESS_DISTRICT", max_length=250, null=True, blank=True)
STORE_ADDRESS_DIVISION = models.CharField("STORE_ADDRESS_DIVISION", max_length=250, null=True, blank=True)
STORE_EMPLOYEE_STATUS = models.BooleanField("EMPLOYEE_STATUS")
STORE_NUMBER_OF_EMPLOYEE = models.IntegerField("NUMBER_OF_EMPLOYEE", null=True, blank=True)
STORE_AVG_REVENUE = models.IntegerField("STORE_AVG_REVENUE", null=True, blank=True)
STORE_AVG_COGS = models.IntegerField("STORE_AVG_COGS", null=True, blank=True)
STORE_AVG_PROFIT = models.IntegerField("STORE_AVG_PROFIT", null=True, blank=True)
STORE_CUSTOMER_CREDIT_LIMIT = models.IntegerField("CUSTOMER_CREDIT_LIMIT", null=True, blank=True)
STORE_BUSINESS_TARGET = models.IntegerField("BUSINESS_TARGET", null=True, blank=True)
STORE_REORDER_THRESHOLD = models.IntegerField("REORDER_THRESHOLD", null=True, blank=True)
STORE_PASSWORD = models.TextField("STORE_PASSWORD", max_length=50, default=None, null=True, blank=True)
def __str__(self):
return str(self.id)
class MSE_EMPLOYEE(models.Model):
emp_id = models.IntegerField(null=True, blank=True)
store = models.ForeignKey(OWNER_STORE)
MSE_EMPLOYEE_ID = models.IntegerField(null=True, blank=True)
MSE_EMPLOYEE_NAME=models.CharField(max_length=250, null=True, blank=True)
MSE_EMPLOYEE_MOBILE_NUMBER = models.CharField(max_length=250, null=True, blank=True)
MSE_EMPLOYEE_JOINING_DATE = models.DateField(null=True, blank=True)
MSE_EMPLOYEE_SALARY = models.IntegerField(null=True, blank=True)
def __str__(self):
return str(self.MSE_EMPLOYEE_NAME)
For my serializers.py, I did this
class STORE_EMPLOYEE_SERIALIZER(serializers.ModelSerializer):
employees = EMPLOYEE_SERIALIZER(many=True)
class Meta:
model = OWNER_STORE
fields=("MSE_STORE_TYPE", "MSE_OWNER_INFO", "STORE_NAME", "STORE_ID", "STORE_ADDRESS_HOUSE", "STORE_ADDRESS_ROAD",
"STORE_ADDRESS_VILLAGE", "STORE_ADDRESS_UNION", "STORE_ADDRESS_THANA", "STORE_ADDRESS_DISTRICT",
"STORE_ADDRESS_DIVISION", "STORE_EMPLOYEE_STATUS", "STORE_NUMBER_OF_EMPLOYEE",
"STORE_AVG_REVENUE", "STORE_AVG_COGS", "STORE_AVG_PROFIT", "STORE_CUSTOMER_CREDIT_LIMIT",
"STORE_BUSINESS_TARGET", "STORE_REORDER_THRESHOLD", "STORE_PASSWORD", "employees")
I was hoping that with a get request, I would get all the employees under store but I keep getting this error.
AttributeError: 'OWNER_STORE' object has no attribute 'employees'
and on the last line of terminal,
AttributeError: Got AttributeError when attempting to get a value for field employees on serializer STORE_EMPLOYEE_SERIALIZER.
The serializer field might be named incorrectly and not match any attribute or key on the OWNER_STORE instance.
Original exception text was: 'OWNER_STORE' object has no attribute 'employees'.
You need use MSE_EMPLOYEE_set instead employees.
Or add related_name to the store = models.ForeignKey(OWNER_STORE)
store = models.ForeignKey(OWNER_STORE, related_name='employees')