How to get id from created object in Django - python

I have models: Group and Members.
Groups have many members, but when a Group is created, currentUser automatically becomes a Member.
I'm doing everything in single request and I have problem with getting id createdGroup.
My models:
class Group(models.Model):
groupName = models.CharField(max_length=100)
description = models.CharField(max_length=255)
inviteKey = models.UUIDField(default=uuid.uuid4,
unique=True,
editable=False)
class Members(models.Model):
userId = models.ForeignKey(User, on_delete=models.CASCADE)
groupId = models.ForeignKey(Group, on_delete=models.CASCADE)
Form:
class GroupForm(forms.ModelForm):
groupName = forms.CharField(label='Name', max_length=100)
description = forms.CharField(label='Description', max_length=255)
inviteKey: forms.CharField(label='Invite Key')
class Meta:
model = Group
fields = ['groupName', 'description']
View:
def createGroup(request):
if request.method == "POST":
form = GroupForm(request.POST)
if form.is_valid():
form.save()
currentUser = request.user
print('group id', request.POST.get('id', ''))
#after group creation i would add current member
addMember(currentUser, True, True) # should be currentUser, createdGroup, True
messages.success(request, f'Group created')
return redirect('/')
else:
form = GroupForm()
return render(request, 'group/createGroup.html',{'form': form})
How can I get the newly created Group's id?
I've tried something like this:
group = request.POST.get('id', '')
When I console.log(request.POST) I'm getting only (name, description)

try this:
new_group = form.save()
id = new_group.id
the id is created when you save the form triggert by the request... so it can't be in the request!

Related

Post Multiple values as foreign key -- Django restframework

I have a model(ProfessionalMemberContacts) which has a primary key in different model(MasterProfessionalMembers).
ProfessionalMemberContacts expects multiple or single set of details as per user input
ie user could give multiple contact details.
Problem: I cant figure out the way to loop over all the contact details(if multiple) to save in "ProfessionalMemberContacts" with reference to "MasterProfessionalMembers".
Here is my relevant code for models and views for it.
Models.py
class ProfessionalMemberContacts(models.Model):
professionalmemberId = models.ForeignKey(MasterProfessionalMembers, default=None,on_delete=models.CASCADE, related_name="pro_contact")
contact_person = models.CharField(max_length=100)
contact_email = models.EmailField(max_length=100)
contact_number = models.CharField(max_length=100)
class MasterProfessionalMembers(models.Model):
professionalmemberId = models.CharField(primary_key=True, max_length=100, default=1)
profile_pic = models.ImageField(blank=True)
organization_name = models.CharField(max_length=100)
incorp_date = models.DateField(default=date.today())
organization_type = models.CharField(max_length=100)
views.py
#api_view(['POST'])
#csrf_exempt
#permission_classes([IsAuthenticated])
def create_pro_individual_member(request):
if request.method == "POST":
contact_person = request.POST.getlist('contact_person')
contact_email = request.POST.getlist('contact_email')
contact_number = request.POST.getlist('contact_number')
professionalmemberId =request.POST.get('professionalmemberId')
member_object = MasterProfessionalMembers.objects.get(professionalmemberId=professionalmemberId)
if len(contact_person) != 0:
for p,ce,n in contact_person, contact_email, contact_number:
reference = ProfessionalMemberContacts(
contact_person = p,
contact_email = ce,
contact_number = n,
professionalmemberId = member_object
)
reference.save()
return HttpResponse('professionalmember Id created as: '+professionalmemberId)
EDIT: Changed the input value fields to request.POST.getlist(<value>)
Note: Expecting data and values in Form data.
Please suggest any way to save contact details provided by user.
Request Data: Testing in postman as Form data
professionalmemberId = 1234567
contact_person = abc
contact_email = abc#xyz.com
contact_number = 567789
contact_person = xyz
contact_email = xyz#abc.com
contact_number = 123456890
Try to use zip:
for p,ce,n in zip(contact_person, contact_email, contact_number):
...

how to set a default value in Django forms?

In the database there is class Borrowing which contains employee_id that will borrow item and tag_id (the item) and subscriber_id
in my code, if an employee request a borrowing, he can choose subscriber_id.
I need to set the subscriber_id to 1, without even asking the employee to choose.
in the models.py file
class Borrowing(models.Model):
borrowing_id = models.IntegerField(null=True)
start_date = models.DateField(auto_now_add=True, null=True)
end_date = models.DateField(null=True)
employee_id = models.ForeignKey(Employee, null=True, on_delete= models.SET_NULL)
tag_id = models.ForeignKey(Tag, null=True, on_delete= models.SET_NULL)
subscriber_id = models.ManyToManyField(Subscriber)
def __str__(self):
return str(self.borrowing_id)
in forms.py file
class BorrowingForm(ModelForm):
class Meta:
model = Borrowing
fields = ['end_date', 'employee_id', 'tag_id', 'subscriber_id']
in views.py
def createBorrowing(request, pk):
BorrowingFormSet = inlineformset_factory(Employee, Borrowing, fields=('end_date','tag_id','subscriber_id'))
employee = Employee.objects.get(id=pk)
formset = BorrowingFormSet(queryset=Borrowing.objects.none(), instance=employee)
if request.method == 'POST':
formset = BorrowingFormSet(request.POST, instance=employee)
if formset.is_valid():
formset.save()
return redirect('/login')
context = {'formset':formset}
return render(request, 'assetstracking/createBorrowing.html', context)
You must set a default value in the Models.py
class Borrowing(models.Model):
...
subscriber_id = models.ManyToManyField(Subscriber, default=default_subscriber)
...
def __str__(self):
return str(self.borrowing_id)
And if you don't need the employee to chose you can remove subscriber_id from the fields in the forms.py
Notice that default_subscriber needs to be a subscriber.

django model form saving data to multiple models

I have a Custom User model with a team field. I also have a Team model with a ManyToManyField for the Custom Users.
I have a template that allows a user to create a team using whatever Team Name they want. Upon creation, I want that user's Team to be assigned but the team primary key isn't created until the Team is created so how do I get that primary key id into the Custom User model?
My direction of thought is that I would perform a user save after the "create-team" form save in the views, but I'm not sure how to do that.
models.py
class Team(models.Model):
team_id = models.BigAutoField(auto_created=True, primary_key=True)
team_name = models.CharField(max_length=35, null=False, default='YourTeam')
team_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30)
num_users = models.IntegerField(default=1)
emails = models.ManyToManyField('CustomUser', related_name='teamemails')
class CustomUser(AbstractUser):
username = None
first_name = models.CharField(max_length=255, unique=False, verbose_name='first name')
last_name = models.CharField(max_length=255, unique=False, verbose_name='last name')
email = models.EmailField(max_length=255, unique=True)
team = models.ForeignKey(Team, on_delete=models.SET_NULL, null=True, blank=True, related_name='userteam')
team_leader = models.BooleanField(default=False)
team_member = models.BooleanField(default=False)
forms.py
class CreateTeamForm(forms.ModelForm):
team_name = forms.CharField(label='Team Name', required=True)
class Meta:
model = Team
fields = ['team_name']
views.py
#verified_email_required
def create_team(request):
template = 'users/create_team.html'
if request.method == "POST":
form = CreateTeamForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
form.team_name = request.team_name
form.save()
messages.success(request, 'Team Created!')
return redirect('home')
else:
messages.error(request, 'Oops! Something went wrong')
else:
form = CreateTeamForm()
context = {
'form':form,
}
return render(request, template, context)

getting value from Mysql and passing to Django

I connected my database to django. I want to enable user (teacher) insert the name of a student and get test results on certain subjects.
I run python3 manage.py inspectdb and inserted it into models.py
class Profilez(models.Model):
student = models.CharField(max_length=255)
schgroup = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profilez'
class Schoolz(models.Model):
profilez_id = models.AutoField(primary_key=True)
lit = models.IntegerField(blank=True, null=True)
math = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'schoolz'
in forms.py i put:
class StudentForm(forms.ModelForm):
SUB = (
('lit', 'lit'),
('math', 'math')
)
student = forms.CharField(max_length=150, label='', widget=forms.TextInput)
class Meta:
model = Schoolz
fields = ('student',)
in views.py:
def home(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
form1 = form.save(commit=True)
name = form1.student
ab=schoolz.objects.all()
context={
'name':name,
}
return render(request, 'book/analysis.html', context)
else:
form = StudentForm()
return render(request, 'book/search.html', {'form': form})
Can you please help me to understand what i am doing wrong and how to get value for certain subject for exmaple math subject.
I would appreciate help and guidance to undertand and execute it. I am struggling a month.
Notes
Add a field in Profile that should be unique for each student. Currently I am assuming name and surname combination will be unique.
If you use ajax, you can get score without refresh. Current way I have used is not very good.
You don't have to write models if you already have in DB. You can remove your models. add already present models in models.py and makemigrations and migrate.
Add a ForiegnKey field in Class10
class Class10(models.Model):
profile_id = models.IntegerField()
math = models.IntegerField()
literature = models.IntegerField()
biology = models.IntegerField()
student = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='stud_name') # add this in model
class Meta:
managed = False # make this True otherwise makemigrations won't get the changes.
db_table = 'class_10'
class Profile(models.Model):
student_name = models.CharField(max_length=255)
student_surname = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profile'
views.py
def home(request):
if request.method == "POST":
form = StudentlForm(request.POST)
if form.is_valid():
form_1 = form.save(commit=False)
name = form_1.student_name
surname = form_1.student_surname
subject = form_1.subject
fil = Q(student__student_name=name) & Q(student__student_surname=surname)
student_1 = StudentScore.objects.filter(fil).values()
score = student_1[0][subject] # answer
context={
'score':score
}
return render(request, 'school/analysis.html', context)
else:
form = StudentlForm()
return render(request, 'school/search.html', {'form': form})
forms.py
class StudentForm(forms.ModelForm):
SUB = (
('math', 'math'),
('literature', 'literature'),
('biology', 'biology')
)
student_name = forms.CharField(max_length=150, label='', widget=forms.TextInput)
student_surname = forms.CharField(max_length=150, label='', widget=forms.TextInput)
subject = forms.CharField(widget=forms.Select(choices=SUB))
class Meta:
model = Profile
fields = ('student_name', 'student_surname', 'subject')
#Nina,
Please look on the relationship> it's general idea for the Student & Gradesheet model
class Student(models.Model):
std_name = models.CharField(max_length=100)
def __str__(self):
return self.std_name
class Gradesheet(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
sub = models.CharField(max_length=50)
grade = models.CharField(max_length=50)
def __str__(self):
return self.student.std_name
So if you need to search for a student grade for particular subject:
std_info = Student.objects.get(std_name='Nina')
Then you will get a Student Class instance for Nina.
Now fetch the data by relationship:
std_grade = std_info.gradesheet_set.filter(sub='math')
You will get QuerySet. Then just :
std_grade[0].grade
You will get your student's grade for particular subject. Look its a model relationship. So you may use other filtering options also to get your desired result.
According to your given model:
Instead of the profile_id you should use the Profile object which will help you to take the control through django ORM.
class Profile(models.Model):
student_name = models.CharField(max_length=255)
student_surname = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profile'
class Class10(models.Model):
#profile_id = models.IntegerField()
profile = models.OneToOneField(Profile, on_delete=models.CASCADE,related_name='profile')
math = models.IntegerField()
literature = models.IntegerField()
biology = models.IntegerField()
class Meta:
managed = False
db_table = 'class_10'
So your query can be build by:
std_profile = Profile.objects.get(student_name='SomeoneName')
Now turn it for get the grade. Result would be:
math_grade = std_profile.profile.math
biology_grade = std_profile.profile.biology
literature_grade = std_profile.profile.literature
average_grade = ((math_grade + biology_grade + literature_grade)/3)
Here, your model relationship:Profile to Class10 is OneToOne

Cannot assign "'HR'": "Employee.department" must be a "Department" instance

when I try to feel department field is show me this error.
I don't understand this error.. please help me out
Cannot assign "'HR'": "Employee.department" must be a "Department" instance.
here is my model.py
class Department(models.Model):
name = models.CharField(max_length= 20,null=True)
def __str__(self):
return self.name
class Employee(models.Model):
employee_name = models.CharField(max_length= 20, null=True)
surname = models.CharField(max_length= 20, null=True)
address = models.CharField(max_length = 50, null=True)
qualification = models.CharField(max_length = 30,null=True)
contact_num = models.IntegerField(null=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
def __str__(self):
return self.employee_name
here is my form.py
class AdForm(forms.ModelForm):
employee_name = forms.CharField()
surname = forms.CharField ()
address = forms.CharField ()
qualification = forms.CharField ()
contact_num = forms.IntegerField ()
department = forms.CharField()
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
here is my view.py
def create(request):
if request.method == 'POST':
form = AdForm(request.POST)
if form.is_valid(): #getting error on this
form.save()
return HttpResponseRedirect(reverse('employee-list'))
else:
form = AdForm()
return render(request, 'employee/create.html', {'form': form})
The department field on your Employee model is a ForeignKey field, but in your AdForm you define it as CharField.
You could fix the field definition in your form. Alternatively, you could also simply remove the explicit field definition. When using a model form, Django will select the correct field type for you.
class AdForm(forms.ModelForm):
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
This will render the department field as a <select> widget, allowing you to select from your (pre-existing) departments.

Categories

Resources