data passing by one to one field in Django - python

I have two models Employee and myCustomeUser in my Django project.
My models.py:
class myCustomeUser(AbstractUser):
username = models.CharField(default="abcdef", max_length=150, unique="True")
password = models.CharField(default="12345", max_length=150)
is_Employee = models.BooleanField(default=False)
is_Inspector = models.BooleanField(default=False)
is_IndustryOwner = models.BooleanField(default=False)
is_Admin = models.BooleanField(default=False)
class Employee(models.Model):
user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='releted_user')
extraField = models.TextField(blank=True)
Now I am trying to entry an Employee's data with views.py like this:
Employee_obj = Employee.objects.create(releted_user.username=this_username, releted_user.password=this_password, releted_user.is_Employee=True)
Employee_obj.save()
But It shows error like this:
Employee_obj = Employee.objects.create(releted_user.username=this_username, releted_user.password=this_password, releted_user.is_Employee=True)
^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
How can I solve this problem? Mainly I need to save any employee's data by Employee.objects.create()

You can not work with .create(foo.bar=…) that is just illegal Python syntax. If you need to create an object that is referenced throug a OneToOneField, you first create that object, like:
u = myCustomeUser.objects.create(
username=this_username,
password=this_password,
is_Employee=True
)
Employee_obj = Employee.objects.create(user=u)
Please do not store raw passwords. Django normally hashes passwords. See the how does Django stores passwords section of the documentation.

Related

Django PostgreSQL ArrayField does not work

I have just switched to PostegreSQL. Now whenever I add the following code to my Custom User Model, the database is broken, no new values are added to the database, for example during registration
from django.contrib.postgres.fields import ArrayField
class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('Email'), unique=True)
username = models.CharField(max_length=150, unique=True)
start_date = models.DateTimeField(default=timezone.now)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(default=timezone.now)
code = models.ImageField(blank=True, upload_to='code',)
#part that breaks the databse:
ip_addresses = ArrayField(
models.CharField(blank=True), default=list)
From the moment also no more migrations are recognized.
Or I get something like this
django.db.utils.ProgrammingError: column "ip_addresses" does not exist
LINE 1: ...ER COLUMN "ip_addresses" TYPE varchar(15)[] USING "ip_addres...
What error I get is 50 50 chance but atleast the first error is always here.
I also tried this which did not work either
ip_addresses = ArrayField(
models.CharField(max_length=15), default=list)

Unable to delete object from Django admin panel with MongoDB

I have a Django project using a MongoDB connected by Djongo. I created a simple model which looks like:
from django.db import models
# Create your models here.
class Property(models.Model):
name = models.CharField(max_length=128, blank=False)
property_type = models.CharField(max_length=24, blank=True)
include_on = models.CharField(max_length=256, blank=True)
format_example = models.TextField(blank=True)
notes = models.TextField(blank=True)
After registering the model by using the line admin.site.register(Property) in the admin.py file I end up seeing my model appear. After adding a test Property I see the line
The property “Property object (61226db9f4f416b206c706e5)” was added successfully.
Which tells me the item was added. It also appears on the admin panel but it looks like:
Property object (None)
If I select the property I get an error that says:
Property with ID “None” doesn’t exist. Perhaps it was deleted?
If I try to delete the property I get a ValueError with error of:
Field 'id' expected a number but got 'None'.
Since I am currently learning Django/MongoDB I actually ran across the ValueError once before. The fix was to delete the entire database and start over. The issue is I don't want to run into this in the future and want to know what I have to do to fix it, or correct what I am doing wrong.
I found my answer. Turns out I need to assign a primary key. I fixed this by changing my model to..
class Property(models.Model):
name = models.CharField(primary_key=True, max_length=128, blank=False)
property_type = models.CharField(max_length=24, blank=True)
include_on = models.CharField(max_length=256, blank=True)
format_example = models.TextField(blank=True)
notes = models.TextField(blank=True)

How to access data using reverse foreign key reference in django

I have a model named UserProfile and a model PersonalInformation. I would like to fetch all the data of PersonalInformation using UserProfile model when the user is logged into the webiste but i have a foreign key refernce in the PersonalInformation model with the UserProfile model so how do i fetch the personal information using UserProfile model?
User Profile Model :
class UserProfile(models.Model):
"""Represents a user's model inside our system"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
profile_picture = models.ImageField(upload_to='photos/%y/%m/%d/')
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
highest_degree_earned = models.CharField(max_length=255, blank=False)
college_name = models.CharField(max_length=255, blank=False)
graduation_year = models.IntegerField(default=2020, blank=False)
Personal Information Model :
class PersonalInformation(models.Model):
"""Represents a user's personal Infromation inside our system"""
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
mobile = models.CharField(max_length=10 ,blank=True)
bio = models.TextField(max_length=200, blank=True)
college_university = models.CharField(max_length=100, blank=False)
course = models.CharField(max_length=100, blank=False)
First of all, in the code, you are showing you have the names of the models wrong. The UserProfile model name is set as PersonalInformation, change it or the migrations won't work (it's not accepted on the database no matter which one you're using).
Referent to the question you're asking, to fetch the related instance of PersonalInformation of a certain UserProfile instance you should just query the next:
user = UserProfile.objects.get(id='') #Introduce the id of the user you want to fetch its personal information.
user.personalinformation_set.all() # This will return you a QuerySet with all the related instances of PersonalInformation class.
user.personalinformation_set.get(id='') #To get a specific one or you may use a filter to get a filtered QS.
If you want, you can use the related_name attribute for ForeignKey class in order to set a different name from personalinformation_set.
I recommend you too to read the Django documentation, it's really well explained and clear I think:
https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_one/
As I've seen in a comment, you may also think to use a OneToOne relation instead of ForeignKey if you only expect one instance of PersonalInformation per User. The documentation is at:
https://docs.djangoproject.com/en/2.2/topics/db/examples/one_to_one/

Django getting especific object using QuerySet in reverse relationship many-to-one

Lets say I have the following models:
Chat(models.Model):
community = models.ForeignKey(Community, related_name="chats", null=True, blank=True)
....
Community(models.Model):
slug = models.CharField(max_length=250, unique=True, default='')
....
Profile(models.Model):
public_name = models.CharField(max_length=20, unique=True)
community_subscriptions = models.ManyToManyField('Community', through='CommunitySubscription')
chat_subscriptions = models.ManyToManyField('Chat', through='ChatSubscription')
....
ChatSubscription(models.Model):
profile = models.ForeignKey(Profile, unique=False, related_name='chat_subscription')
chat = models.ForeignKey(Chat, null=True, blank=True, related_name='chat_subscribers')
....
CommunitySubscription(models.Model):
....
In a view I want to do the following:
profileA = Profile.objects.get(public_name=public_nameA)
profileB = Profile.objects.get(public_name=public_nameB)
community = Community.objects.get(slug=community_slug)
try:
# I want to get the unique chat that involves both profiles for a specific community or get DoesNotExist (or None) if there is not such chat.
chat = Chat.objects.????????????
except Chat.DoesNotExist:
....
If the chat exist then both profiles will have a ChatSubscription object relating the profile with the chat.
Is it possible to do this kind of filtering using Django QuerySets in one single line? If not what would be the most efficient way to do it in more than one line?
Thanks a lot in advance.
Pretty complex, so try using the Q object to do a 'AND' query (assuming I got what you're trying to do):
from django.db.models import Q
Chat.objects.filter(Q(chatsubscription__profile__in=[profileA,profileB]) & Q(community=communty))

Django unique_together does not allow ForeignKey field across applications when syncdb is executed

I'm trying to create a unique constraint on my TranslationRequest model listed below. TranslationRequest has a foreign key relationship with a MachineTranslator model, which exists in another Django application. When I try to run syncdb, I get the error: Error: One or more models did not validate:
wt_articles.translationrequest: "unique_together" refers to translator, a field that doesn't exist. Check your syntax.
When I remove translator from the unique_constraint specification, syncdb runs correctly. Note: I'm using Sqlite3 as my back-end database.
Here are the definitions of TranslationRequest and SourceArticle.
from wt_translation.models import MachineTranslator
class TranslationRequest(models.Model):
article = models.ForeignKey(SourceArticle)
target_language = models.ForeignKey(Language, db_index=True)
date = models.DateTimeField(_('Request Date'))
translator = models.ForeignKey(MachineTranslator),
status = models.CharField(_('Request Status'),
max_length=32,
choices=TRANSLATION_STATUSES)
class Meta:
unique_together = ("article", "target_language", "translator")
class SourceArticle(models.Model):
title = models.CharField(_('Title'), max_length=255)
language = models.ForeignKey(Language, db_index=True)
timestamp = models.DateTimeField(_('Import Date'), default=datetime.now())
doc_id = models.CharField(_('Document ID'), max_length=512)
source_text = models.TextField(_('Source Text'))
sentences_processed = models.BooleanField(_('Sentences Processed'))
Here is the definition of MachineTranslator, in a different (but referenced Django application).
class MachineTranslator(models.Model):
shortname = models.CharField(_('Name'), max_length=50)
supported_languages = models.ManyToManyField(LanguagePair)
description = models.TextField(_('Description'))
type = models.CharField(_('Type'), max_length=32, choices=TRANSLATOR_TYPES, default='Serverland'),
timestamp = models.DateTimeField(_('Refresh Date'), default=datetime.now())
is_alive = models.BooleanField()
Not all of the dependencies have been included in this code sample. Thanks for your help!
i dont' know if it is a typo but i see s "," comma at the end of the line where you declare your translator = models.ForeignKey(MachineTranslator)
This is why maybe the attribute is ot seens

Categories

Resources