So i'm working on job application portal.
the logic is as follows :
Applicant ---> Applies for ---> Job
Models are (Job, User, Application)
I used the User model from django and i extend it.
Now the dilemma is when i render the ApplicationForm, because i have to update the foreign key and i want it to be updated automatically.
Here is my code :
Models.py
class Job(models.Model):
owner = models.ForeignKey(User,related_name='job_owner',on_delete=models.CASCADE)
title = models.CharField(max_length=100)
#location
job_type = models.CharField(max_length=15,choices=JOB_TYPE)
description= models.TextField(max_length=1000)
published_at = models.DateTimeField(auto_now=True)
vacancy = models.IntegerField(default=1)
salary = models.IntegerField(default=0)
experience = models.IntegerField(default=1)
category = models.ForeignKey('Category',on_delete=models.CASCADE)
icon = models.ImageField(upload_to ='job_icons/',default='job_icons/job.png')
slug = models.SlugField(blank = True,null=True)
class Application(models.Model):
job = models.ForeignKey(Job, related_name="job_applied",on_delete=models.CASCADE)
applicant = models.ForeignKey(User,related_name='job_applicant',on_delete=models.CASCADE)
first_name= models.CharField(max_length=40)
last_name= models.CharField(max_length=40)
email = models.EmailField(max_length=60)
website = models.URLField()
cv = models.FileField(upload_to='application/')
coverletter = models.TextField(max_length=550)
application_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.last_name+"\t"+self.first_name
Forms.py
class JobApplication(ModelForm):
class Meta:
model = Application
fields = ['first_name', 'last_name','email', 'website','cv','coverletter']
vews.py
def job_detail(request,slug):
job_specific = Job.objects.get(slug=slug)
form = JobApplication(instance=request.user)
if request.method == 'POST':
form = JobApplication(request.POST,request.FILES)
if form.is_valid():
my_form = form.save(commit=False)
my_form.job = job_specific
Application.applicant.user = request.user
Application.job = job_specific
my_form.save()
context ={'job_specific':job_specific, 'form':form,}
return render(request,"job/job_details.html",context)
So once the user submit their application, i wanted to updated the fields that are "foreign key" without prompting the user.
I do not know how to arrange this in the views.py or if it's even possible this way?
thanks to everyone in advance
So i solved the problem, it was really simple solution:
my_form = form.save(commit=False)
my_form.job = job_specific
my_form.applicant = request.user
Related
I have a CarRent model that is a ForeignKey to the Car model, on a CarRent detailView after payment i want to alter the CarRent model as well as the Car model, the code works well for the CarRent model, but altering the Car model results in “AttributeError at /car/requests/4/
type object 'Car' has no attribute 'object'” error
class Car(models.Model):
car_owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='car_owner', on_delete=models.CASCADE)
car_model = models.CharField(max_length=20, blank=True, null=True)
rented = models.BooleanField(default=False)
class CarRent(models.Model):
car = models.ForeignKey(Car, related_name='rented_car', on_delete=models.CASCADE)
driver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='driver_renting', on_delete=models.CASCADE)
active_rent = models.BooleanField(default=False, null=True)
rent_paid = models.BooleanField(default=False)
#login_required
#driver_required(redirect_field_name='app:home')
#csrf_protect
def car_rent_detail_view(request, pk):
object = get_object_or_404(CarRent, id=pk)
# queryset = Car.objects.get(id=pk)
car_object = get_object_or_404(queryset, id=pk)
paystack = PaystackAccount(
settings.PAYSTACK_EMAIL,
settings.PAYSTACK_PUBLIC_KEY,
object.total_cost
)
context = {'object': object, 'pk_public': settings.PAYSTACK_PUBLIC_KEY, 'currency': 'NGN', 'paystack': paystack,
}
if request.method == 'POST':
if paystack.verify_transaction(request.POST['reference']):
messages.success(request, "paystack payment successfull")
car_rented = Car.object.get(pk=pk)
car_rented.rented = True
rent_activation = CarRent.objects.get(pk=pk)
rent_activation.active_rent = True
rent_activation.rent_paid = True
rent_activation.save()
messages.success(request, "Your Rent has successfully being updated")
return render(request, 'app/CarRent_detail.html', context=context)
Any help will be appreciated greatly.
Its a typo, you need to use objects to access manager method, not object. So replace:
car_rented = Car.object.get(pk=pk)
^^^^^^
With:
car_rented = Car.objects.get(rented_car__pk=pk)
You can reverse query from Car model to CarRent via related_name(which is 'rented_car'). More information can be found in documentation.
How to i update a certain value in the database?
class Userdata(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
faculty = models.ForeignKey(Fakultas,on_delete=models.CASCADE,default= 1)
is_voted = models.BooleanField(default=False)
def __str__(self):return self.user.username
class Voting(models.Model):
name = models.CharField(max_length=50)
faculty = models.ForeignKey(Fakultas, on_delete=models.CASCADE, default=1)
pic = models.CharField(max_length=50)
text = models.TextField()
voters = models.IntegerField()
def __str__(self): return self.name
My Views :
def voted(response):
if response.method == 'POST':
id = response.POST.get['idcalon']
user = Userdata.objects.get() #get the username
calon2 = Voting.objects.get() #get user selection in html
user.is_voted = True
calon2.voters +=1
user.save(['is_voted'])
calon2.save(['voters'])
I'm trying to grab the user's name and then when update the user's is_voted value to True when triggered.
Then, I wanted to grab my Voting model by id, for example, I wanted to edit id = 1
So how do I do it? I've been trying to understand the documentation, but still have 0 idea how to do it.
Thank you
def voted(request):
if request.method == 'POST':
id = request.POST.get['idcalon']
user = Userdata.objects.get(id=request.user.id) #get the username
calon2 = Voting.objects.get(id=id) #get user selection in html
user.is_voted = True
calon2.voters +=1
user.save()
calon2.save()
this will work if user is authenticated
I have a Task model. I want to assign task to multiple users so i have taken ManytoMany relationship. So Django is creating a ManytoMany table but i want to track that which user has completed task and when. So I took intermediary model by using through='TaskComplete'. Now I can not see task_assign_to feild in form. And even i declare in modelForms and submit it gives below error.
Cannot set values on a `ManyToManyField` which specifies an intermediary model. Use audit.TaskComplete's Manager instead.
Now I want that admin selects the user from main form and into intermediary model.
I tried but can not find any solution for this. below is my code. Please guide me how to do it?
My Model:
class Task(models.Model):
task_audit_title = models.ForeignKey(MainAudit,on_delete= models.CASCADE, related_name='audit_title_for_task',verbose_name= ('Audit Title'))
task_subtask_name = models.ManyToManyField(SubTask, related_name='subtask_for_task',verbose_name= ('Subtask Title'))
task_subject = models.CharField(verbose_name= ('Task Subject'),max_length=100,blank=False)
task_description = models.CharField(verbose_name= ('Task Description'),max_length=1000,blank=True)
task_assign_to = models.ManyToManyField(User, related_name='task_assign_to', through='TaskComplete')
task_assign_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_crt_by')
task_deadline = models.DateTimeField(null=True,blank=True)
task_perticulars = models.ManyToManyField(Perticular, related_name='task_perticular', blank=True)
task_created_time = models.DateTimeField(default=timezone.now)
task_modified_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_mod_by', null=True, blank=True)
task_modified_time = models.DateTimeField(null=True,blank=True)
is_del = models.BooleanField(default=0)
class Meta:
permissions = (
("change_temp_delete_task", "Can delete temporarily"),
)
def __str__(self):
return self.task_subject
def get_absolute_url(self):
return reverse('create-task')
class TaskComplete(models.Model):
task_title = models.ForeignKey(Task,on_delete= models.CASCADE, related_name='assigned_task')
is_completed = models.BooleanField(default=0)
task_cmt_by_doer = models.CharField(verbose_name= ('Submit Comment'),max_length=100,blank=True)
completed_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name = 'task_completed_by')
completed_time = models.DateTimeField(null=True,blank=True)
My View:-
class TaskCraeteView(LoginRequiredMixin,SuccessMessageMixin,CreateView):
# permission_required = 'Company.add_company'
model=Task
success_message = " Task Craeted successfully!"
reverse_lazy('create-task')
login_url = 'login'
template_name = 'create-task'
form_class = TaskCreateForm
# fields =[]
def form_valid(self,form):
form.instance.task_assign_by = self.request.user
My traceback my traceback link
My Form
class TaskCreateForm(forms.ModelForm):
class Meta:
model = Task
fields = ['task_audit_title','task_subtask_name','task_subject','task_description',
'task_assign_to','task_deadline','task_perticulars']
I want to be able to have a user update two models with one submit button. The first model will house all of the book titles (unique) and pages that users submit. The other will show which users submitted which books.
Ideally, I'd like to do something like this:
if request.method == "POST":
form = AddBookForm(request.POST)
if form.is_valid():
books = form.save(commit=False)
ub = UserBooks()
books.book_title = form.cleaned_data['book_title']
books.book_total_pages = form.cleaned_data['book_total_pages']
ub.user = request.user
ub.book_title = form.cleaned_data['book_title']
ub.save()
books.save()
return redirect('new_book')
But that's giving me the error:
Cannot assign "'Some Book Title'": "UserBooks.book_title" must be a
"Books" instance.
What would be the best way to update two models with one form?
Here are the other files.
models.py
class Books(models.Model):
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
book_title = models.CharField(max_length=100, unique=True)
book_total_pages = models.IntegerField()
class Meta:
ordering = ('-created',)
def __str__(self):
return '{0}'.format(self.book_title)
class UserBooks(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False)
book_title = models.ForeignKey(Books, on_delete=models.CASCADE, null=False, blank=False)
views.py
def new_book(request):
user = request.user
if request.method == "POST":
form = AddBookForm(request.POST)
if form.is_valid():
books = form.save(commit=False)
books.book_title = form.cleaned_data['book_title']
books.book_total_pages = form.cleaned_data['book_total_pages']
books.save()
return redirect('new_book')
else:
form = AddBookForm()
return render(request, 'main/addanewbook.html', {
'form': form,
'allBooks': allBooks,
'userbooks': userbooks,
})
forms.py
class AddBookForm(forms.ModelForm):
class Meta:
model = Books
fields = ('book_title', 'book_total_pages')
you need to change a bit in the view
if form.is_valid():
books = form.save(commit=False)
ub = UserBooks()
books.book_title = form.cleaned_data['book_title']
books.book_total_pages = form.cleaned_data['book_total_pages']
books = books.save()
ub.user = request.user
ub.book_title = books
ub.save()
return redirect('new_book')
this will do it
Here is my model:
class Browser(models.Model):
profile_name = models.CharField(max_length=400)
browser_type = (
('fr', 'Firefox'),
('ch', 'Chrome'),
('op', 'Opera'),
('ot', 'Other'),
)
browser_name = models.CharField(choices=browser_type, max_length=2)
device_name = models.CharField(max_length=400)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Bookmark(models.Model):
browser = models.ForeignKey(Browser, on_delete=models.CASCADE, null=True, blank=True)
title = models.TextField()
url = models.TextField()
iv = models.TextField()
salt = models.TextField()
iteration = models.IntegerField(default=1500)
tags = TaggableManager()
I only want to update certain fields, so here is the modelform
class BookmarkFormEdit(ModelForm):
class Meta:
model = Browser
exclude = ('tags', 'browser_name', 'device_name', 'profile_name')
but my problem is, values are not updating as expected . Here is the view:
def bookmark_edit(request, pk=None):
if request.method == 'POST':
bookmark = Bookmark.objects.get(pk=pk)
frm = BookmarkFormEdit(request.POST, instance=bookmark)
print(request.POST.get('iteration')) // printing correct value from front-end
if frm.is_valid():
x = frm.save()
print(x.iteration) // not saving the new value !
return JsonResponse({'status': 'created'})
else:
return JsonResponse({'error': frm.errors})
return render(request, 'bookmark_edit.html', {'pk': pk})
You are incorrectly defined model in the form. You should use Bookmark model instead of Browser.
class BookmarkFormEdit(ModelForm):
class Meta:
model = Bookmark
You may need to define fields to include/exclude as you want for this model.