M
M
ma3xak2018-05-30 13:24:33
Django
ma3xak, 2018-05-30 13:24:33

How to pull the username?

Can't figure out how to get the username of the user who submitted the form
My Models

from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from profiles.managers import UserManager
from datetime import datetime
from django.conf import settings

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('Рабочая почта'), unique=True )
    first_name = models.CharField(_('Имя'), max_length = 50, blank = False, null = True, default= None)#Имя юзверя
    last_name = models.CharField(_('Фамилия'),  max_length= 50, blank = False, null = True, default= None)#Фамилия пользователя
    otec_name = models.CharField(_('Отчество'),  max_length=50, blank= False, null = True, default=None) #Отчёчтво юзверя
    brith_day = models.DateField(_('Дата рождения'),  auto_now=False, auto_now_add=False, blank= False, null = True, default=None) #Дата рождения
    location = models.CharField(_('Полный адрес'),  max_length=200, default=None, blank=False, null=True) #Полный адрес
    #pol = models.CharField(verbose_name = "Пол", max_length=10, default=None, blank= False, null = True)
    serial_passport = models.CharField(_('Серия паспорта'),max_length= 4,  blank= False, null = True, default=None) #Серия паспорта
    number_passport = models.CharField(_('Номер паспорта'),max_length= 6,  blank= False, null = True, default=None) #Номер паспорта
    date_passport= models.DateField(_('Дата выдачи'),  auto_now=False, auto_now_add=False, blank= False, null = True, default=None) #Дата выдачи
    puntk_passport = models.CharField(_('Пункт выдачи'), max_length = 200, default=None, blank= False, null = True) #Пункт выдачи
    is_avtive = models.BooleanField(_('Активация'), default = True)
    phone = models.CharField(_('Номер телефона'),  max_length = 11, unique = True, default = None, blank = False, null = True)
    is_staff = models.BooleanField(_('Статус персонала'), default = True)

    objects = UserManager()

    USERNAME_FIELD = 'phone'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = _('Пользователь')
        verbose_name_plural = _('Пользователи')

    def det_full_name(self):
        '''
        Это полное имя пользователя если я не ошибаюсь))
        '''
        full_name = '%s %s' % (self.first_name, self.last_name)
        return  full_name.strip()

    def deg_short_name(self):
        '''
        Вернём короткое имя пользователя
        '''
        return self.first_name

    def email_user(self, subject, message, from_email =  None, **kwargs):
        '''
        Что то делаем с мылом, так и не понял но в документации написано что надо
        ''' 
        send_mail(subject, message, from_email, [self.email], **kwargs)



class card(models.Model):
    user_card = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
    card_number = models.CharField(verbose_name = "Номер карты", max_length=20, blank= False, null = True, default=None)
    name = models.CharField(verbose_name = "Имя владельца", max_length=50, blank= False, null = True, default=None)
    srok = models.CharField(verbose_name = "Срок действия", max_length=5, blank= False, null = True, default=None)


class neww(models.Model):
    title = models.CharField(verbose_name = "Загаловок поста", max_length=200, blank= True, null = True, default=None)
    text = models.TextField(verbose_name = "Загаловок записи", blank= True, null = True, default=None)
    createda = models.DateField(verbose_name = "Дата создания", auto_now=False, auto_now_add=False, blank= True, null = True, default=None)

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return "/profile/news/%i/" % self.id


class user_zaim(models.Model):

    STATUS_CHOICES = (
        ('work','В обработке'),
        ('okey','Одобрена'),
        ('otcaz','Отказано'),
        )

    user_zaim  = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,  null=True, blank=True)
    date_zaim = models.DateTimeField(verbose_name="Дата займа",auto_now=False,auto_now_add=False, blank= True, null = True, default= None)
    date_success =  models.DateTimeField(verbose_name="Дата погашения", auto_now=False,auto_now_add=False,  blank= True, null = True, default=None)
    summa_zaim = models.CharField(verbose_name="Сумма займа", max_length = 5, blank=False, null=True, default=None)
    platej = models.CharField(verbose_name="Количесвто платежей", max_length=1, blank=False, null=True, default = None)
    status = models.CharField(verbose_name = "Стату заявки", max_length = 50, blank=False, null= True,choices= STATUS_CHOICES, default="В обработке")

    class Meta:
        verbose_name = "Заявка на займ"
        verbose_name_plural = "Зявки на получение займа"


class user_pay(models.Model):

    STATUS_CHOICES = (
        ('work','В обработке'),
        ('okey','Одобрена'),
        ('otcaz','Отказано'),
        )

    user_pay = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True, blank = True)#Связываемся с моделью пользователя
    created = models.DateTimeField(verbose_name = "Дата платежа", auto_now_add = True, auto_now = False)#Запоминаем время платежа
    summ_pay = models.CharField(verbose_name = "Сумма платежа", max_length = 5, blank=False, null=True, default=None)#Сумма платежа
    status = models.CharField(verbose_name = "Стату заявки", max_length = 50, blank=False, null= True,choices= STATUS_CHOICES, default="В обработке")#Вешаем статус платежа

    class Meta: 
        verbose_name ="Платеж пользователя"
        verbose_name_plural = "Платежи пользователей"

My views
from django.shortcuts import render, render_to_response
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django import forms
from profiles.models import User
from django.contrib import messages
from django.shortcuts import redirect
from django.contrib.auth import authenticate, login
from profiles.forms import neww, card, NewZaim
from django.views.generic import ListView, DetailView
from django.contrib import auth


def personal(request):
    return render(request, 'profiles/personal.html', locals())

def pay(request):
    return render(request, 'profiles/pay.html', locals())


@login_required
def newzaim(request):
    if request.method == 'POST':
        dolg = NewZaim(request.POST)
        if dolg.is_valid():
            messages.success(request, "Заявка принята в работу вы получите уведомление в SMS")
            dolg.save(request)
            user = ['user_zaim']
        else:
            messages.error(request, "Ошибка при офоромлении")
    else:
        dolg = NewZaim()
    return render(request,'profiles/newzaim.html', {'dolg':dolg})
    
def my(request):
    card_info = card.objects.all()
    if request.method == 'POST':
        card_pay = CardForm(request.POST)
        if card_pay.is_valid():
            card_pay.save(request, User)
            redirect('/profiles/my')
        else:
            messages.error(request, ('Ошибка при добавлении карты'))
    else:
        card_pay = CardForm()
    return render(request,'profiles/personal.html', {'card_pay':card_pay,
                                                     'card_info':card_info})

def docs(request):
    return render(request,'profiles/docs.html', locals())



class PostsListView(ListView): # представление в виде списка
    model = neww

class PostDetailView(DetailView): # детализированное представление модели
    model = neww

Forms to be sent are saved perfectly, but I still need to find out which User sent this request.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2018-05-30
@sim3x

request.user.first_name

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question