Home python outstretched their values ​​ForeignKey field to ModelForm Django

outstretched their values ​​ForeignKey field to ModelForm Django

Author

Date

Category

Faced with the problem of the output values ​​of chelovekoponyatnyh ForeignKey through the form ModelForm. ForeignKey displayed in the form as Dzhango pulls them from the Order table model, such as “Car object (3) ” (in Order stores a reference to the record Car table) / “Client object (4 ) “(in the Order holds a reference to the record Client table), and for convenience it would be nice to see chelovekoponyatnye value names of these objects, which are taken from the corresponding Car / Client model.

In Django model models.py look like this:

class Client (models.Model):
  firstname = models.CharField (max_length = 200, null = False)
  lasttname = models.CharField (max_length = 200, null = False)
  dob = models.DateField
  address = models.CharField (max_length = 200)
  phone = models.BigIntegerField
  email = models.EmailField
  class Meta:
    db_table = 'clients'
    # Ordering = [ "lastname"]
class Car (models.Model):
   YEAR_CHOICES = []
   for r in range (1980, (datetime.now () year + 1).):
      YEAR_CHOICES.append ((r, r))
  maker = models.CharField (max_length = 50)
  model = models.CharField (max_length = 50)
  year = models.IntegerField (
    ( 'Year'), choices = YEAR_CHOICES, default = datetime.now (). Year)
  vin = models.CharField (max_length = 17)
  owner = models.ForeignKey (Client, on_delete = models.PROTECT)
  class Meta:
    db_table = 'cars'
class Order (models.Model):
  car = models.ForeignKey (Car, on_delete = models.PROTECT)
  customer = models.ForeignKey (Client, on_delete = models.PROTECT)
  note = models.CharField (max_length = 250)
  class Meta:
    db_table = 'orders'

Part of the views.py , which is responsible for the work of the form looks like this:

def index (request):
  full_order_list = Order.objects.all ()
  full_car_list = Car.objects.values ​​()
  full_clients_list = Client.objects.values ​​()
  if request.method == 'POST':
    form = AddNewOrderForm (request.POST)
    if form.is_valid ():
      new_order = form.save ()
  ELSE:
    form = AddNewOrderForm
  template = loader.get_template ( 'index.html')
  context = {
    'Full_order_list': full_order_list,
    'Full_car_list': full_car_list,
    'Full_clients_list': full_clients_list,
    'Form': form
  }
  return render (request, 'index.html', context)

A index.html Paste form looks classically:

& lt; form action = "" method = 'post' & gt;
    {% Csrf_token%}
    & Lt; table & gt;
    {{Form.as_table}}
    & lt; / Table & gt;
    & Lt; input type = 'submit' value = 'submit' & gt;
& lt; / form & gt;

The most important part – forms.py . Here are some points that need to be clarified. I tried to make a crutch to the user prints the value of the adjacent tables Car and Client (see 2 lines commented after the class AddNewOrderForm (forms.ModelForm):. and the row in triple apostrophes in the end, it took from the public. tutorials on the forms.Form and it does not work for the forms.ModelForm it turned out beautifully, but the system was not working, an error that to add a new record, you must Car object / Cliete object, rather than abstract id as int.

clientsOptions = []
carsOptions = []
templist = []
full_clients_list = Client.objects.values ​​()
for client in full_clients_list:
  templist.append (client [ "id"])
  templist.append (str (client [ "firstname"] + "" + client [ "lasttname"]))
  clientsOptions.append (templist)
  templist = []
full_car_list = Car.objects.values ​​()
for car in full_car_list:
  templist.append (car [ "id"])
  templist.append (str (car [ "maker"] + "" + car [ "model"]))
  carsOptions.append (templist)
  templist = []
class AddNewOrderForm (forms.ModelForm):
  #car = forms.ChoiceField (choices = carsOptions, required = True) 
#Customer = Forms.choiceField (Choices = ClientsOptions, Required = True)
  Class Meta:
    Model = order
    Fields = '__all__'
    widgets = {
      'Car': Forms.Select (attrs = {'class': 'Table Table-SM', 'Size': '3'}),
      'Customer': Forms.Select (ATTRS = {'Class': 'Table Table-SM', 'Size': '3'}),
      'Note': Forms.Textarea (attrs = {'size': '60', 'Placeholder': 'What happened?'})
    }
'' '
  car = Forms.ChoiceField (
    widget = Forms.select (attrs = {'class': 'Table Table-SM', 'Size': '3'}),
 Choices = CarsOptions, Required = True)
  Customer = Forms.choiceField (
    widget = Forms.select (attrs = {'class': 'Table Table-SM', 'Size': '3'}),
 Choices = ClientsOptions, Required = True)
  Notes = Forms.charfield (Widget = Forms.Textarea (
    attrs = {'size': '60', 'PLACEHOLDER': 'What happened?'}))
'' '

What we have at the moment:

  1. form works – adds entries to the Order Table with ForeignKey
  2. but it looks like this:
  3. And it should look like this and at the same time – work:

Answer 1, Authority 100%

In order to get the understandable names of objects when displaying in admin and other places, you need to add __ STR __ () :

class client (models.model):
  FirstName = Models.charfield (max_length = 200, null = false)
  LasttName = Models.Charfield (max_length = 200, null = false)
  # The rest of the fields
  DEF __STR __ (SELF):
    # Here we return a string with the name and surname
    Return '{0} {1}'. Format (Self.FirstName, Self.LastTname)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions