How to edit following Django Moellform - django

new to django. I am building a form for user to save to the database. the save to database part is working. However, I want to be able to view and edit the data on two separate template. let's call them view_self_eval.html and edit_self_eval.html. I am stuck.
following is my code for Models.py, Forms.py and View.py for the particular form
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.forms import ModelForm
class self_eval(models.Model):
Owner = models.OneToOneField(User, on_delete=models.CASCADE, default=None)
First_Name = models.CharField(max_length=100, default=None)
Last_Name = models.CharField(max_length=100, default=None)
Current_Role = models.CharField(max_length=100)
My_Strengths = models.CharField(max_length=1000)
Improvement = models.CharField(max_length=4000)
Goals = models.CharField(max_length=4000)
Profesional_Certification = models.CharField(max_length=4000)
Important_discussion = models.CharField(max_length=4000)
def __str__(self):
return self.Owner.username
def create_self_eval(sender, **kwargs):
if kwargs['created']:
self_eval = self_eval.objects.create(user=kwargs['instance'])
post_save.connect(create_self_eval, sender=User)
Forms.Py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from accounts.models import self_eval
class SelfEvalForm(forms.ModelForm):
class Meta:
model = self_eval
fields=(
'First_Name',
'Last_Name',
'Current_Role',
'My_Strengths',
'Improvement',
'Goals',
'Profesional_Certification',
'Important_discussion'
)
def save(self, commit=True):
self_eval = super(SelfEvalForm, self).save(commit=False)
self_eval.First_Name = self.cleaned_data['First_Name']
self_eval.Last_Name = self.cleaned_data['Last_Name']
self_eval.Current_Role = self.cleaned_data['Current_Role']
self_eval.My_Strengths = self.cleaned_data['My_Strengths']
self_eval.Improvement = self.cleaned_data['Improvement']
self_eval.Goals = self.cleaned_data['Goals']
self_eval.Profesional_Certification = self.cleaned_data['Profesional_Certification']
self_eval.Important_discussion = self.cleaned_data['Important_discussion']
if commit:
self_eval.save()
return self_eval
Views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from accounts.forms import (
RegistrationForm,
EditProfileForm,
SelfEvalForm,
EditSelfEvalForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from .models import self_eval
from django.views.generic import UpdateView
def self_eval(request):
if request.method == 'POST':
form = SelfEvalForm(request.POST)
if form.is_valid():
#save form data to DB
instance = form.save(commit=False)
instance.Owner=request.user
instance.save()
return redirect(reverse('accounts:self_eval'))
else:
form = SelfEvalForm()
args = {'form': form}
return render(request, 'accounts/self_eval_form.html', args)
def edit_self_eval(request, Owner_id):
self_eval = get_object_or_404(self_eval, pk=Owner_id)
if request.method == 'POST':
form = SelfEvalForm(request.POST, instance=Current_Role, Owner=request.user)
if form.is_valid():
self_eval = form.save()
else:
form = SelfEvalForm(intance=self_eval, Owner=request.user)
args = {'form':form,
'Current_Role':Current_Role
}
return render(request, 'accounts/edit_self_eval.html', args)

Related

Trying to make a form with 2 inputs

I have two different forms in my register page as the one to one relationship in one of the model will show a drop down box therefore I am using the second models field where the user will have to input the field.
How would I make it so when the forms are valid, the 'SNI' will save to the first form and not the second.
Model
from asyncio import FastChildWatcher
import email
from pyexpat import model
from xxlimited import Null
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class userCouncil(BaseUserManager):
def create_user(self, userID, password=None):
if not email:
raise ValueError("Email is required")
user = self.model(userID = self.normalize_email(userID))
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, userID, password):
user = self.model(userID = self.normalize_email(userID))
user.set_password(password)
user.is_staff = True
user.is_admin = True
user.save(using=self._db)
return user
class sni(models.Model):
SNI = models.CharField(max_length=256, primary_key=True)
Used = models.IntegerField(null=True, blank=True)
password = None
USERNAME_FIELD = 'SNI'
def __str__(self):
return self.SNI
class Account(AbstractBaseUser):
userID = models.EmailField(primary_key= True ,max_length=256, unique=True)
name = models.CharField(max_length=100)
dateOfBirth = models.DateField(max_length=8, null=True)
homeAddress = models.CharField(max_length=100, null=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True)
USERNAME_FIELD = 'userID'
objects = userCouncil()
def __str__(self):
return self.userID
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
Forms
import email
from pprint import isreadable
from pyexpat import model
from statistics import mode
from tabnanny import check
from xxlimited import Null
from attr import field
from django.forms import ModelForm, forms, widgets
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from matplotlib import use
from matplotlib.style import context
from .models import Account, sni
class createUserForm(UserCreationForm):
class Meta:
model = Account
fields = ['userID','name','dateOfBirth','homeAddress','password1','password2', 'sni']
def clean_userID(self):
userID = self.cleaned_data['userID'].lower()
u = self.cleaned_data['userID']
check_existing = Account.objects.filter(userID=userID).exists()
if check_existing:
raise forms.ValidationError("The following userID already exists: " + u)
else:
return userID
class SNIForm(UserCreationForm):
class Meta:
model = sni
fields = ['SNI', 'Used']
class AccountAuthenticationForm(forms.ModelForm):
password = forms.CharField(label = "password", widget = forms.PasswordInput)
class Meta:
model = Account
fields = ('userID', 'password')
Views
from django.shortcuts import redirect, render
from django.http import HttpResponse
from matplotlib import use
from matplotlib.pyplot import get
from matplotlib.style import context
from werkzeug import Request
from .models import *
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login as dj_login
from django.forms import ModelForm, forms
from django.contrib.auth.decorators import login_required
from .forms import AccountAuthenticationForm, SNIForm, createUserForm
def login(request):
context = {}
if request.method == 'POST':
username = request.POST.get('username').lower()
password = request.POST.get('password')
user = authenticate(request, userID = username, password = password)
form = AccountAuthenticationForm(request.GET)
if user is not None:
dj_login(request, user)
return redirect('dashboardPage')
else:
messages.info(request, "userID or password is incorrect")
return render(request, 'base.html', context)
def registerPage(request):
form = createUserForm()
form2 = SNIForm()
if request.method == 'POST':
form = createUserForm(request.POST)
form2 = SNIForm(request.POST)
if form.is_valid() and form2.is_valid:
print(form2['SNI'].value)
form.save()
form2.save()
userID = form.cleaned_data.get('userID')
messages.success(request, "Account created for: " + userID)
return redirect('loginPage')
context = {'form' : form, 'form2' : form2}
return render(request, 'register.html', context)
#login_required(login_url='loginPage')
def dashboardPage(request):
context = {}
return render(request, 'dashboard.html', context)
In views please refer to the registerPage function. Thank you
What the first form can take is Sni_id.
There is no sni_id without first saving an sni instance.
What you can do is...
Save both forms
f=form.save()
f2=form2.save()
f2.instance.user = f.instance.id
UPDATE:
if form2.is_valid():
sni = form2.data["sni"]
used = form2.data["used"]
if SNI.objects.filter(sni=sni, used=used).exists()
f=form.save()

Django question on assigning the created news/team to the user who created it

please help me with one question, if possible.
I have a profile model that has a OneToOneField to User and there is a team field in the Profile model, there is also a Team model with a name, tag, etc. I would like to ask how to make the user who creates the team immediately be in it, so that the team field of the Profile model is assigned this team automatically, so that he is its creator and captain immediately. Maybe someone can help, explain, throw a banal example for understanding.
The creation was done like this, in a separate application. But I don't understand how to give the browser the created tim.
models.py
from django.db import models
from django.contrib.auth.models import User
from slugify import slugify
from django.urls import reverse
class BaseModel(models.Model):
objects = models.Manager()
class Meta:
abstract = True
class Profile(BaseModel):
user = models.OneToOneField(
User, on_delete=models.CASCADE, null=True, blank=True
)
nickname = models.CharField(max_length=30, unique=True, null=True)
team = models.ForeignKey('Team', on_delete=models.SET_NULL, blank=True, null=True)
def save(self, *args, **kwargs):
super(self.__class__, self).save(*args, **kwargs)
if self._state.adding is True:
Profile.objects.create()
def __str__(self):
return self.nickname
class Meta:
verbose_name = "Автор"
verbose_name_plural = "Авторы"
class Team(BaseModel):
name = models.CharField('Название', max_length=50)
tag = models.CharField('Тег', max_length=16, unique=True)
slug = models.SlugField(unique=True, blank=True, null=True)
def __str__(self):
return f'{self.name} [{self.tag}]'
def get_absolute_url(self):
return reverse("team_detail", kwargs={"slug": self.slug})
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Team, self).save(*args, **kwargs)
class Meta:
verbose_name = "Команда"
verbose_name_plural = "Команды"
forms.py
from django import forms
from django.contrib.auth.models import User
from django.forms import TextInput, Textarea, FileInput, IntegerField
from django.forms import TextInput, Textarea, FileInput, Select
from .models import *
class CreateTeamForm(forms.ModelForm):
class Meta:
model = Team
fields = {
'name', 'tag', 'slug'
}
views.py
from django.conf import settings
from django.contrib.auth import authenticate, login, get_user_model
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render, redirect, resolve_url
from django.utils.http import url_has_allowed_host_and_scheme
from django.views.generic.base import View
from django.views.generic import DetailView, ListView
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.views.decorators.csrf import csrf_exempt
from .models import *
from .forms import *
# Create your views here.
class CreateTeam(View):
def get(self, request):
form = CreateTeamForm(request.POST)
context = {'form': form}
return render(request, 'team/home.html', context)
def post(self, request):
if request.method == 'POST':
form = CreateTeamForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
return redirect('home')
I'm just learning django, so it's hard to implement everything at once, and I'll be happy to help.
NEW CODE
forms.py
class JoinTeamForm(forms.ModelForm):
key = forms.CharField(label='key', max_length=20)
class Meta:
model = Team
fields = {'key'}
I tried without key = forms.CharField(label='key', max_length=20), but in html {{ form.key }} didn't work.
views.py
class JoinTeam(LoginRequiredMixin, View):
def get(self, request, pk):
print(f'post:{request.POST}, get:{request.GET}')
form = JoinTeamForm(request.POST or None)
team = Team.objects.get(id=pk)
context = {'form': form,
'team': team
}
return render(request, 'team/team_detail.html', context)
def post(self, request, pk):
print(f'post: {request.POST} team_id: {Team.objects.get(id=pk).key}')
profile = request.user.profile
error_msg = 'Неверный код'
if request.method == 'POST':
form = JoinTeamForm(request.POST)
role = Role.objects.get(id=2)
team = Team.objects.get(id=pk)
if form.is_valid():
key = form.save()
if key == team.key:
profile.team = team
profile.role = role
profile.save()
return redirect(team.get_absolute_url())
else:
return HttpResponse(error_msg)
return redirect(team.get_absolute_url())
Could you edit your view to update the user's profile after the team is created?
class CreateTeam(View):
def get(self, request):
form = CreateTeamForm(request.POST)
context = {'form': form}
return render(request, 'team/home.html', context)
def post(self, request):
profile = request.user.profile
if request.method == 'POST':
form = CreateTeamForm(request.POST)
if form.is_valid():
team = form.save()
profile.team = team
profile.save()
return redirect('home')
return redirect('home')
Please note, the way you have this set up is that each profile can only be on one team. If that's your intent, great, but if not you may want to set up a many to many model here so a user can be associated with multiple teams.

adding country and cities django

i want to add country and cities in forms currently i'm using django-countries for country but i'm gettings this error:
django.core.exceptions.FieldError: Unknown field(s) (country) specified for CustomUser
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from bootstrap_datepicker_plus import DatePickerInput
from tempus_dominus.widgets import DatePicker
from .models import CustomUser
from django_countries.fields import CountryField
class RegistrationForm(UserCreationForm):
CHOICES = (
(0, 'celebrities'),
(1, 'singer'),
(2, 'comedian'),
(3, 'dancer'),
(4, 'model'),
(5, 'Photographer')
)
Mobile_Number = forms.CharField(label='Mobile Number', widget= forms.NumberInput)
Artist_Category = forms.ChoiceField(choices=CHOICES)
bio = forms.CharField(widget=forms.Textarea,label = 'something about yourself')
portfolio = forms.URLField(label = 'enter your portfolio')
country = CountryField(blank_label = '(select_country)')
# country = forms.co
class Meta:
model = CustomUser
fields = ('email','password','Mobile_Number','Artist_Category','portfolio','country','bio',)
models.py: custome user model
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=100, unique=True)
name = models.CharField(max_length=100)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
last_login=models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD='email'
REQUIRED_FIELDS=[]
objects=UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
view.py:
from django.shortcuts import render, redirect
from main_site.models import artist
from django.urls import reverse_lazy
from .forms import BookartistForm, ContactForm
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.core.mail import EmailMultiAlternatives,EmailMessage
from django.template import loader
from .forms import RegistrationForm
from django.contrib.auth import login, authenticate
from django.http import HttpResponseRedirect
register view
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user= form.save()
raw_password = form.cleaned_data.get('password1')
# user = authenticate(request, email=user.email, password=raw_password)
# if user is not None:
# login(request, user)
# else:
# print('user is not authenticated')
return redirect('login')
else:
form = RegistrationForm()
return render(request, 'main_site/register.html', {'form':form})
...........................................................................................................................

How to setup registration and signals in django 2.0

Can someone help me figure out what i am doing wrong trying to setup authentication and signals to work along with the models created in django 2.0.
models.py
from django.db import models
from django.conf import settings.AUTH_USER_MODEL
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
bio = models.TextField(foo)
location = models.CharField(foo)
# Override save method
# Run after the method is saved to add signal functionality below
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
else:
instance.profile.save()
forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.forms import ModelForm
from .models import Profile
Profile = get_user_model()
class UserRegisterForm(forms.ModelForm):
email = forms.EmailField(foo)
first_name = forms.CharField(foo)
last_name = forms.CharField(foo)
password = forms.CharField(foo)
password2 = forms.CharField(foo)
class Meta:
model = Profile
fields = [
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
]
views.py
from django.shortcuts import render, redirect
from django.contrib.auth import get_user_model
from .forms import UserRegisterForm
from .models import Profile
from django.conf import settings
def register(request):
next = request.GET.get('next')
form = UserRegisterForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
password = form.cleaned_data.get('password')
user.set_password(password)
user.save()
new_user = authenticate(username=user.username, password=password)
login(request, new_user)
if next:
return redirect(next)
return redirect('accounts:login')
context = {
'form': form,
}
return render(request, "accounts/register.html", context)
Foo = just a placeholder
The code above create the user but not the profile associated to it.
Any help would be much appreciated.

Exception Value:NOT NULL constraint failed: auth_user.username

I am creating a project to register and view profile using Django.
The problem is when I am trying to register a new user I am getting some errors
NOT NULL constraint failed: auth_user.username
Here is my form.py and view.py file:
form.py
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
class FileDataForm(forms.Form):
name = forms.CharField(max_length=50)
file = forms.FileField()
image = forms.ImageField()
class userregister(UserCreationForm):
first_name = forms.CharField(max_length=50, required = False ,help_text ='optional')
last_name = forms.CharField(max_length=50, required = False ,help_text ='optional')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'password1', 'password2', )
class editprofileform(UserChangeForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email','password')
View.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render,redirect,render_to_response
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View
from .models import FileData
from .forms import FileDataForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .forms import userregister,editprofileform
from django.contrib.auth.forms import UserChangeForm , PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
# Create your views here.
#login_required
def home(request):
return HttpResponse('<h1>Welcome to your first page<h1>')
def registration(request):
print request
print 'request'
if request.method == 'POST':
#save the user data
form = userregister(request.POST)
print form.errors
print 'here'
if form.is_valid():
print 'i am here'
form.save()
return render(request , 'registration/success.html' ,{'form' : form,} )
else:
form = userregister()
return render(request , 'registration/register.html' ,{'form' : form,} )
else:
form = userregister()
return render(request , 'registration/register.html' , {'form': form,})
models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length = 100,default='')
city = models.CharField(max_length =30)
mobile = models.IntegerField(default=0)
def create_profile(sender , **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user = kwargs['instance'])
post_save.connect(create_profile , sender=User)
error:
Exception Value:
NOT NULL constraint failed: auth_user.username
In your form.py file, try inserting 'username' as the first element in the 'fields' list. It looks like you're not using that in the form so when you submit, it's leaving the username null.