S
S
Stanislav Konovalov2019-03-08 12:46:00
Django
Stanislav Konovalov, 2019-03-08 12:46:00

Django. How to bind a user to a model and implement adding, editing and deleting data through forms?

Hello. I am building a website for a real estate agency. I need it to be a closed system, i.e. without registration, the admin will add certain realtors (users) and that's it. It is also necessary for the realtor to be able to add his ad, edit, delete it on the site.
Such a question:
1) How to create the Ads table correctly so that it is tied to the user, i.e. so that, when adding an ad, the realtor does not select a user from the drop-down list, if this was done through ForeignKey, but in some other way, so that the ad is automatically linked to the user;
2) How then to create the form correctly so that you can perform CRUD operations.
I did a video lesson, but, of course, I didn’t understand a lot of it.
Here is my model at the moment:

from django.db import models
from datetime import datetime
from django.contrib.auth.models import User

class Listing(models.Model):
  realtor = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Риэлтор')
  realtor_photo = models.ImageField(blank=True, upload_to='photos/%Y/%m/%d/', verbose_name='Фото риэлтора')
  region = models.CharField(default="Чуйская", max_length=100, verbose_name='Область')
  city = models.CharField(default="Бишкек", max_length=100, verbose_name='Город')
  district = models.CharField(max_length=100, verbose_name='Район')
  title = models.CharField(max_length=200, verbose_name='Заголовок')
  address = models.CharField(max_length=200, verbose_name='Адрес')
  description = models.TextField(blank=True, verbose_name='Описание')	
  stage = models.IntegerField(verbose_name='Этаж')
  rooms = models.IntegerField(verbose_name='Количество комнат')	
  garage = models.IntegerField(default=0, verbose_name='Гараж')
  sqmt = models.IntegerField(verbose_name='Площадь')
  price = models.IntegerField(verbose_name='Цена')
  photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Основное фото')
  photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 1')
  photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 2')
  photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 3')
  photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 4')
  photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 5')
  photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 6')
  is_published = models.BooleanField(default=True, verbose_name='Публично')
  list_date = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата публикации')

  def __str__(self):
    return self.title

  class Meta:
    verbose_name = 'Объявление'
    verbose_name_plural = 'Объявления'

Here is the forms.py file
from django import forms
from .models import Listing

class ListingForm(forms.ModelForm):

    class Meta:
        model = Listing
        fields = ('realtor', 'realtor_photo', 'region', 'city', 'district', 'title', 'address',
        	'description', 'stage', 'rooms', 'garage', 'sqmt', 'price', 'photo_main', 'photo_1',
        	'photo_1', 'photo_2', 'photo_3', 'photo_4','photo_5',)

Here is the idea, I know that nothing will be saved in the database yet, because I don’t know how to do it yet, I tried it in different ways, but it didn’t work out yet.
def listing_add(request):
    form = ListingForm()   
    return render(request, 'listings/listing_add.html', {'form': form})

The input is done like this:
{% extends 'base.html' %}

{% block title %} | Вход {% endblock %}

{% block content %}
<section id="login" class="bg-light py-5">
    <div class="container">
      <div class="row">
        <div class="col-md-6 mx-auto">
          <div class="card">
            <div class="card-header bg-primary text-white">
              <h4>
                <i class="fas fa-sign-in-alt"></i> Войти</h4>
            </div>
            <div class="card-body">
              <!-- Alerts -->
              {% include 'partials/_alerts.html' %}
              <form action="{% url 'login' %}" method="POST">
              	{% csrf_token %}
                  <div class="form-group">
                    <label for="username">Имя пользователя</label>
                    <input type="text" name="username" class="form-control" required>
                  </div>
                  <div class="form-group">
                    <label for="password2">Пароль</label>
                    <input type="password" name="password" class="form-control" required>
                  </div>
                <input type="submit" value="Войти" class="btn btn-secondary btn-block">
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
{% endblock %}

Presentation function:
def login(request):
  if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']

    user = auth.authenticate(username=username, password=password)

    if user is not None:
      auth.login(request, user)
      messages.success(request, 'Вы вошли в систему')
      return redirect('dashboard')
    else:
      messages.error(request, 'Введены неверные данные')
      return redirect('login')
  else:
    return render(request, 'accounts/login.html')

Thanks in advance ;)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-03-08
@stas_workout

Remove the realtor from the form, and in view, after validating the form, save it like this and then the listing will have the current user who creates this entry as a realtor

listing = form.save(commit=False)
listing.realtor = request.user
listing.save()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question