Django: store variables in database and pass them between different modules - python

In my model I'm trying to calculate my user age and create for them an id code and I want this information to be saved in my database, but "age" and "id_code" fields are missing in my database. If I change the name of the function age and id variable are not computed at all.
**accounts.models**
class UserInformation(models.Model):
name = models.CharField(max_length=250)
lastname = models.CharField(max_length=250)
phone = models.CharField(max_length=250)
birthday = models.DateField()
age = models.CharField(max_length=2)
id = models.CharField(max_length=250)
def __str__(self):
self.name + '_' + self.lastname + '_' + str(self.birthday.year)
def age(self):
age = datetime.now().year - int(self.birthdate.year)
return age
def id_code(self):
id_code = self.name + '_' + self.lastname + '_' + int(self.birthday.year)
return id_code
**accounts.forms.py**
class UserInformationForm(forms.ModelForm):
class Meta:
model = UserInformation
fields = ('name', 'lastname', 'birthday', 'phone')
**accounts.views.py**
def add_information(request):
if request.method == 'POST':
form = UserInformationForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('home')
else:
form = UserInformationForm()
return render(request, 'add_information.html', {'form': form})
I've also an another models file in another app where I've two quiz for my user. I'd like to save in my database with answers also the id code created in the other models file and use the userinformation answer to create the string name to use in the database but it gives me error "'ImportError: cannot import name 'name' from 'accounts.models' " even if I've imported the modules:
**question.models.py**
from accounts.models import name
class QuestionOne(models.Model):
question_1a = models.CharField(max_length=250, choices=point)
question_2a = models.CharField(max_length=250, choices=point)
question_3a = models.CharField(max_length=250, choices=point)
id_code = models.CharField(max_length=250)
def __str__(self):
return self.name + '_question_1'
class QuestionTwo(models.Model):
question_1b = models.CharField(max_length=250, choices=point)
question_2b = models.CharField(max_length=250, choices=point)
question_3b = models.CharField(max_length=250, choices=point)
id_code = models.CharField(max_length=250)
def __str__(self):
return self.name + '_question_2'
**question.forms.py**
class QuestionOneForm(forms.ModelForm):
class Meta:
model = QuestionOne
fields = ('question_1a', 'question_2a', 'question_3a')
class QuestionTwoForm(forms.ModelForm):
class Meta:
model = QuestionOne
fields = ('question_1b', 'question_2b', 'question_3b')
Lasltly in my html I'd like to show how many question forms have been completed so I added the "quest__done" variable. Unfortunly is not working and in my page {{ quest_done }} is just a blank space
**question.views.py**
def question_one(request):
quest_done = 0
if request.method == 'POST':
form = QuestionOneForm(request.POST, request.FILES)
if form.is_valid():
quest_done += 1
form.instance.user = request.user
form.save()
return redirect('home')
else:
form = QuestionOneForm()
return render(request, 'quest.html', {'form': form, 'quest_done': quest_done})
def question_two(request):
quest_done = 0
if request.method == 'POST':
form = QuestionTwoForm(request.POST, request.FILES)
if form.is_valid():
quest_done += 1
form.instance.user = request.user
form.save()
return redirect('home')
else:
form = QuestionTwoForm()
return render(request, 'quest.html', {'form': form, 'quest_done': quest_done})
*html**
<div class="row">
<div class="col-sm-3">
<h6 class="mb-0">Question form completed:</h6>
</div>
<div class="col-sm-9 text-secondary">
{{ quest_done }} /2
</div>
</div>

Override save() method in model.
class UserInformation(models.Model):
name = models.CharField(max_length=250)
lastname = models.CharField(max_length=250)
phone = models.CharField(max_length=250)
birthday = models.DateField()
age = models.CharField(max_length=2,default="")
id = models.CharField(max_length=250,default="")
def save(self, *args, **kwargs):
if self.age ="":
self.age = datetime.now().year - int(self.birthdate.year)
self.save()
super(UserInformation, self).save(*args, **kwargs)
you can do same for id in save() method.

Related

OrderForm' object has no attribute 'get' via request.post

I've created an orderform and was trying to extract information from the form. However, each time when i called for forms.get("firstname") or anything, i will face the error that the object has no attribute 'get" even though it is a form. more specifically, the error is "AttributeError: 'OrderForm' object has no attribute 'get'"
Here is the relevant code:
in models.py:
class BaseModel(models.Model):
eid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
date_created = models.DateTimeField(auto_now_add=True, db_index=True)
class Meta: abstract = True
#classmethod
def get_or_none(cls, **kwargs):
try:
return cls.objects.get(**kwargs)
except cls.DoesNotExist:
return None
class Order(BaseModel):
itemname = models.CharField(max_length =100, default="")
firstname = models.CharField(max_length = 20)
lastname = models.CharField(max_length = 20)
email = models.EmailField()
phone = PhoneNumberField(null=False, blank=False)
comments = models.TextField()
delivery = models.BooleanField(default=False)
def __str__(self):
return str(self.eid)
in forms.py:
class OrderForm(forms.ModelForm):
itemname = forms.ModelMultipleChoiceField(queryset=Post.objects.filter(title__contains="Bae"), required=True)
class Meta:
model = Order
fields = ('itemname', 'firstname', 'lastname', 'email', 'phone','delivery', 'comments')
labels = {'itemname': 'Order Item', 'firstname': 'First Name', 'lastname':"Last Name", 'email':"Email", 'phone':"Phone Number", 'delivery':'Deliver?', 'comments':'Comments'}
in views.py. This is where the error occurs:
def order(request):
if request.method == "POST":
form = OrderForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
item_selected = form.get('itemname')
order.itemname = item_selected
order.save()
return render(request, 'Reddit_app/order_thankyou.html')
else:
form = OrderForm()
return render(request, 'Reddit_app/order_from_post.html', {"form": form})
finally, the order html code is :
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-primary">Submit</button>
</form>
item_selected = form.cleaned_data.get('itemname')
if you want to access data from form you need to access cleaned_data after the is_valid function is invoked

Django saving data in model through model form and foreign key

I have a model named Doctor and a model named Appoint which have doctor as a foreign key. and I have a model form to take input for the Appoint model but not for the foreign key in it. I am able to link the Doctor model through url but I am not able to save doctor(foreign key) in Appoint model.
here are the 2 models:-
``` class Doctor(models.Model):
docid = models.IntegerField(null=True, default=1001)
name = models.CharField(max_length=40)
phone = models.IntegerField()
add = models.TextField()
email = models.EmailField()
category = models.CharField(choices=doc_cat,max_length=20)
price = models.IntegerField()
def __str__(self):
return self.name
class Appoint(models.Model):
f_name = models.CharField(max_length=12)
l_name = models.CharField(max_length=12)
phone1 = models.IntegerField()
phone2 = models.IntegerField()
add = models.CharField(max_length=100)
city = models.CharField(max_length=20)
state = models.CharField(max_length=30)
pincode = models.IntegerField()
doctor = models.ForeignKey(Doctor,null=True, on_delete=models.CASCADE)
day = models.CharField(max_length=30)
timeslot = models.CharField(max_length=30)
symptom = models.CharField(max_length=200)
email = models.EmailField()
date = models.DateField(auto_now=True)
def __str__(self):
return self.f_name + self.l_name```
here is the view method:-
``` def takeappointment(request, docid):
doctor = Doctor.objects.get(docid = docid)
if request.method == 'POST':
form = Appointform(request.POST)
if form.is_valid():
form.save()
f_name = request.POST['f_name']
l_name = request.POST['l_name']
day = request.POST['day']
timeslot = request.POST['timeslot']
email = request.POST['email']
return render(request, 'submit.html', {
'f_name' : f_name,
'l_name' : l_name,
'day' : day,
'timeslot' : timeslot,
'email' : email,
})
form = Appointform()
return render(request, 'takeappointment.html', {'form': form, 'doctor': doctor})
```
how can save the foreign key from Doctor model along with form data in Appoint model?
you can do it this way:
add doctor parameter to your Appointform
class Appointform(forms.ModelForm):
class Meta:
model = Appoint
def __init__(self, *args, **kwargs):
self.from_doctor = kwargs.pop("from_doctor", None)
super().__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
cleaned_data["doctor"] = self.from_doctor
return cleaned_data
and in your takeappointment view add this parameter when create form
def takeappointment(request, docid):
doctor = Doctor.objects.get(docid = docid)
if request.method == 'POST':
form = Appointform(request.POST, from_doctor=doctor)
if form.is_valid():
form.save()
f_name = request.POST['f_name']
l_name = request.POST['l_name']
day = request.POST['day']
timeslot = request.POST['timeslot']
email = request.POST['email']
return render(request, 'submit.html', {
'f_name' : f_name,
'l_name' : l_name,
'day' : day,
'timeslot' : timeslot,
'email' : email,
})
form = Appointform(from_doctor=doctor)
return render(request, 'takeappointment.html', {'form': form, 'doctor': doctor})
you also need to change definition of Appoint model, add blank=True to your doctor field
doctor = models.ForeignKey(Doctor, null=True, blank=True, on_delete=models.CASCADE)
you can do it other way.
class Appointform(forms.ModelForm):
class Meta:
model = Appoint
exclude = ("doctor", )
def __init__(self, *args, **kwargs):
self.from_doctor = kwargs.pop("from_doctor", None)
super().__init__(*args, **kwargs)
def save(self, *args, **kwargs):
self.instance.doctor = self.from_doctor
return super().save(*args, **kwargs)

django modelform more then one foreign key using exclude

here user i want user and userprofile. useing exclude. when i add userprofile error 'WSGIRequest' object has no attribute 'userprofile'
modelform
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ('categories', 'title', 'description', 'image', 'price')
exclude = ('user','userprofile')
view
#login_required
def productpost(request):
form = ProductForm()
if request.method == "POST":
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.userprofile = request.userprofile
form.save()
return success(request)
else:
print("The Form Is Invalid")
return render(request, 'product/postproduct.html', {'form': form})
Model
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
userprofileinfo = models.ForeignKey(UserProfileInfo, on_delete=models.CASCADE)
categories = models.ForeignKey(Categories, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
description = models.TextField()
image = models.FileField()
price = models.IntegerField()
pub_date = models.DateTimeField('date published', auto_now_add=True)
def __str__(self):
return self.title
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

Django: getting access to related fields in other modles

I have the below
class Chore(models.Model):
title = models.CharField(max_length=300)
reward = models.PositiveIntegerField( default= 1)
def __str__(self):
return self.title
class Child(models.Model):
created_by = models.ForeignKey(User,on_delete=models.PROTECT, blank = True, null = True)
name = models.CharField(max_length=300)
age = models.DecimalField (max_digits=2, decimal_places=1, default=3.0, blank = True )
class ChildChore(models.Model):
child = models.ForeignKey(Child, on_delete=models.PROTECT)
chore = models.ForeignKey(Chore, on_delete=models.PROTECT)
points = models.PositiveIntegerField( default= 0, blank = True, null = True)
Form:
class ProgressForm(ModelForm):
class Meta:
model = ChildChore
exclude = ()
ProgressFormSet = modelformset_factory(ChildChore, form=ProgressForm, extra=0, can_delete=[False])
html page:
{{ formset.management_form }}
{% for form in formset %}
{{form.chore}} # will return the title
{{form.child}} # will return the child name
{{form.points}}
View:
def ProgressCreate(request, cid):
template_name = 'chore/progress_form.html'
if request.method == 'GET':
formset = ProgressFormSet(queryset=ChildChore.objects.filter(child=cid))
elif request.method == 'POST':
formset = ProgressFormSet(request.POST)
if formset.is_valid():
for form in formset:
# only save if name is points
if form.cleaned_data.get('points'):
form.save()
return redirect('children-list')
else:
print (formset.errors)
return render(request, 'chore/progress_form.html', {'formset': formset})
my question here is how to get the other models fields in the template? For example, I want the "reward" from Chore Model and I need the "age" form Child.
something like {{form.child.age}} will not work and creating a function in the child model to return the age didn't work as well.
I tried to make

Django- display manytomanyfield form in template and post to the base

People, please help me :)
I have 2 class :
In first we can sign to the edition - name, surname, phone, mail.
In second we can display form with number edition and users who sign to sth edition.
I want display only 'publish' number edition in template.
In page we can choice edition (drop-down list /multiple), write name etc and save to this edition..
I know I write awfully, but maybe U understand..
models:
class Signup(models.Model):
name = models.CharField(max_length=30, verbose_name='Imię',)
surname = models.CharField(max_length=30, verbose_name='Nazwisko', blank=True, null=True)
phone = models.CharField(max_length=20, verbose_name='Numer telefonu', blank=True, null=True)
mail = models.EmailField(verbose_name="Email", max_length=254, blank=True, null=True)
home = models.CharField(max_length=40, verbose_name='Miejsce zamieszkania', blank=True, null=True)
nr_edition = models.ManyToManyField('Edition', verbose_name='Edycja', blank=True, null=True,)
class Meta:
verbose_name = "Uczestnik"
verbose_name_plural = "Uczestnicy"
def __unicode__(self):
return u'%s %s' % (self.name, self.surname)
class PublishedEditManager(models.Manager):
def get_query_set(self):
return super(PublishedEditManager, self).get_query_set().filter(published=True)
class Edition(models.Model):
name_edit = models.CharField('Nazwa edycji', max_length=100)
slug = models.SlugField('Odnośnik', unique=True, max_length=100)
# new_user = formset_factory(ContactForm)
published = models.BooleanField('Opublikowany', blank=True)
objects = models.Manager()
published_edition = PublishedEditManager()
class Meta:
verbose_name = "Numer edycji"
verbose_name_plural = "Numery edycji"
def __unicode__(self):
return self.name_edit
def get_absolute_url(self):
return u'%s' % self.name_edit
forms
class ContactForm(forms.Form):
name = forms.CharField()
surname = forms.CharField()
phone = forms.CharField()
mail = forms.EmailField()
nr_edition = forms.ModelMultipleChoiceField
def is_valid(self):
vf = forms.Form.is_valid(self)
for f in self.errors:
self.fields[f].widget.attrs.update({'class': 'errorlist'})
return vf
def clean(self):
cleaned_data = super(ContactForm, self).clean()
return cleaned_data
ContactFormSet = formset_factory(ContactForm)
view
def about_alfa(request):
c = {}
c['about_alfa'] = True
c['request'] = request
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST, request.FILES) # A form bound to the POST data
ContactFormSet = formset_factory(ContactForm)
if form.is_valid(): # All validation rules pass
name = form.cleaned_data['name']
surname = form.cleaned_data['surname']
phone = form.cleaned_data['phone']
mail = form.cleaned_data['mail']
nr_edition = form.cleaned_data['nr_edycji']
id_model = Signup.objects.create(
name=name,
surname=surname,
phone=phone,
mail=mail,
nr_edycji=nr_edition
)
c['form'] = form
c['send']= True
# print sendimage
text = u'Imię: %s \n' \
u'Nazwisko: %s \n' \
u'Telefon: %s \n' \
u'Mail: %s \n' % (name, surname, phone, mail)
html = u'<p>Imię: <strong>%s</strong></p>' \
u'<p>Nazwisko: <strong>%s</strong></p>' \
u'<p>Telefon: <strong>%s</strong></p>' \
u'<p>Mail: <strong>%s</strong></p>' % (name, surname, phone, mail)
sendMailTemplate(['dp#asd.pl'], 'Nowa osoba zapisała się ne Alfe.', text, html, copy=False,
)
return render(request, 'about_alfa.html', c)
else:
c['form'] = form
return render(request, 'about_alfa.html', c)
else:
c['form'] = ContactForm()
return render_to_response('about_alfa.html', c, context_instance=RequestContext(request))
Edit
models
Nothing change
forms
I delete first part and this is result:
class ContactForm(forms.ModelForm):
class Meta:
model = Signup
nr_edition = forms.ModelMultipleChoiceField(queryset=Edition.objects.all())
def save(self):
signup = forms.ModelForm.save(self)
for edition in self.cleaned_data['nr_edition']:
signup.edition_set.add(edition)
def clean(self):
cleaned_data = super(ContactForm, self).clean()
return cleaned_data
ContactFormSet = formset_factory(ContactForm)
view
I delete almost all and :
def about_alfa(request):
c = {}
c['about_alfa'] = True
c['request'] = request
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST, request.FILES) # A form bound to the POST data
ContactFormSet = formset_factory(ContactForm)
if form.is_valid():
form.save()
return render_to_response('about_alfa.html', c, context_instance=RequestContext(request))
Edit 2
I have no errors but i dont see any field in template (only submit^^).. ?
Use ModelForm with ModelMultipleChoiceField:
class ContactForm(forms.ModelForm):
class Meta:
model = Signup
nr_edition = forms.ModelMultipleChoiceField(queryset=Edition.objects.all())
def save(self):
signup = forms.ModelForm.save(self)
for edition in self.cleaned_data['nr_edition']:
signup.edition_set.add(edition)
And in your view you just save the form:
if form.is_valid():
form.save()
and in template:
<form action="{% url "viewname" %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Edit:
To use formset with ModelForm, you must use modelformset_factory, see docs, not formset_factory
ContactFormSet = modelformset_factory(Signup, form=ContactForm)
Also, you are instantiating ContactForm, you must instead instantiate ContactFormSet with request.POST..
So the view will be like this:
def about_alfa(request):
c = {}
c['about_alfa'] = True
c['request'] = request
ContactFormSet = modelformset_factory(Signup, form=ContactForm)
if request.method == 'POST':
formset = ContactFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
else:
c['form'] = formset
else:
c['form'] = ContactFormSet()
return render_to_response('about_alfa.html', c, context_instance=RequestContext(request))

Categories

Resources