Please help me I don't know what I am doing wrong I am getting an error
Available_time matching query does not exist.
I use here OneToOneField from the Available_time database from Sunday to Saturday. I don't understand why this error is showing.
class Available_time(models.Model):
timezone = models.TimeField(auto_now=False, auto_now_add=False)
nickname = models.CharField(max_length=30, default='IST_time')
def __str__(self):
return str(self.nickname)
class RMDatabase(models.Model):
user_id = models.ForeignKey(User, on_delete=models.CASCADE)
date_at = models.DateTimeField(auto_now=True)
country= models.CharField(max_length=100, blank=True)
province = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=100, blank=True)
contact = models.CharField(max_length=100, blank=True)
countryCode = models.CharField(max_length=100, blank=True)
motherTongue = models.CharField(max_length=100, blank=True)
secondSpokenLang = models.CharField(max_length=100, blank=True)
secondSpokenLangReason = models.CharField(max_length=100, blank=True)
interstedIn = models.CharField(max_length=100, blank=True)
skillLevel = models.CharField(max_length=100, blank=True)
qualification = models.CharField(max_length=100, blank=True)
qualificationAwardedBy = models.CharField(max_length=100, blank=True)
qualificationFile= models.FileField(upload_to='folder/')
videolink = models.CharField(max_length=100, blank=True)
preferredDayTime = models.CharField(max_length=100, blank=True)
sunday= models.ManyToManyField(Available_time,blank=True, related_name='sunday')
monday = models.ManyToManyField(Available_time, blank=True,related_name='monday')
tuesday= models.ManyToManyField(Available_time,blank=True, related_name='tuesday')
wednesday = models.ManyToManyField(Available_time, blank=True,related_name='wednesday')
thrusday= models.ManyToManyField(Available_time,blank=True, related_name='thrusday')
friday = models.ManyToManyField(Available_time, blank=True,related_name='friday')
saturday = models.ManyToManyField(Available_time,blank=True, related_name='saturday')
def __str__(self):
return self.motherTongue
**My view.py
here I simple takin input from the user and save the database. the problem I facing from **if request.POST.get('sunday-evening'): to till end if conditions. if remove those lines then working fine.
def MNFRM(request):
x= RMDatabase()
# if request.user.is_active:
# if x.objects.filter(user_id=request.user).exists():
# return render(request, 'relationshipmanager/userexists.html')
if request.method == 'POST':
x.user_id = request.user
x.country = country_list[str(request.POST.get('country')).upper()]
x.province = request.POST.get('state')
x.city = request.POST.get('city')
x.contact = request.POST.get('number')
x.countryCode = request.POST.get('code')
for it in ["motherTounge", "nativLanguage", "mediumOfInstruction", "qualifiedInParticularLanguage"]:
if request.POST.get(it):
s = it+','
x.secondSpokenLangReason += s
x.motherTongue = request.POST.get('motherTongue')
x.secondSpokenLang=request.POST.get('secondSpokenLang')
for it in ["Script Writing", "Producing Films", "Directing", "Acting", "Editing", "Animation"]:
if request.POST.get(it):
s = it+','
x.interstedIn += s
x.skillLevel=request.POST['SkillLevel']
x.qualification=request.POST.get('qualification')
x.qualificationAwardedBy=request.POST.get('qualificationAwardedBy')
x.qualificationFile=request.FILES['qualificationFile']
x.videolink=request.POST.get('videolink')
x.save()
if request.POST.get('sunday-evening'):
x.sunday.add(Available_time.objects.get(nickname='evening-time'))
if request.POST.get('sunday-afternoon'):
x.sunday.add(Available_time.objects.get(nickname='afternoon-time'))
if request.POST.get('sunday-morning'):
x.sunday.add(Available_time.objects.get(nickname='morning-time'))
if request.POST.get('monday-evening'):
x.monday.add(Available_time.objects.get(nickname='evening-time'))
if request.POST.get('monday-afternoon'):
x.monday.add(Available_time.objects.get(nickname='afternoon-time'))
if request.POST.get('monday-morning'):
x.monday.add(Available_time.objects.get(nickname='morning-time'))
if request.POST.get('tuesday-evening'):
x.tuesday.add(Available_time.objects.get(nickname='evening-time'))
if request.POST.get('tuesday-afternoon'):
x.tuesday.add(Available_time.objects.get(nickname='afternoon-time'))
if request.POST.get('tuesday-morning'):
x.tuesday.add(Available_time.objects.get(nickname='morning-time'))
if request.POST.get('wednesday-evening'):
x.wednesday.add(Available_time.objects.get(nickname='evening-time'))
if request.POST.get('wednesday-afternoon'):
x.wednesday.add(Available_time.objects.get(nickname='afternoon-time'))
if request.POST.get('wednesday-morning'):
x.wednesday.add(Available_time.objects.get(nickname='morning-time'))
if request.POST.get('thrusday-evening'):
x.thrusday.add(Available_time.objects.get(nickname='evening-time'))
if request.POST.get('thrusday-afternoon'):
x.thrusday.add(Available_time.objects.get(nickname='afternoon-time'))
if request.POST.get('thrusday-morning'):
x.thrusday.add(Available_time.objects.get(nickname='morning-time'))
if request.POST.get('friday-evening'):
x.friday.add(Available_time.objects.get(nickname='evening-time'))
if request.POST.get('friday-afternoon'):
x.friday.add(Available_time.objects.get(nickname='afternoon-time'))
if request.POST.get('friday-morning'):
x.friday.add(Available_time.objects.get(nickname='morning-time'))
if request.POST.get('saturday-evening'):
x.saturday.add(Available_time.objects.get(nickname='evening-time'))
if request.POST.get('saturday-afternoon'):
x.saturday.add(Available_time.objects.get(nickname='afternoon-time'))
if request.POST.get('saturday-morning'):
x.saturday.add(Available_time.objects.get(nickname='morning-time'))
x.save()
# email_message = EmailMessage(
# "RM Registration Successful",
# "Hi "+str(request.user.first_name)+' '+str(request.user.last_name) +
# ",\nYou have successfully registered for our Relationship Manager programme.",
# settings.EMAIL_HOST_USER,
# [request.user.email]
# )
# email_message.send()
subject= "Relationship Manager form is successfully submitted "+ "."
from_email = settings.EMAIL_HOST_USER
to = request.user.email
html_content = render_to_string('relationshipmanager/email.html') # render with dynamic value
# Strip the html tag. So people can see the pure text at least.
text_content = strip_tags(html_content)
# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
return redirect('base')
# return HttpResponse('Thanks your application has successfully registered, we will notify you via email about your application status.')
# z = xyz()
# print(z)
# return render(request, 'lpp/lppreg.html', {})
return render(request,'relationshipmanager/rmreg.html',{})
Related
This is my models
class Tasklist(models.Model):
clientname= models.CharField(max_length=100,null=True,blank=True)
task = models.CharField(max_length=100)
startdate = models.DateField(default=timezone.now, blank=True, null=True)
enddate = models.DateField(blank=True, null=True)
assignee = models.CharField(max_length=30)
status = models.CharField(max_length=30)
fstatus = models.BooleanField(default=False)
def __str__(self):
return self.task + " - Task - " + str(self.fstatus)
class edit_page(models.Model):
old_id = models.ForeignKey(Tasklist,on_delete=models.CASCADE)
updatedate = models.DateField(blank=True, null=True)
time_from = models.TimeField(blank=True, null=True)
time_to = models.TimeField(blank=True, null=True)
messagelogs = models.TextField(blank=True, null=True)
def __str__(self):
return self.messagelogs
This is My Views page
def edit_task(request, task_id):
if request.method == "POST":
updatedate=request.POST.get("updatedate","")
time_from=request.POST.get("time_from","")
time_to=request.POST.get("time_to","")
messagelogs=request.POST.get("messagelogs","")
test_list=edit_page(updatedate=updatedate,time_from=time_from,time_to=time_to,messagelogs=messagelogs)
test_list.save()
task = Tasklist.objects.get(pk=task_id)
form = TaskForm(request.POST or None, instance = task)
if form.is_valid():
form.save()
messages.success(request,("Task Edited "))
return redirect('email_updatetask', (task_id))
return redirect('todolist')
else:
task_obj = Tasklist.objects.get(pk=task_id)
return render(request, 'edit.html', {'task_obj': task_obj})
can u pls how can i store my primary keys into the second foreign key field via HTML files....
I am trying to change my label in Forms. But despite trying, I can't get a label change for consumer field. I also don't see a typo made by me.
models.py
class Offer(models.Model):
owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='Klient')
seller = models.ForeignKey(Seller, on_delete=models.CASCADE, verbose_name='Sprzedawca')
vat = models.ForeignKey(Vat, on_delete=models.CASCADE, verbose_name='Stawka VAT')
annual_usage_kw = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name='Roczne zużycie KW')
monthly_usage_kwh = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name='Miesięczne zużycie KWH')
monthly_usage_zl = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name='Miesieczne zużycie PLN')
excepted_power = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name='Oczekiwana moc KW')
roof_orientation = models.ForeignKey(RoofConstruction, on_delete=models.CASCADE, verbose_name='Konstrukcja dachu')
price_per_kw = models.ForeignKey(PricePerKw, on_delete=models.CASCADE, verbose_name='Cena za KW')
product = models.ManyToManyField(Product, verbose_name='Produkt')
inverter = models.ManyToManyField(Inverter, blank=True, verbose_name='Inverter')
number_of_product = models.IntegerField(blank=True, null=True, verbose_name='Liczba produktów (opcjonalnie)')
employer_margin_price = models.IntegerField(blank=True, null=True, verbose_name='Marża cenowa pracownika')
accessories = models.ManyToManyField(Accesorie, blank=True, verbose_name='Akcesoria')
forms.py
class OfferParametersForm(forms.ModelForm):
class Meta:
model = Offer
fields = ('customer', 'vat', 'annual_usage_kw', 'monthly_usage_kwh', 'monthly_usage_zl', 'excepted_power',
'roof_orientation', 'price_per_kw')
labels = {'customer': 'Klient',
'vat': 'VAT',
'annual_usage_kw': 'Roczne zużycie KW',
'monthly_usage_kwh': 'Miesięczne zużycie KWH',
'monthly_usage_zl': 'Miesieczne zużycie PLN',
'excepted_power': 'Oczekiwana moc KW',
'roof_orientation': 'Konstrukcja dachu',
'price_per_kw': 'Cena za KW',
}
I use my form as method {{ form.as_p }}. I guess I might be making some stupid mistakes. But I don't see the wrong setting and my label is still costumer instead of klient. How to change costumer label to klient.
views.py
def parameters(request):
#basic
step = 2
step_percentages = 33
template_name = 'Nowa oferta'
object_id = request.session.get('costumer_id')
#form
OfferParametersForm.base_fields['customer'] = forms.ModelChoiceField(queryset=Customer.objects.filter(owner=request.user))
if request.method == 'POST':
form = OfferParametersForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
qd = QueryDict(mutable=True)
qd.update(customer=cd['customer'], vat=cd['vat'], annual_usage_kw=cd['annual_usage_kw'],
monthly_usage_kwh=cd['monthly_usage_kwh'], monthly_usage_zl=cd['monthly_usage_zl'],
excepted_power=cd['excepted_power'], roof_orientation=cd['roof_orientation'],
price_per_kw=cd['price_per_kw'])
return HttpResponseRedirect(
'{}?{}'.format(reverse('app:products'), qd.urlencode())
)
else:
form = OfferParametersForm(initial={'customer': object_id,
'vat': 1})
context = {'step': step,
'step_percentages': step_percentages,
'template_name': template_name,
'form': form}
return render(request, 'app/parameters.html', context)
I am new to Python trying to make forms field and have a problem.
My forms shows correctly at html but when I am trying to submit data and save it to a database, but I have an error:
TypeError at /srdb/
'send_date' is an invalid keyword argument for this function
Here is my code:
models.py
class Srdb(models.Model):
send_date = models.DateField()
send_weight = models.IntegerField(default=0, validators=[MaxValueValidator(10000), MinValueValidator(100)])
track_code = models.CharField(default=None, blank=False, max_length=20)
send_index = models.IntegerField(default=None, blank=False,
validators=[MaxValueValidator(999999), MinValueValidator(100000)])
sender_fullname = models.CharField(default=None, blank=False, max_length=150)
sender_dob = models.DateField()
sender_adress = models.CharField(default=None, blank=False, max_length=400)
receiver_index = models.IntegerField(default=None, blank=False,
validators=[MaxValueValidator(999999), MinValueValidator(100000)])
receiver_fullname = models.CharField(default=None, blank=False, max_length=150)
receiver_adress = models.CharField(default=None, blank=False, max_length=400)
sender = models.ForeignKey(Dostavshik, on_delete=models.CASCADE, default=None, blank=False)
def __str__(self):
return str(self.id)
forms.py
class SrdbForm(forms.Form):
send_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Дата Отправки')
send_weight = forms.IntegerField(initial=0, validators=[MaxValueValidator(10000), MinValueValidator(100)],
label='Отправленный Вес (граммы)')
track_code = forms.CharField(max_length=20,
widget=forms.TextInput(attrs={'placeholder': 'Код Отслеживания Посылки'}),
label='Трек Код')
send_index = forms.IntegerField(validators=[MaxValueValidator(999999), MinValueValidator(100000)],
widget=forms.TextInput(attrs={'placeholder': 'Индекс Почты Отправления'}),
label='Индекc Отправления')
sender_fullname = forms.CharField(max_length=150,
widget=forms.TextInput(attrs={'placeholder': 'Отправитель'}),
label='ФИО отправителя')
sender_dob = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Дата Рождения Отправителя')
sender_adress = forms.CharField(max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Полный Адрес Отправителя'}),
label='Адрес отправителя')
# Получатель
receiver_index = forms.IntegerField(validators=[MaxValueValidator(999999), MinValueValidator(100000)],
widget=forms.TextInput(attrs={'placeholder': 'Индекс Почты Получения'}),
label='Индекс Получателя')
receiver_fullname = forms.CharField(max_length=100,
widget=forms.TextInput(attrs={'placeholder': 'Получатель'}),
label='ФИО Получателя')
receiver_adress = forms.CharField(max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Полный Адрес Получателя'}),
label='Адрес Проживания Получателя')
sender = forms.ModelChoiceField(queryset=Dostavshik.objects.all(),
label='Отправил Доставщик')
views.py
def srdb(request):
form_srdb = SrdbForm()
if request.method == 'POST':
form_srdb = SrdbForm(request.POST)
if form_srdb.is_valid():
Srdb.objects.create(**form_srdb.cleaned_data)
messages.success(request, 'Данные Успешно Сохранены')
context = {
'form_srdb': form_srdb
}
template = 'srdb.html'
return render(request, template, context)
After submit always have this error:
TypeError at /srdb/
'send_date' is an invalid keyword argument for this function
When requesting a blank RegisterForm, I get a KeyError. I believe that when I click the link on the site, I submit a GET request to the register method and the form1 = RegisterForm() line fires. I believe there is something wrong with my RegisterForm class but I can't figure out what it is. I'm using the User model and UserCreationForm. Any help is greatly appreciated.
KeyError at /profile/pm/register u'username'
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vagrant/project/tmp/user_profile/views.py" in register
77. form1 = RegisterForm()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/forms.py" in __init__
97. self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': ''})
Exception Type: KeyError at /profile/pm/register
Exception Value: u'username'
views.py
def register(request, user_type):
if user_type not in ["pm", "hm"]:
raise Http404
if request.user.is_authenticated():
return redirect(reverse('index'))
if user_type == 'hm':
userTypeChoices = [Profile.RecruiterAgency, Profile.RecruiterInternal, Profile.HiringManager]
else:
userTypeChoices = [Profile.PMEmployee, Profile.PMContractConsultant, Profile.PMBoth]
if request.method =="POST":
# accept tos
if 'accepted_tos' in request.POST:
return acceptedTOS(request)
form1 = RegisterForm(request.POST)
form2 = ProfileForm(request.POST)
if form1.is_valid() and form2.is_valid():
user = form1.save()
profile = Profile()
profile.user_id = user.id
profile.company = form2.cleaned_data["company"]
profile.phone = form2.cleaned_data["phone"]
profile.user_type = form2.cleaned_data["user_type"]
profile.save()
if profile.user_type in [Profile.PMEmployee, Profile.PMContractConsultant, Profile.PMBoth]:
prospect = Prospect(profile=profile)
prospect.save()
else:
employer = Employer(profile=profile)
employer.save()
return JsonResponse({'message':'success'})
else:
return JsonResponse({'message':form2.errors})
else:
form1 = RegisterForm()
form2 = ProfileForm()
return render(request, 'profile/register.html', {'form1':form1, 'form2':form2, 'userType':user_type, 'userTypeChoices':userTypeChoices})
forms.py
class RegisterForm(UserCreationForm):
email = forms.EmailField(label = "Email")
first_name = forms.CharField(label = "First name")
last_name = forms.CharField(label = "Last name")
class Meta:
model = User
fields = ("email", "first_name", "last_name")
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError('Email already in use.')
return email
def save(self, commit=True):
user = super(RegisterForm, self).save(commit=False)
user.username = self.cleaned_data["email"]
if commit:
user.save()
return user
models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
phone = models.CharField(max_length=200, null=True, blank=True)
RecruiterAgency = 'ra'
RecruiterInternal = 'ri'
HiringManager = 'hm'
PMEmployee = 'pe'
PMContractConsultant = 'pc'
PMBoth = 'pm'
USER_TYPE_CHOICES = (
(RecruiterAgency, 'Recruiter - Agency'),
(RecruiterInternal, 'Recruiter - Internal'),
(HiringManager, 'Hiring Manager'),
(PMEmployee, 'PM - Employee'),
(PMContractConsultant, 'PM - Contract / Consultant'),
(PMBoth, 'PM - Both'),
)
user_type = models.CharField(max_length=2, choices=USER_TYPE_CHOICES, default=RecruiterAgency)
company = models.CharField(max_length=200, null=True, blank=True)
bio = models.TextField(null=True, blank=True)
accepted_tos = models.BooleanField(default=False)
profile_photo = models.ImageField(null=True, blank=True, upload_to="avatar")
def __str__(self):
return "%s's profile" % self.user.email
class Prospect(models.Model):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True, blank=True, related_name="profile_prospects")
RestrictedCompany = models.ForeignKey(RestrictedCompany, on_delete=models.CASCADE, null=True, blank=True, related_name="company_prospects")
badge = models.ManyToManyField(Badge, blank=True, related_name="badge_prospects")
certification = models.ManyToManyField(Certification, blank=True, related_name="certification_prospects")
LargestProject1 = 'lp1'
LargestProject2 = 'lp2'
LargestProject3 = 'lp3'
LargestProject4 = 'lp4'
LargestProject5 = 'lp5'
LARGEST_PROJECT_CHOICES = (
(LargestProject1, '$1-100,000'),
(LargestProject2, '$100,001-$500,000'),
(LargestProject3, '$500,001-$1,000,000'),
(LargestProject4, '$1,000,001-$5,000,000'),
(LargestProject5, '$5,000,001+'),
)
largest_project = models.CharField(max_length=3, choices=LARGEST_PROJECT_CHOICES, default=LargestProject1)
add_to_pool = models.BooleanField(default=False)
LargestTeam1 = 'lt1'
LargestTeam2 = 'lt2'
LargestTeam3 = 'lt3'
LargestTeam4 = 'lt4'
LargestTeam5 = 'lt5'
LargestTeam6 = 'lt6'
LARGEST_TEAM_CHOICES = (
(LargestTeam1, '0-5'),
(LargestTeam2, '6-10'),
(LargestTeam3, '11-20'),
(LargestTeam4, '21-50'),
(LargestTeam5, '51-100'),
(LargestTeam6, '100+'),
)
largest_team = models.CharField(max_length=3, choices=LARGEST_TEAM_CHOICES, default=LargestTeam1)
Contract = 'ct'
FullTimeEmployee = 'fe'
Both = 'bo'
Position_Type_CHOICES = (
(Contract, 'Contract'),
(FullTimeEmployee, 'Full-Time Employee'),
(Both, 'Both'),
)
position_type = models.CharField(max_length=2, choices=Position_Type_CHOICES, default=Contract)
resume = models.FileField(null=True, blank=True, upload_to="resume")
EntryLevel = 'el'
Junior = 'jn'
Professional = 'pr'
TIER_CHOICES = (
(EntryLevel, 'Entry-Level'),
(Junior, 'Junior'),
(Professional, 'Professional'),
)
tier = models.CharField(max_length=2, choices=TIER_CHOICES, default=EntryLevel)
billable_rate = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
annual_salary = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
total_years_exp = models.DecimalField(max_digits=4, decimal_places=2, null=True, blank=True)
def __str__(self):
return "%s" % self.profile.user.email
class Employer(models.Model):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True, blank=True, related_name="profile_employers")
title = models.CharField(max_length=200, null=True, blank=True)
street = models.CharField(max_length=200, null=True, blank=True)
city = models.CharField(max_length=200, null=True, blank=True)
zip = models.CharField(max_length=200, null=True, blank=True)
state = models.CharField(max_length=200, null=True, blank=True)
country = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return "%s" % self.profile.user.email
The comments were correct and very helpful! I needed to rename the "email" field on the RegisterForm to "username":
class RegisterForm(UserCreationForm):
username = forms.EmailField(label = "Email")
first_name = forms.CharField(label = "First name")
last_name = forms.CharField(label = "Last name")
class Meta:
model = User
fields = ("username", "first_name", "last_name")
def clean_email(self):
username = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError('Email already in use.')
return username
def save(self, commit=True):
user = super(RegisterForm, self).save(commit=False)
user.username = self.cleaned_data["email"]
if commit:
user.save()
return user
You have come across this issue where the UserCreationForm crashes if USERNAME_FIELD (in your case username) is not a form field.
The issue only affects Django 1.10, it doesn't affect earlier versions of Django. It will be fixed in the upcoming Django 1.10.1 release.
I have the following models that I need to create a form which allows for the updating of an existing Response (generated previously with a slug and then emailed to the respondent) and the creation of a Rating for each CV in CV.objects.all(). What's the easiest way to do this in Django. Currently I have a class-based UpdateView for Response and that's it.
class Response(models.Model):
first_name = models.CharField(max_length=200, null=True, blank=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
email = models.EmailField(max_length=254)
slug = models.SlugField(max_length=32)
submited = models.BooleanField(default=False)
submit_time = models.DateTimeField(null=True, blank=True)
creation_time = models.DateTimeField(auto_now_add=True)
class CV(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=content_file_name)
class Rating(models.Model):
cid = models.ForeignKey('CV')
rid = models.ForeignKey('Response')
score = models.IntegerField()
comment = models.TextField()
I eventually worked out how to do this. My code was as follows in case anyone is interested.
def add_response(request):
CVs = CV.objects.all()
if request.method == "POST":
ResForm = ResponseForm(request.POST, instance=Response())
RatForms = [RatingForm(request.POST, prefix=str(cv.id), instance=Rating(cid=cv)) for cv in CVs]
if ResForm.is_valid() and all([rf.is_valid() for rf in RatForms]):
new_response = ResForm.save(commit=False)
new_response.submit_time = datetime.now()
new_response.submited = True
new_response.save()
for rf in RatForms:
new_rating = rf.save(commit=False)
new_rating.rid = new_response
new_rating.save()
return HttpResponseRedirect('/thanks/')
else:
for i, _ in enumerate(RatForms):
RatForms[i].cv = CV.objects.filter(id=int(RatForms[i].prefix))[0]
print RatForms[i].cv
return render(request, 'response.html', {'response_form': ResForm, 'rating_forms': RatForms})
else:
ResForm = ResponseForm(instance=Response())
RatForms = [RatingForm(prefix=str(cv.id), instance=Rating(cid=cv)) for cv in CVs]
for i, _ in enumerate(RatForms):
RatForms[i].cv = CV.objects.filter(id=int(RatForms[i].prefix))[0]
print RatForms[i].cv
return render(request, 'response.html', {'response_form': ResForm, 'rating_forms': RatForms})