Django email address not showing in admin - django

I'm trying to create a simple email and name collector , everything looks fine but I can only see the name option in the admin site the email option is not there
admin page model
Here is my code
Forms.py
from django import forms
from sonus import models
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label="Your Name",max_length=20)
your_email = forms.EmailField(label="Email",max_length=100)
Here Goes my Views.py
def get_name(request):
person = Person()
if request.method=="POST":
form = NameForm(request.POST)
if form.is_valid():
person.name = form.cleaned_data['your_name']
person.email = form.cleaned_data['your_email']
person.save()
return HttpResponseRedirect(reverse('index'))
else:
form = NameForm()
return render(request,'form.html',{ 'form': form })
My Admin.py
from django.contrib import admin
from django.contrib.admin.decorators import display
from django.contrib.auth.admin import UserAdmin
from .models import Details, Person,list
from sonus import models
# Register your models here.
admin.site.register(Person)
Here is the model
class Person(models.Model):
name = TextField(max_length=20)
email = EmailField(max_length=100)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('person',kwargs={'pk': self.pk})

In your admin.py change your code to that :
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'email',)
admin.site.register(Person, PersonAdmin)

Related

Cannot assign "<User: someuser>": "UserProfileInfo.user" must be a "User" instance

[enter image description here][1]I don't know what is causing this error but i couldn't find any solution for this. i checked everything and everything seems to be fine but i don't know why this error is occuring.
Views.py
from django.contrib.auth import get_user_model
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView,FormView
from . import forms
# Create your views here.
def signup(request):
if request.method =='POST':
user_create_form = forms.UserCreateForm(data=request.POST)
user_profile_form = forms.UserProfileInfoForm(data=request.POST)
if user_create_form.is_valid() and user_profile_form.is_valid():
user = user_create_form.save()
user.save()
profile = user_profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
else:
print(user_create_form.errors,user_profile_form.errors)
else:
user_create_form = forms.UserCreateForm()
user_profile_form = forms.UserProfileInfoForm()
return render(request,'accounts/signup.html',{'user_create_form':user_create_form,
'user_profile_form':user_profile_form})
Models.py
from django.db import models
from django.contrib import auth
# Create your models here.
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "#{}".format(self.username)
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
Contact_number = models.IntegerField(blank=True)
joined_at = models.DateTimeField(auto_now=True)
profile_pic = models.ImageField(upload_to='profiles',blank=True)
def __str__(self):
return self.user.username + ' Profile'
Forms.py
from django.contrib.auth import get_user_model # this gets the model that is in the application
from django import forms
from django.contrib.auth.forms import UserCreationForm
from . import models
class UserCreateForm(UserCreationForm):
class Meta():
fields = ('username','email','password1','password2',)
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name' # to set up a custom label for the field
self.fields['email'].label = "Email Address"
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = models.UserProfileInfo
fields = ('Contact_number','profile_pic')
I am getting this error no matter what i do, i tried referencing other similar questions but couldn't find any solution for this error. pls help me out on this one.
Thanks in Advance !
image of the error
[1]: https://i.stack.imgur.com/HOcmf.png
You can overwrite save() method in your model to return a model instance after saving an object, for example:
class YourModel(models.Model):
name = models.CharField(max_length=20)
def save(self, *args, **kwargs):
super(YourModel, self).save(*args, **kwargs)
return self
your_model_saved_instance = YourModel(name='example').save()
Then you will receive an instance from the user class instead of the form class
user = user.save()

ValueError at /profile/ ModelForm has no model class specified. Error django

Iam coding in django and trying to figure how to update profile of a user in my app
Please help me Iam trying to learn how to code and this is a big barrier for me to learn
here's models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
image = models.ImageField(default='default.jpg',upload_to="profile_pics")
def __str__(self):
return f'{self.user.username} Profile'
here's my views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get("username")
messages.success(request, f'Yor account has been created! You are now able to login')
return redirect('/login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html',{'form': form})
#login_required
def profile(request):
u_form = UserUpdateForm(instance = request.user)
p_form = ProfileUpdateForm(instance= request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context)
Iam getting error at 'u_form':u_form,
and This is my forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email','password1','password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username','email']
class ProfileUpdateForm(forms.ModelForm):
model = Profile
field = ['image']
Iam getting my error at this
p_form = ProfileUpdateForm()
In the ProfileUpdateForm you defined the model class name without the Meta class
Model name and fields should be defined inside the Meta class like this:
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']

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.

How to validate the email field of UserCreationForm using the built-in EmailValidator in Django?

Right now, if I enter invalid data into my UserCreationForm and submit it, the page reloads but doesn't show any error. I would like the EmailValidator validator in Django to show the error. I have tried adding the validators attribute to the email field, but it didn't do anything.
Here are my views:
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render
from django.urls import reverse
from .models import CustomUserCreationForm
# Create your views here.
def register(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('index'))
elif request.method == 'GET':
form = CustomUserCreationForm()
elif request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
context = {
'user': request.user,
}
return HttpResponseRedirect(reverse('index'), context)
else:
return HttpResponseRedirect(reverse('register'))
else:
return HttpResponse("Project 3: TODO")
context = {
'form': form,
}
return render(request, 'registration/signup.html', context)
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('login'))
And here are my models:
from django.contrib.auth.models import AbstractUser, AbstractBaseUser
from django import forms
from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import EmailValidator
# Create your models here.
# Customer class.
class CustomUser(User):
REQUIRED_FIELDS = ['email', 'first_name', 'last_name']
# Create user registration form class.
class CustomUserCreationForm(UserCreationForm):
first_name = forms.CharField(required=True, max_length=150, help_text='Required.')
last_name = forms.CharField(required=True, max_length=150, help_text='Required.')
email = forms.CharField(required=True, max_length=150, help_text='Required.', validators=[EmailValidator], error_messages={'invalid': 'This does not look like an email address.'})
class Meta:
model = User
fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)
# TODO: show an error message when email is incorrectly formatted.
# TODO: make email field unique and show an error message when it was already used.
Use built in EmailField of Django in CustomUserCreationForm
email = forms.EmailField(...)
See this too (validation of email) (form.clean), read this for showing errors of individual form fields

Django send data to Database: NOT NULL constraint failed: sms_post.author_id

I am new to django, I migrated my models, the database is working fine, i can see the data that I added by the manage.py shell. But I cant add Data from my webApp. When I wrote text on the fields and press the submit button it gave me this error NOT NULL constraint failed: sms_post.author_id
Thanks for helping..
models.py files
from django.db import models
from django.contrib.auth.models import User
THE_GENDER = [
("Monsieur", "Monsieur"),
("Madame", "Madame")
]
class Post(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
gender = models.CharField(max_length=8, choices=THE_GENDER)
number = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
forms.py files
from django import forms
from .models import Post
from crispy_forms.helper import FormHelper
class post_form(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(post_form, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
class Meta:
model = Post
fields = ["name", "email", "gender", "number"]
views.py files
from django.shortcuts import render
from django.http import HttpResponse
from .forms import post_form
from django.contrib.auth.decorators import login_required
#login_required
def home(request):
form = post_form(request.POST or None)
if form.is_valid():
form.save()
context = {
"form": form
}
return render(request, "sms/home.html", context)
You did not set the author of the instance in your for to a User object. You can do this with:
from django.shortcuts import redirect
#login_required
def home(request):
if request.method == 'POST':
form = post_form(request.POST)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect('name-of-view')
else:
form = post_form()
context = {
'form': form
}
return render(request, 'sms/home.html', context)
In order to implement the Post/Redirect/Get pattern [wiki], in case of a successful POST request, you should make a redirect, for example to the same view. You thus can here replace 'name-of-view' with the name of a view to redirect to.