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):
...
Related
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!
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.
I'm really having some trouble with this. I've got some custom user's setup and those users can be attached to companies via foreign key. I'm just having trouble saving them. I've tried a ton of different variations of getting the user attached to a company and I just can't crack it. The forms do work and it does both create a "customer" and a "customer company".
I know this needs to be a variation of:
if customer_form.is_valid() and customer_company_form.is_valid():
customer_company = customer_company_form.save()
customer = customer_form.save(commit=False)
customer.user = customer_company
customer_company.save()
models.py
class CustomerCompany(models.Model):
COUNTRIES = (
('USA', 'United States'),
('CAN', 'Canada')
)
name = models.CharField(max_length=100, blank=True, unique=True)
website = models.CharField(max_length=100, blank=True)
phone = models.CharField(max_length=10, blank=True)
address = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=255, blank=True)
state = USStateField(blank=True, null=True)
us_zipcode = USZipCodeField(blank=True, null=True)
ca_province = models.CharField(max_length=50, blank=True, null=True)
ca_postal_code = models.CharField(max_length=7, blank=True, null=True)
country =models.CharField(max_length=3, choices=COUNTRIES,
blank=True)
def get_absolute_url(self):
return reverse('accounts:customer_company_detail',kwargs={'pk':self.pk})
def __str__(self):
return self.name
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
primary_key=True, related_name='customer_profile')
company = models.ForeignKey(CustomerCompany, on_delete=models.CASCADE, null=True)
phone = models.CharField(max_length=10)
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name
forms.py
class CustomerSignupForm(UserCreationForm):
first_name = forms.CharField(max_length=50, required=True)
last_name = forms.CharField(max_length=50, required=True)
phone = forms.CharField(max_length=10, required=True)
email = forms.EmailField(required=True)
class Meta(UserCreationForm.Meta):
model = User
#transaction.atomic
def save(self, commit=True):
user = super(CustomerSignupForm, self).save(commit=False)
user.is_customer = True
user.first_name = self.cleaned_data.get('first_name')
user.last_name = self.cleaned_data.get('last_name')
user.email = self.cleaned_data.get('email')
user.save()
customer = Customer.objects.create(user=user)
customer.phone = self.cleaned_data.get('phone')
customer.save()
return user
class CustomerCompanyCreateForm(forms.ModelForm):
ca_province = CAProvinceField(required=False, label="Province")
ca_postal_code = CAPostalCodeField(required=False, label="Postal Code")
class Meta:
model = CustomerCompany
fields = ['name', 'website', 'phone', 'address', 'city', 'state',
'us_zipcode', 'country', 'ca_province', 'ca_postal_code']
labels = {
"us_zipcode": "Zipcode",
}
views.py Updated with working code
def customer_signup(request):
if request.method == 'POST':
customer_form = CustomerSignupForm(request.POST)
customer_company_form = CustomerCompanyCreateForm(request.POST)
if customer_form.is_valid() and customer_company_form.is_valid():
# first save the user object
user_obj = customer_form.save(commit=False)
# Then use this object to get to my Customer model via the related name
customer = user_obj.customer_profile
# now save the CustomerCompany
company = customer_company_form.save()
# attach the customer to the Company
customer.company = company
# now fully save the customer after he's attached to his company
customer.save()
return redirect('customer_dashboard:customer_dashboard')
else:
messages.error(request, 'Please correct the errors below.')
else:
customer_form = CustomerSignupForm()
customer_company_form = CustomerCompanyCreateForm()
return render(request, 'accounts/registration/customer_signup_combined.html', {
'customer_form' : customer_form,
'customer_company_form' : customer_company_form,
})
You're saving both forms in your view but you're not connecting the two objects.
Calling save on the customer_form will return a User object since its a User ModelForm. You can use this object to get to the Customer object via the customer_profile related_name and set the company field to the Company instance returned when you save the customer_company_form.
It should look like this:
if customer_form.is_valid() and customer_company_form.is_valid():
user_obj = customer_form.save(commit=True)
customer = user_obj.customer_profile
company = customer_company_form.save(commit=True)
customer.company = company
customer.save()
return redirect('customer_dashboard:customer_dashboard')
I'm trying to get all of a users reports and pass them to the page template. My question is how do I filter by user_id=1?
views.py
data = report.objects.values()
return render(request,'list.html',data)
models.py
class user(models.Model):
firstname = models.CharField(max_length=250)
lastname = models.CharField(max_length=250)
email = models.CharField(max_length=250)
password = models.CharField(max_length=250)
newsletter = models.BooleanField(default=0)
accountlevel = models.BigIntegerField(default=1)
reportsCreated = models.BigIntegerField(default=0)
class report(models.Model):
user = models.ForeignKey(user, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
dateran = models.DateField()
fromdate = models.DateField()
todate = models.DateField()
state = models.IntegerField()
graphURL = models.CharField(max_length=1000)
reporttype = models.CharField(max_length=250)
In your views.py you can filter values by user id.
Refer following code
data = report.objects.filter(user__id=your_user_id).values()
return render(request,'list.html',data)
Got it to work, I was missing the context,
data = Report.objects.filter(user__id=1).values()
context = {'data': data}
return render(request,'list.html',context)
Thank you call for your help :)
I created models called Interview, Users, Interview_interviewer like wise...
Interview_interviewer table has foreign keys from other models.
I just want to save data from both 2 tables to Interview_interviewer(Without django forms) table which is many to many table. So I just created the views and template for it. When button clicks it save the Interviewers to table along side with the interview. But when do it, It gave me and error called "User matching query does not exist".
/home/govinda/DMG/test3/myapp/views.py in hod_inter_interviewer_2
usr = User.objects.get(id=pid)
What should I do?
class Interview(models.Model):
Time = models.TimeField()
Date = models.DateField()
Venue = models.ForeignKey('Venue')
HOD = models.ForeignKey(User)
Vacancy = models.ForeignKey('Vacancy', on_delete=models.CASCADE)
Department = models.ForeignKey(Department, on_delete=models.CASCADE)
InterviewType = models.ForeignKey(InterviewType, on_delete=models.CASCADE)
Interviewer_Review = models.TextField(blank=True, null=True)
HOD_Review = models.TextField(blank=True, null=True)
HR_Review = models.TextField(blank=True, null=True)
NoOfPasses = models.PositiveIntegerField(blank=True, null=True)
NoOfFails = models.PositiveIntegerField(blank=True, null=True)
NoOfOnHolds = models.PositiveIntegerField(blank=True, null=True)
InterviewNo = models.IntegerField(blank=True, null=True)
Post = models.ForeignKey(Post, on_delete=models.CASCADE)
and
class Users(models.Model):
User = models.OneToOneField(User)
FullName = models.CharField(max_length=100)
Post = models.ForeignKey(Post)
UPhoto = models.FileField(upload_to=User_directory_path,null = True,blank=True)
Department = models.ForeignKey(Department)
UserRole = models.ForeignKey(UserRole)
def __str__(self):
return u'{}'.format(self.User)
and
class Interview_Interviewer(models.Model):
Interview = models.ForeignKey(Interview)
Interviewer = models.ForeignKey(User)
def __str__(self):
return u'{}'.format(self.Interviewer)
views are...
def hod_pre_interviwer_list(request, iid):
inter = Interview.objects.get(id=iid)
a = UserRole.objects.get(Role="Interviewer")
viewer = Users.objects.filter(UserRole=a.id)
return render(request, 'hod_inter_create_2.html', {'viewer': viewer, 'inter': inter, 'a':a})
def hod_inter_interviewer_2(request, iid, pid):
inter = Interview.objects.get(id=iid)
usr = User.objects.get(id=pid)
a = UserRole.objects.get(Role="Interviewer")
viewer = Users.objects.filter(UserRole=a.id)
usr_id = Users.objects.get(User=a.id)
inter_id = inter
person_id = usr_id
form = Interview_Interviewer(Interview=inter_id, Interviewer=person_id)
form.save()
return render(request, 'hod_inter_create_2.html', {'viewer': viewer, 'inter': inter})
urls are...
urlpatterns = [
url(r'^hod/hod_vacancy/test/part2/inter_list/(\d+)/$', hod_pre_interviwer_list, name="inter1"),
url(r'^hod/hod_vacancy/test/part2/inter_list/(\d+)/(\d+)/$', hod_inter_interviewer_2, name="inter2"),
]
template is...
<a type="submit" class="btn btn-primary" href="/hod/hod_vacancy/test/part2/inter_list/{{ inter.id }}/{{ viewer.id }}">Add</a>
Try using named groups in your url patterns
urlurl(r'^hod/hod_vacancy/test/part2/inter_list/?P<iid>[0-9]+)/?P<pid>[0-9]+/$', hod_inter_interviewer_2, name="inter2"),
If that doesn't work then i suggest trying User.object.get(pk=pid) as in most doc examples.
And make sure that there is a user with that id (iid) in the url.
You should also use get_object_or_404 for getting any single object from a model in the view as it gives a more user friendly and appropriate error.