I have a contact form/model in Django that isn't showing up on the admin management page.
I have no idea why it isn't showing up, I have tried to debug by running migrations, and also renaming some of the model variables.
models.py
from django.db import models
class Contact(models.Model):
their_name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
message = models.CharField(max_length=500)
def __str__(self):
return self.name
forms.py
from django import forms
class ContactForm(forms.Form):
their_name = forms.CharField(label='Name', max_length=100)
email = forms.EmailField(label='Email', max_length=100)
message = forms.CharField(label='Message', max_length=500, widget=forms.Textarea(attrs = {'id': 'Message_form'}))
admin.py
from django.contrib import admin
from .models import Contact
admin.register(Contact)
views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from .models import Contact
from .forms import ContactForm
...
def contact(request):
valid_input = 'no input'
if request.method == 'POST':
valid_input = 'invalid input'
TheForm = ContactForm(request.POST)
if TheForm.is_valid():
valid_input = 'valid input'
name = TheForm['name']
email = TheForm['email']
message = TheForm['message']
Contact.objects.create(name=name, email=email, message=message)
else:
TheForm = ContactForm()
return render(request, 'BlogHome/pages/contact.html', {'TheForm': TheForm, 'valid_input': valid_input})
Could this be the way I am importing the model? I have no idea what is causing this problem.
In your admin.py create an admin class for your Contact model and after register this model in admin using that class.
class ContactAdmin(admin.ModelAdmin):
list_display = ('id', 'their_name', 'email', 'message')
admin.site.register(Contact, ContactAdmin)
Related
Hi im trying to add a DOB field to my django project but I keep getting this error but i cant find where to find it
File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\urls.py", line 2, in <module>
from . import views
File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\views.py", line 13, in <module>
from .forms import CreateUserForm
File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\forms.py", line 9, in <module>
class CreateUserForm(UserCreationForm):
File "C:\Users\Ugur\Anaconda3\envs\ECS639U\lib\site-packages\django\forms\models.py", line 276, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (dateofbirth) specified for User
My Forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'dateofbirth']
My views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
# Create your views here.
from .models import *
from .forms import CreateUserForm
def registerPage(request):
if request.user.is_authenticated:
return redirect('/home')
else:
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + user)
return redirect('/login')
context = {'form':form}
return render(request, 'accounts/register.html', context)
def loginPage(request):
if request.user.is_authenticated:
return redirect('/home')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/home')
else:
messages.info(request, 'Username OR password is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
def logoutUser(request):
logout(request)
return redirect('/login')
#login_required(login_url='/login')
def home(request):
context = {}
return render(request, 'accounts/dashboard.html', context)
My models.py
from django.db import models
# Create your models here.
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
dateofbirth= models.CharField(max_length=200, null=True)
creditcard = models.CharField(max_length=16, null = True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
The console I cant understand where the issue is located to change to add the label onto the register area any help is fully thank have a good afternoon :)
In your forms, you specified a field for Modal = User, but your Class called Customer. When you say modal = User Django tries to use own User Modal which does not have dateofbirth field.
I need to register a user and use it's email as Username. I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register on the page. I AM NEW TO DJANGO AND PYTHON
My Code is
forms.py File
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from phonenumber_field.formfields import PhoneNumberField
from django.db import transaction
from .models import User
class UserRegistrationForm(UserCreationForm):
name = forms.CharField(max_length=60)
# Username = forms.CharField(max_length=15)
email = forms.EmailField()
class Meta(UserCreationForm.Meta):
models = User
fields = ['name','email','password1','password2']
views.py file
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from .forms import UserRegistrationForm
from django.contrib.auth import get_user_model
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
User = form.save()
else:
form = UserRegistrationForm()
return render(request, 'users/signup.html', {'form': form})
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""docstring for User"""
email = models.EmailField(verbose_name='Email Address', unique=True)
name = models.CharField(max_length=50)
USERNAME_FIELD = 'email'
user_permissions = None
groups = None
REQUIRED_FIELDS = []
def __str__():
return self.name
I´m making my own portfolio and I wanna be able to see the messages that people sent me in the admin page but I don't seem to be able to make it so when someone submits the message it saves in the model and "broadcasts" in the admin page.
Models.py
from django.db import models
# Create your models here.
class Messages(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=50)
website = models.CharField(max_length=50)
text = models.CharField(max_length=500)
Forms.py
from django import forms
from django.core import validators
from django.forms import ModelForm
from .models import Messages
class Messages(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'name'}), required=True, label='', max_length=100)
email = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'email'}), required=True, label='', max_length=50)
website = forms.CharField(widget=forms.TextInput(attrs={'class' : 'website'}),required=False, label='', max_length=50)
text = forms.CharField(widget=forms.TextInput(attrs={'class' : 'text'}), required=True, label='', max_length=500)
bot = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)])
class Meta():
model = Messages
fields = '__all__'
Views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Template, Context
from . import forms
# Create your views here.
def index(request):
return render(request, 'index.html')
def portfolio(request):
return render(request, 'portfolio.html')
def certificate(request):
return render(request, 'certificate.html')
def contact(request):
form = forms.Messages()
if request.method == 'post':
form = form.Messages(request.post)
if form.is_valid():
form.save(commit=True)
return thankyou(request)
else:
print('CONTACT ERROR')
return render(request, 'contact.html', {'form':form})
def thankyou(request):
return render(request, 'thankyou.html')
Admin.py
from django.contrib import admin
from toni.models import Messages
# Register your models here.
admin.site.register(Messages)
Python is case sensitive. The request.method will always be uppercase, and the post data is stored in request.POST. Change the code to:
if request.method == 'POST':
form = forms.Messages(request.POST)
You can debug problems like this by adding more print() lines. For example, you could have added print("in the post") after if request.method == 'post':. Then when you saw that the line was never printed, you could have added print(request.method). Hopefully you would then spot the mismatch between 'post' and 'POST'.
The use case is that a logged in use, can call up their profile into a form, edit it and it gets updated in the database.
With the code below the correct Profile data can be viewed. It can also be called up into an editable form. The form allows the data to be edited , but when it is submitted, the database is NOT updated and the original profile is displayed.
I’ve tried everything, including console print statements so I know that it is getting to the POST portion of the code, is a valid form and doing the initial save().
Any insights would be appreciated (I am using Django 1.11). I do not want to start a rabbit running but the only thing I have not tried is breakink the OneToOne relationship with User and using a foriegnkey because I want the profile entry creaed when the user registers.
Notes:
When I popped this in for testing purposes: save_data.user = request.user
I get the error: Exception Value:'User' object has no attribute 'cleaned_data'`from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100, default='')
city = models.CharField(max_length=100, default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
balance = models.FloatField(default=0)
bank = models.FloatField(default=0)
image = models.ImageField(upload_to='profile_image', blank=True)
def __str__(self):
return self.user.username
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
Forms.py
from django import forms
from django.contrib.auth.models import User
from .models import UserProfile
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('description', 'city', 'phone', 'balance', 'bank', 'website', 'image')
Views.py
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.contrib.auth import login, authenticate, update_session_auth_hash
from django.contrib.auth.forms import (
UserCreationForm,
UserChangeForm,
PasswordChangeForm
)
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from core.forms import ( EditAccountForm, SignUpForm,
ProfileForm
)
from core.models import UserProfile
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
def edit_profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user)
if form.is_valid():
save_data = form.save()
save_data.user = request.user
print(save_data)
save_data.save()
return redirect(reverse('core:profile'))
else:
udata = UserProfile.objects.get(user=request.user)
form = ProfileForm(instance=udata)
args = {'form': form}
return render(request, 'core/test.html', args)
urls.py
from django.conf.urls import url
from django.contrib import admin
#from playme.core import views as core_views
from core import views as core_views
from django.contrib.auth import views as auth_views
# SET THE NAMESPACE!
app_name = 'core'
urlpatterns = [
url(r'^$', core_views.index, name='index'),
url(r'signup/$', core_views.signup, name='signup'),
url(r'^account/$', core_views.account, name='account'),
url(r'^profile/$', core_views.view_profile, name='profile'),
url(r'^login/$', auth_views.login, {'template_name': 'core/login.html'}, name='user_login'),
url(r'^logout/$', auth_views.logout, {'next_page': '/play/'}, name='logout'),
url(r'^edit_account/$', core_views.edit_account, name='edit_account'),
url(r'^edit_profile/$', core_views.edit_profile, name='edit_profile'),
url(r'^change_password/$', core_views.change_password, name='change_password'),
]
The URL I am hitting is:
http://127.0.0.1:8000/play/profile/
Which then goes to :
http://127.0.0.1:8000/play/edit_profile/
The form loads up but when submitted goes back to:
http://127.0.0.1:8000/play/profile/
With no database update.
I'm surprised this doesn't give an error.
When you instantiate the form on a GET, you correctly pass the UserProfile object as the instance parameter - this is correct because the form has that as its model. But when you instantiate on POST, you incorrectly pass the User object - request.user. You should pass the profile, as you do in the other branch.
Note, in both cases you can get the profile more simply by just doing request.user.userprofile.
Well the form being invalid situation isn't being handled here at all. Your code should look like this
def edit_profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user)
if form.is_valid():
save_data = form.save(commit=False)
save_data.user = request.user
save_data.save()
return redirect(reverse('core:profile'))
else:
udata = UserProfile.objects.get(user=request.user)
form = ProfileForm(instance=udata)
args = {'form': form}
return render(request, 'core/test.html', args)
Note the change in indentation.
Could someone smart explain me please where I have a bug?
I get this error when I would like to send a profile user form
NOT NULL constraint failed: userprofile_userprofile.godzina_id
I have an app "userprofile"
forms.py
from django import forms
from models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('imie', 'godzina')
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from forms import UserProfileForm
from django.contrib.auth.decorators import login_required
from django.conf import settings
#login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render(request, 'user_profile.html', args)
models.py:
from django.db import models
from django.contrib.auth.models import User
from godzina.models import Godzina
class UserProfile(models.Model):
user = models.OneToOneField(User)
imie = models.CharField(max_length=150)
godzina = models.ForeignKey('godzina.Godzina')
User.profile = property(lambda u:UserProfile.objects.get_or_create(user=u)[0])
You could add null=True to your godzina attribute:
godzina = models.ForeignKey('godzina.Godzina', null=True)