D
D
darkglare2020-11-18 16:11:58
Django
darkglare, 2020-11-18 16:11:58

How to autocomplete a form field?

How to make it so that when filling out the order form, the id of the currently authorized user is automatically entered in the "Nickname" field. Or his Login, but the LOGIN must match its id in the Database.
Now the form is displayed so that if the user wants to place an order, he is prompted to enter his ID, which is automatically created in the database during registration. Of course the user does not know it. You need to pass the id of the authorized user in the nickname field

models.py

from django.db import models
import django
from shop.models import Product
from django.contrib.auth.models import User

class Order(models.Model):
    nickname = models.ForeignKey(User, on_delete=models.CASCADE)
    email = models.EmailField()
    postal_code = models.CharField(max_length=20)
    city = models.CharField(max_length=100)
    street = models.CharField(max_length=100, default="s")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    paid = models.BooleanField(default=False)

    class Meta:
        ordering = ('-created',)
        verbose_name = 'Заказ'
        verbose_name_plural = 'Заказы'

    def __str__(self):
        return 'Order {}'.format(self.id)

    def get_total_cost(self):
        return sum(item.get_cost() for item in self.items.all())


class OrderItem(models.Model):
    
    order = models.ForeignKey(Order, related_name='items')
    product = models.ForeignKey(Product, related_name='order_items')
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.PositiveIntegerField(default=1)
    

    def __str__(self):
        return '{}'.format(self.id)

    def get_cost(self):
        return self.price * self.quantity


views.py

def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            
            order = form.save() 

            for item in cart:
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
            # очистка корзины
            cart.clear()
            return render(request, 'orders/order/created.html',
                          {'order': order})
    else:
        form = OrderCreateForm
        
    return render(request, 'orders/order/create.html',
                  {'cart': cart, 'form': form})


forms.py

from django import forms
from .models import Order
from django.contrib.auth.models import User


class OrderCreateForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ['nickname', 'email',  'postal_code', 'city', 'street',]
        widgets = {
            'nickname': forms.TextInput(attrs={"class": "form-control", "placeholder": "Имя"}),
            
            'email': forms.EmailInput(attrs={"class": "form-control", "placeholder": "e-mail"}),
            'postal_code': forms.TextInput(attrs={"class": "form-control", "placeholder": "Почтовый индекс"}),
            'city': forms.TextInput(attrs={"class": "form-control", "placeholder": "Город"}),
            'street': forms.TextInput(attrs={"class": "form-control", "placeholder": "Улица"}),

            }


admin.py

from django.contrib import admin
from .models import Order, OrderItem

class OrderItemInline(admin.TabularInline):
    model = OrderItem
    raw_id_fields = ['product']


class OrderAdmin(admin.ModelAdmin):
    list_display = ['id', 'nickname' ,'email',
                     'postal_code', 'city', 'paid',
                    'created', 'updated']
    list_filter = ['paid', 'created', 'updated']
    inlines = [OrderItemInline]

admin.site.register(Order, OrderAdmin)


html

<form action="." method="post" class="order-form">

 {{form.as_p}}

</form>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AlexandrBirukov, 2020-11-18
@AlexandrBirukov

https://docs.djangoproject.com/en/3.1/ref/forms/ap...

D
darkglare, 2020-11-18
@darkglare

Decision

class OrderCreateForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = [ 'email',  'postal_code', 'city', 'street',]
        widgets = {
             'email': forms.EmailInput(attrs={"class": "form-control", "placeholder": "e-mail"}),
            'postal_code': forms.TextInput(attrs={"class": "form-control", "placeholder": "Почтовый индекс"}),
            'city': forms.TextInput(attrs={"class": "form-control", "placeholder": "Город"}),
            'street': forms.TextInput(attrs={"class": "form-control", "placeholder": "Улица"}),
 
            }

def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            order.nickname = request.user
            order.save()
            for item in cart:
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
            # очистка корзины
            cart.clear()
            return render(request, 'orders/order/created.html',
                          {'order': order})
    else:
        form = OrderCreateForm
    return render(request, 'orders/order/create.html',
                  {'cart': cart, 'form': form})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question