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
Related
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.
I have created a form for a Post. The form loads and when I enter all the value and try to submit the form, it gets refreshed but the database is not updated.
Here is my Post Model:
class Post(models.Model):
no_people = models.IntegerField()
no_days = models.IntegerField()
tour_date = models.CharField(max_length=200, blank=True)
Gender_types = (
('M', 'Male'),
('F', 'Female'),
('O', 'Others'),
)
Gender_prefer = models.CharField(max_length=1, choices=Gender_types)
location = models.CharField(max_length=200, blank=True)
pic_location = models.ImageField(blank=True, upload_to="posts/")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
detail = models.TextField()
liked = models.ManyToManyField(Yatru, blank=True, related_name= 'likes')
author = models.ForeignKey(Yatru, on_delete=models.CASCADE, related_name = 'posts',null=True)
def __str__(self):
return str(self.location)
def no_likes(self):
return self.liked.all().count()
class Meta:
ordering = ('-created',)
def save(self, *args, **kwargs):
self.location = self.location.upper()
return super(Post, self).save(*args, **kwargs)
LIKE_CHOICES = (
('Like', 'Like'),
('Unlike', 'Unlike'),
)
Here is the form.py:
from django import forms
from .models import Post
class PostModelForm(forms.ModelForm):
class Meta:
model = Post
fields = ('no_people','no_days','tour_date', 'Gender_prefer','location','detail')
Here is the views.py:
def post_add(request):
user = request.user
profile = Yatru.objects.get(user=user)
form = PostModelForm(request.POST or None, request.FILES or None, instance=profile)
if request.method == 'POST':
if form.is_valid():
newpost=form.save(commit=False)
newpost.user=request.user
newpost.save()
return render(request, 'posts/my_post.html',{'form': form})
This is the HTML file:
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button type='submit'>Submit </button>
</form>
Hi please follow instructions:
First insert "author" field in field tuple of model form
In your post_add view change below line
newpost.author=request.user
I am building a hospital management app and I am currently building the Nurse's webpage. In that webpage, I would like the following to display: a list of all employed nurses, a list of their workshifts, and what departments they work for.
I am trying to get the department section to display but I keep getting an error "too many values to unpack (expected 2)".
What can I do so that the nurses' department shows?
Models.py
from django.db import models
# Create your models here.
#Work Related aka Department and Work Shift
class Department(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class WorkShift(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
start_datetime = models.DateTimeField(null=True, blank=True)
end_datetime = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.name
#Personel Related aka Employees and Patients
class Doctor(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, null=True, blank=True, on_delete=models.CASCADE)
work_shift = models.OneToOneField(WorkShift, blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Nurse(models.Model):
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
sector = models.ForeignKey(Department, null=True, blank=True, on_delete=models.CASCADE)
reports_to = models.ForeignKey(Doctor, blank=True, null=True, on_delete=models.CASCADE)
work_shift = models.OneToOneField(WorkShift, default="", blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Patient(models.Model):
STATUS = (
('Sick', 'Sick'),
('Healing', 'Healing'),
('Cured', 'Cured'),
('Deceased', 'Deceased'),
)
name = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(blank=True, null=True)
status = models.CharField(max_length=200, null=True, blank=True, choices=STATUS)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
care = models.ForeignKey(Nurse, default="", blank=True, null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return self.name
from django.shortcuts import render, redirect
Views.py
# Create your views here.
from django.shortcuts import render
from .models import Doctor, Nurse, Patient, Department, WorkShift
from django.http import HttpResponse
from .forms import DoctorForm, NurseForm, PatientForm
# Create your views here.
def index(request):
patient = Patient.objects.all()
nurse = Nurse.objects.all()
doctor = Doctor.objects.all()
department = Department.objects.all()
total_patient = patient.count()
sick = patient.filter(status='Sick').count()
healing = patient.filter(status='Healing').count()
cured = patient.filter(status='Cured').count()
total_nurse = nurse.count()
# if request.method == 'POST':
# form =
context = {
'patient':patient, 'nurse':nurse,
'doctor':doctor, 'total_patient':total_patient,
'sick':sick, 'healing':healing, 'cured':cured,
'total_nurse':total_nurse,
'department':department
}
return render(request, 'lifesaver/index.html', context)
#All Patient Related
def patient(request):
patient = Patient.objects.all()
context = {'patient':patient}
return render(request, 'lifesaver/patient.html', context)
def patient_add(request):
patient = Patient.objects.all()
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
print("Patient Form is Valid")
form.save()
else:
print("Patient Form is Invalid")
print(form.errors)
return redirect('patient')
context = {'form':form,}
return render(request, 'lifesaver/patient_add.html', context)
def patient_update(request, pk):
patient = Patient.objects.get(id=pk)
form = PatientForm(instance=patient)
if request.method == 'POST':
form = PatientForm(request.POST, instance=patient)
if form.is_valid():
print('Update completed')
form.save()
return redirect('patient')
else:
print('Update not completed')
print(form.errors)
context = {'form':form}
return render(request, 'lifesaver/patient_update.html', context)
#All Doctor Related
def doctor(request):
doctor = Doctor.object.all()
context = {}
return render(request, 'lifesaver/doctor.html', context)
def doctor_add(request):
doctor = Doctor.object.all()
form = DoctorForm()
context = {'doctor':doctor, 'form':form}
return render(request, 'lifesaver/doctor')
def doctor_update(request):
doctor = Doctor.object.all()
form = DoctorForm()
context = {'doctor':doctor, 'form':form}
# Nurse Related
def nurse(request):
nurse = Nurse.objects.all()
workshift = WorkShift.objects.all()
department = Nurse.objects.get('sector')
context = {'nurse':nurse, 'workshift':workshift, 'department':department}
return render(request, 'lifesaver/nurse.html', context)
def nurse_add(request):
nurse = Nurse.objects.all()
form = NurseForm()
if request.method == 'POST':
form = NurseForm(request.POST)
if form.is_valid():
print("Nurse Form is Valid")
form.save()
else:
print("Nurse Form is Invalid")
print(form.errors)
return redirect('nurse')
context = {'form':form,}
return render(request, 'lifesaver/nurse_add.html', context)
def nurse_update(request):
nurse = Nurse.objects.all()
form = NurseForm()
context = {}
return render(request, 'lifesaver/nurse_update.html', context)
#Work Related
def department(request):
department = Department.objects.all()
context = {'department':department}
return render(request, 'lifesaver/department.html', context)
Forms.py
from django import forms
from django.forms import ModelForm
from .models import Doctor, Nurse, Patient, Department, WorkShift
from django.contrib.auth.forms import UserCreationForm
class DoctorForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Doctor',
'class': 'form-control'
}
))
department = forms.ModelChoiceField(queryset=Department.objects.all(), widget=forms.Select(attrs=
{
'class': 'selectpicker',
'placeholder': 'Department',
}
))
class Meta:
model = Doctor
fields = ['name', 'department']
class NurseForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Nurse',
'class': 'form-control'
}
))
class Meta:
model = Nurse
fields = ['name']
class PatientForm(ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Nurse',
'class': 'form-control'
}
))
description = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': "Describe the patient's symptoms",
'class': 'form-control'
}
))
department = forms.ModelChoiceField(queryset=Department.objects.all(), widget=forms.Select(attrs=
{
'class': 'selectpicker',
'placeholder': 'Select Department',
}
))
class Meta:
model = Patient
fields = ['name', 'description', 'department', 'care', 'status']
#Work Related
class WorkShiftForm(ModelForm):
class Meta:
model = WorkShift
fields = '__all__'
Nurse.html
{% extends 'lifesaver/main.html' %}
{% block content %}
{% for nurse in nurse %}
{{nurse.name}}
{{nurse.report_to}}
{{nurse.care}}
{{nurse.work_shift}}
{{department}}
{% endfor %}
{% endblock %}
In models.py, Nurse object has field 'sector' which is a Foreign Key to a Department record. So part of the problem is you're trying to output the wrong field name in your template as there is no actual department field defined on Nurse model.
Try these edits to views.py:
nurses = Nurse.objects.all()
then in your context: context = {..., 'nurses': nurses, ...}
Then in nurse.html:
{% for nurse in nurses: %}
...
{{ nurse.sector.name }}
{% endfor %}
That should at least get your nurse objects rendered in the template. But you have a potential issue in calling nurse.sector when that FK is defined in the Nurse model with null=True. So a better practice would be to define an accessor method in the Nurse model to check if sector is present before calling it's name, i.e.:
# in Nurse model
def department_name(self):
if self.sector_id:
return self.sector.name
else:
return '' # or some other default
Then you could edit nurse.html again replacing my code above with:
{% for nurse in nurses: %}
...
{{ nurse.department_name }}
{% endfor %}
This is just scratching the surface of how you could handle this but it hopefully answers your question and prevents a common error once you make these edits.
You'll also probably want to look into Django QuerySet API's select_related() and prefetch_related() methods to avoid N+1 query issues that are possible in your current code. See here and here for more background.
So for example, to avoid N+1, instead of calling nurses = Nurse.objects.all() instead do nurses = Nurse.objects.select_related('sector').all(). That will do a join to the Department model on the FK. This answer to one of the above N+1 questions has more details.
you need to pass a field and a value, e.g.
Nurse.objects.get('sector' = 'dentistry')
or if you want to display a specific nurses department you would use this in your template:
{{nurse.department.name}}
The general task: there is a list of the events which are displayed in a table view, the user clicks on the event and gets redirected to a single event page, which displays extra information about an event.
There is a button on this template that should give functionality to record some data of the event in the user-selected events list.
And I really don't get how to pass the event data into the form to create the user_event, maybe I chose the wrong way to create the instance of the model?
Models.py
class Event(models.Model):
LANGUAGE_CHOICES = [
('EN', 'English'), ('IT', 'Italian'), ('FR', 'French'), ('DE', 'German'), ('RU', 'Russian'), ]
STATUS_CHOICES = [('draft', 'Draft'), ('confirmed', 'Confirmed'), ]
FORMAT_CHOICES = [('live', 'Live'), ('online', 'Online'), ]
TOPIC_CHOICES = [('cataract', 'Cataract'),
('vitreo', 'Vitreoretinal'),
('optometry', 'Optometry'),
('multi', 'Multidisciplinary'),
('plastic', 'Plastic and Reconstructive surgery'),
('onco', 'Ocular oncology'),
('glaucoma', 'Glaucoma'),
('pediatrics', 'Pediatrics'), ]
title = models.CharField(
max_length=250, verbose_name='Event', db_index=True, default="Event")
slug = models.SlugField(max_length=250, unique_for_date='publish')
kol = models.ManyToManyField(
Kol, verbose_name='Presenter', db_index=True, blank=True)
body = models.TextField(verbose_name='Description', blank=True)
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
sponsor = models.CharField(
max_length=150, verbose_name='Sponsored by', default='')
organizer = models.CharField(
max_length=150, verbose_name='Organized by', default='')
topic = models.CharField(
max_length=100, choices=TOPIC_CHOICES, default='multi', verbose_name='Discipline')
status = models.CharField(
max_length=100, choices=STATUS_CHOICES, default='draft')
event_format = models.CharField(
max_length=50, choices=FORMAT_CHOICES, default='online', verbose_name='Format', db_index=True)
main_language = models.CharField(
max_length=50, choices=LANGUAGE_CHOICES, default='EN', verbose_name='Main language', db_index=True)
event_url = models.URLField(blank=True)
event_date_start = models.DateField(
verbose_name='Start date', db_index=True)
event_time_start = models.TimeField(default='09:00')
event_date_finish = models.DateField(
verbose_name='End date', auto_now=True)
event_time_finish = models.TimeField(default='18:00')
is_cme = models.BooleanField(
default=False, verbose_name='CME credits', db_index=True)
objects = models.Manager() # the default manager
published = PublishedManager() # published manager
futured = FutureManager() # future dates only
# follow check
users_follow = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name='events_liked', blank=True)
class Meta:
ordering = ('event_date_start',)
def __str__(self):
return self.title
def get_kols(self):
return "\n".join([str(p) for p in self.kol.all()])
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Event, self).save(*args, **kwargs)
#property
def _month(self):
return datetime.date(self.event_date_start).month
event_month = property(_month)
def get_absolute_url(self):
return reverse('events:event_detail', args=[self.publish.year,
self.publish.strftime(
'%m'),
self.publish.strftime(
'%d'),
self.slug])
class UserEvent(models.Model):
follower = models.ForeignKey(
User, related_name='user_events', on_delete=models.CASCADE)
my_event = models.ForeignKey(
Event, related_name='selected_event', on_delete=models.CASCADE)
title = models.CharField(
max_length=250, verbose_name='Event', db_index=True, default="Event")
event_url = models.URLField(blank=True)
event_date_start = models.DateField(
verbose_name='Start date')
event_date_finish = models.DateField(
verbose_name='End date')
class Meta:
ordering = ['-event_date_start']
def save(self, *args, **kwargs):
created = not self.pk
super().save(*args, **kwargs)
if created:
UserEvent.objects.create(user=self)
def __str__(self):
return self.title
forms.py
class UserEventForm(forms.ModelForm):
class Meta:
model = UserEvent
fields = ("title", "event_url",
"event_date_start", "event_date_finish")
detail.html with the button
{% extends 'bbase11.html' %} {% block title %} {{ event.title}} {% endblock %} {% block content %}
<div class="container">
<h1> {{ event.title }}</h1>
<p class='event_descr'> {{event.body}}</p>
<p> Presenting professionals {{event.get_kols}}</p>
<div>Organized by {{event.organizer}}</div>
<div>Sponsored by {{event.sponsor}}</div>
<div>
<form action= "{% url "events:add_event" %}" method = "POST" >
{{form.as_p}}
{% csrf_token %}
<input id='event' type='hidden' value = {{event.id}}>
<button type="submit" class="btn btn-outline-primary btn-sm m-0 waves-effect">Add to calendar</button></div>
</form>
</div>
{% endblock %}
views.py
def event_detail(request, year, month, day, event):
event = get_object_or_404(Event, slug=event,
status='confirmed',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request, 'events/event/detail.html', {'event': event, 'add_event': add_event})
#login_required
def add_event(request):
if request.method == 'POST':
form = UserEventForm(request.POST or None)
if form.is_valid():
form.save()
messages.success(request, ("Event has been added"))
return redirect('event_list')
else:
messages.error(request, ("Event has not been added"))
return redirect('events:event_list')
else:
events = Event.futured.all()
return render(request, 'list.html', {'events': events})
Using a class based view instead of your function based one, you can override the get_initial method as follows:
class AddEventCreateView(CreateView):
model = Event
form_class = UserEventForm
template_name = 'your/template.html'
def get_initial(self):
initial = super().get_initial()
# Add your initial values here - for example
initial['title'] = 'Some value'
return initial
def form_valid(self, form):
self.object = form.save(commit=False)
# Do something here
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy('your:url-name')
You can now pass as many initial values to your form as needed. See http://ccbv.co.uk/projects/Django/3.0/django.views.generic.edit/CreateView/#get_initial for details.
It looks like it may be a typo in the URL in the detail.html with the quotes.
Change this:
<form action= "{% url "events:add_event" %}" method = "POST" >
To this:
<form action="{% url 'events:add_event' %}" method="POST">
I have to send some data to my database where I have a phone object. For this I need to select the desired phone number and insert the desired information to the database.
A requirement is to display the phone numbers that belongs to the current login user.
I use Django model named Phone and a modelForm named phoneForm.
class Phone(models.Model):
user = models.ForeignKey(User)
phone_num = models.ForeignKey(Sim, null=True)
imei = models.CharField(max_length=30, primary_key=True)
num_calls = models.CharField(max_length=20, null=True, blank=True)
time_btwn_calls = models.CharField(max_length=20, null=True, blank=True)
psap = models.CharField(max_length=30, null=True, blank=True)
class Sim(models.Model):
phone_num = models.CharField(max_length=30, primary_key=True)
pin = models.CharField(max_length=15)
puk = models.CharField(max_length=15)
class phoneForm(ModelForm):
class Meta:
model = Phone
fields = ['phone_num', 'num_calls', 'time_btwn_calls', 'psap']
widgets = {'phone_num': Select(attrs={'class': 'form-control'}),
'num_calls': TextInput(attrs={'class': 'form-control'}),
'time_btwn_calls': TextInput(attrs={'class': 'form-control'}),
'psap': TextInput(attrs={'class': 'form-control'})
}
labels = {
'phone_num': ('Select phone number'),
'num_calls': ('Number of calls'),
'time_btwn_calls': ('Time between calls'),
'psap': ('PSAP'),
}
def __init__(self, *args, **kwargs):
super(phoneForm, self).__init__(*args, **kwargs)
self.queryset = Phone.objects.filter(user_id = request.user.id).values('phone_num')
How can I acces the database properly to filter the phone_num values that belongs to the current user and then set them in phone_num choices?
My template is:
<div class="row">
<div class="col-md-6 col-sm-offset-3">
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %} <!-- obligatorio para protegerse de ataques maliciosos -->
{{ form.as_p }} <!-- pasamos la variable form y con as_p conseguimos <p> -->
<button type="submit" class="btn btn-primary">Send to TCU</button>
</form>
</div>
And my view.py:
def phone_config(request):
phone = Phone.objects.get(phone_num=611111111)
if request.method == 'POST':
form = phoneForm(request, request.POST, instance=phone)
if form.is_valid():
form.save()
return redirect(reverse('gracias'))
else:
form = phoneForm(request, instance=tcu)
return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})
def gracias_view(request):
return render(request, 'heroconfigurer/gracias.html')
To modify the phone_num field in your form, you access self.fields['phone_num'] in your form's __init__ method.
class phoneForm(ModelForm):
class Meta:
model = Phone
...
def __init__(self, user, *args, **kwargs):
super(phoneForm, self).__init__(*args, **kwargs)
phone_nums = Phone.objects.filter(user=user).values_list('phone_num', flat=True)
self.fields['phone_num'].queryset = Sim.objects.filter(phone_num__in=phone_nums)
When you initialise the form in your view, you need to pass the user, e.g.
form = phoneForm(user, request.POST)
If that doesn't work, please explain why and show your Sim model.
Note a couple of other changes:
No need to use values()
If Sim.user is a foreign key, then you can simplify the filter to filter(user=request.user)
The user has been added to the form's __init__ method.