M
M
Maxim Zubenko2018-09-27 10:51:09
Django
Maxim Zubenko, 2018-09-27 10:51:09

Django: How to populate order form fields (First Name, Last Name, Phone) if user is already registered and logged in?

There is an order model (in models.py):

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,)
    first_name = models.CharField(max_length=50, verbose_name="Заказчик")
    last_name = models.CharField(max_length=50, blank=True)
    phone = models.CharField(max_length=20)
    address = models.CharField(max_length=255, blank=True)
    date = models.DateTimeField(auto_now_add=True, verbose_name="Дата заказа")
    delivery_type = models.CharField(max_length=40, choices=(('self','Самовывоз'),('delivery','Доставка')), default='self', verbose_name="Тип доставки")
    delivery_date = models.DateField(default=get_tomorrow())
    comments = models.TextField(blank=True)
    status = models.CharField(max_length=100, choices=ORDER_STATUS_CHOICES, default='accepted', verbose_name="Статус")
    total_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0.00, verbose_name="Итоговая стоимость")
    discount = models.DecimalField(max_digits=5, decimal_places=2, default=0.00)

    class Meta:
        verbose_name = "Заказ"
        verbose_name_plural = "Заказы"

    def __str__(self):
        return "Заказ #{0}".format(str(self.id))

As you can see, it uses users who are registered in the system. If the user is not registered, then he will not get to the checkout page.
There is a form (in forms.py):
class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ['first_name', 'last_name', 'phone', 'delivery_type', 'delivery_date', 'address', 'comments']
        labels = {
            'first_name': 'Имя *',
            'last_name': 'Фамилия',
            'phone': 'Контактный телефон *',
            'delivery_type': 'Способ получения',
            'delivery_date': 'Дата доставки',
            'address': 'Адрес доставки',
            'comments': 'Комментарии к заказу',
        }
        help_texts = {
            'phone': '* Пожалуйста, указывайте реальный номер телефона, по которому с Вами можно связаться',
            'address': '* Обязательно указывайте город!',
            'delivery_date': '! Доставка производится не раньше, чем на следущий день, после оформления заказа. Менеджер с Вами предварительно свяжется!',
        }
        widgets = {
            'delivery_date': forms.SelectDateWidget(),
        }

The form is generated automatically using the django-bootstrap3 extension and in the template the code looks like this:
<div class="col-xs-offset-1 col-xs-8">
<form method='POST' action='{% url "make_order" %}' class="form-horizontal"> {% csrf_token %}
    {% bootstrap_form form show_label=False layout='horizontal' %}
    {% bootstrap_button "Отправить заказ" icon="ok" button_type="submit" button_class="btn-success" extra_classes="pull-right" %}
</form>
</div>

And in the browser it’s like this:
5bac8a9f703d5003873267.png
if you select delivery (additional fields will open, I did it through Ajax), but you shouldn’t be distracted by this.
So it turns out that every time an already logged-in user has to Specify the first name, last name and phone number. But they are in the profile.

What should I add where (ideally to the forms.py file) so that these fields are filled in automatically?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question