I'm creating a simple To Do app using Django 3.2, and I have stuck in a error which is: FieldError: Cannot resolve keyword 'user' into field. Choices are: content, created, email, id, name, user1, user1_id
This is models.py:
from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.fields import CharField
from django.contrib.auth.models import User
# Create your models here.
class User(models.Model):
content = models.CharField(max_length=200, null=True)
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
user1 = models.ForeignKey(User, on_delete=CASCADE)
def __str__(self):
return self.content
forms.py
from django import forms
from django.forms import ModelForm, fields
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', 'first_name', 'last_name', 'email', 'password1', 'password2']
views.py
from django.shortcuts import render, redirect
from django.http.response import HttpResponse
from django.utils import timezone
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from demo.forms import CreateUserForm
from .models import *
from .models import __str__
# Create your views here.
#login_required(login_url='/login')
def home(request):
user = request.user
all_items = User.objects.filter(user=user).order_by("created")
context = {'all_items': all_items}
return render(request, 'html/home.html', context)
#login_required(login_url='/login')
def add_content(request):
current_date = timezone.now()
newItem = User(content=request.POST.get('content'))
newItem.save()
return redirect('/')
#login_required(login_url='/login')
def login_user(request):
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('/')
return render(request, 'html/login.html')
def logoutUser(request):
logout(request)
return redirect('login/')
def register_user(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
user = authenticate(request, username=user.username, password=request.POST.get('password1'))
if user is not None:
login(request, user)
return redirect('/')
context = {'form':form}
return render(request, 'html/register.html', context)
home.html
<div>
<form class="felx" action="add_content/" method="POST">
{% csrf_token %}
<input class="form-control me-2" type="text" name="content" placeholder="Hey">
<button id="add-btn" class="button" type="submit">Add</button>
</form>
<table>
<thead>
{% for all_item in all_items %}
<tr>
<td>{{ all_item.content }}</td>
</tr>
{% endfor %}
</thead>
</table>
Logout
{% if request.user.is_authenticated %}
<p>Hello {{request.user}}</p>
{% endif %}
</div>
By far, any data that is added can be access by every account, but what i'm trying to do is that each user has his own data or tasks in this case.
Would appreciate any idea!
Thanks
i think your problem is here
#login_required(login_url='/login')
def home(request):
user = request.user.pk
all_items = User.objects.filter(user1_id=user).order_by("created") #new
context = {'all_items': all_items}
return render(request, 'html/home.html', context)
#login_required(login_url='/login')
def add_content(request):
current_date = timezone.now()
newItem = User(content=request.POST.get('content'),user1_id=request.user.pk)
newItem.save()
return redirect('/')
Advice:Please try to change the User in models.py to an other name because Django has by default a model called User.
Related
I have two models defined, a Test model and a User model. The Test model relates to the User model
with a ForeignKey. The Test model has many different aspects to it, so I have truncated it, but I make a form of it with ModelForm. Then I call the form, and indeed all the entries show up, including a cell for User, however it shows no options or pre-selection for current user. What am I doing wrong?
#User as rendered in form in browser:
<select name="researcher" id="id_researcher">
<option value="" selected>---------</option>
models.py
from django.db import models
from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser)
class User(AbstractBaseUser):
is_active = models.BooleanField(default=True)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = "%s %s" % (self.first_name, self.last_name)
return full_name.strip()
#property
def is_staff(self):
"Is the user a member of staff?"
return self.staff
#property
def is_admin(self):
"Is the user a admin member?"
return self.admin
class Test(models.Model):
researcher = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="researcher")
views.py
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from database.forms import TestForm
from database.models import User, Test
# Create your views here.
def index(request):
return render(request, "database/index.html")
def test(request):
#If request is post, throw in data, check if valid, if correct, save it
if request.method == "POST":
form=TestForm(request.POST)
print(form)
if form.is_valid():
form.save()
context={"form": form}
return render(request, "database/test.html", context)
test.html:
{% extends "database/layout.html" %}
{% block body %}
<form action="" method="post">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
{% endblock %}
forms.py:
from django.forms import ModelForm
from database.models import Test
class TestForm(ModelForm):
class Meta:
model = Test
fields='__all__'
I am creating an e-commerce website where people can choose to login or not but still the can order and checkout (even if you are an AnonymousUser or Guest user). Now, I am making a login and register form in my website. The login form works and looks good but the register form wasn't working and throwing an error that said "RelatedObjectDoesNotExist at / User has no customer."
I think the reason is that when I register, it only makes a User in database but didn't register anything in the Customer table (which consists Name and Email). How can I register a Customer and User at the same time when I hit the "Submit" button? And how can I make that specific User have "Staff status" only and cannot make changes in the Admin site?
Also, I want to add new fields in the Register form for Name and Email that will go directly to the Customer table. I tried to do this one but it doesn't work and throwed and error that says "django.core.exceptions.FieldError: Unknown field(s) (name) specified for User".
Here's what I did:
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import *
class CustomUserCreationForm(UserCreationForm):
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
class Meta:
model = User
fields = ['username', 'name', 'email', 'password1', 'password2']
SUMMARY:
I want to add extra fields in the Register form called Name and Email. Then after clicking the Register form, I want create User and Customer at the same time. But the User should only have "Staff status" and cannot make changes in the Admin site. And the Name and Email field should go to Customer Table with the User I've created.
Here's the screenshot of my Register form:
Here's my forms.py file:
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'password1', 'password2']
def __init__(self, *args, **kwargs):
super(CustomUserCreationForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Enter Username'})
self.fields['password1'].widget.attrs.update({'class':'form-control','placeholder':'Enter Password'})
self.fields['password2'].widget.attrs.update({'class':'form-control','placeholder':'Confirm Password'})
Here's my views.py file:
def loginUser(request):
page = 'login'
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
print('USER:', user)
if user is not None:
login(request, user)
return redirect('/')
return render(request, 'store/login_register.html', {'page': page})
def logoutUser(request):
logout(request)
return redirect('/')
def registerUser(request):
page = 'register'
form = CustomUserCreationForm()
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
user = authenticate(request, username=user.username, password=request.POST['password1'])
if user is not None:
login(request, user)
return redirect('/')
context = {'form': form, 'page': page}
return render(request, 'store/login_register.html', context)
Here's my models.py file:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
def __str__(self):
return self.name
Here's my register.html file:
<form class="form" method="POST">
{% csrf_token %}
<h2> REGISTER </h2>
<h4> Create your account now! </h4>
<br />
{% for field in form %}
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">{{field.label}}:</label>
{{field}}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
<br />
<p> Already have an account? Login here </p>
</form>
Like the title says, I'm trying to create a social media app and my users can upload text to their websites. Currently I'm working on adding Image functionality. I can easily add this images in the Django admin page, but whenever I try to do it from the User's create post form, nothing shows up. Here's my post create form:
{% extends "social/base.html" %}
{% load crispy_forms_tags %}
{% block content4 %}
<h1>Make Your Post</h1>
<p>Write a post / Share an image</p>
<br>
<div class="container">
<form method="post">
{% csrf_token %}
{{form|crispy}}
<button type="submit" name="button">Make Post</button>
</form>
</div>
{% endblock content4 %}
Here's my views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Posts
from django.contrib.auth.forms import AuthenticationForm
from .forms import NewUserForm
from django.contrib import messages
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView
from django.contrib.auth.decorators import login_required
# Create your views here.
def home(request):
context = {
'posts' : Posts.objects.all()
}
return render(request, 'social/social.html', context)
def register(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, f"New Account Created: {username}")
login(request, user)
return redirect ("/social")
else:
for msg in form.error_messages:
print(form.error_messages[msg])
messages.error(request, f"{msg}: {form.error_messages[msg]}")
return render(request, 'social/register.html', {"form" : form})
form = NewUserForm
return render(request, 'social/register.html', {"form" : form})
def logout_request(request):
logout(request)
messages.info(request, "Logged out successfully!")
return redirect('/social')
def login_request(request):
if request.method == 'POST':
form = AuthenticationForm(request, data = request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username = username, password = password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect ('/social')
else:
messages.error(request, "Invalid username and/or password.")
else:
messages.error(request, "Invalid username and/or password.")
form = AuthenticationForm()
return render(request, 'social/login.html', {'form' : form})
class PostCreateView(CreateView):
model = Posts
fields = ['post_title', 'post_text_content', 'post_image']
def form_valid(self, form):
form.instance.post_author = self.request.user
print(self.request.user)
return super().form_valid(form)
my model:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class Posts(models.Model):
post_title = models.CharField(max_length = 40, help_text = 'Enter post title')
post_text_content = models.TextField(max_length = 1000)
post_author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
post_date = models.DateField(auto_now = True, auto_now_add = False)
#Make optional Image Field
post_image = models.ImageField(upload_to = 'images', blank = True)
class Meta:
ordering = ['-post_date', 'post_title', 'post_author', 'post_text_content', 'post_image']
def __str__(self):
return self.post_title
def get_absolute_url(self):
return reverse('social-home')
That's pretty much it. If you need any more code, please ask me.
Thank you in advance!
EDIT: To be clear, when I add the images from the admin "create new post" it works, but when I add the image from the regular django form it does not show up.
You need to set enctype="multipart/form-data" on your form tag in you HTML to upload files.
<form method="post" enctype="multipart/form-data">
I am a newbie to django framework and want to take values and save it to database. for this i used post method but when i check it is executing else part. I went through previous question on it but still found unsatisfying in my case.
Code is as follow:
#views.py
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from .models import StudentInfo, History
from django.shortcuts import get_object_or_404, render
from .forms import Info
def index(request):
return HttpResponse("Hello, world")
def info(request):
if request.method == "POST":
the_form=Info(request.POST or None)
context={
"form": the_form
}
if form.is_valid():
form.save()
else:
return HttpResponse("It sucks")
return render(request, 'details.html', context)
#models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class StudentInfo(models.Model):
name=models.CharField(max_length=40, help_text="Enter Name")
reg_no=models.IntegerField(help_text='Enter your reg_no', primary_key=True)
email=models.EmailField(help_text='Enter email')
def __str__(self):
return self.name
class History(models.Model):
Reg_no=models.ForeignKey('StudentInfo', on_delete=models.CASCADE)
date=models.DateTimeField(auto_now=True)
def was_published_recently(self):
return self.date >= timezone.now() - datetime.timedelta(days=1)
#forms.py
from django import forms
from .models import StudentInfo, History
class Info(forms.ModelForm):
name= forms.CharField(label= 'Enter name')
reg_no= forms.CharField(label= 'Enter registration no.')
email= forms.EmailField(label= 'Enter email')
class Meta:
model= StudentInfo
fields= ['name', 'reg_no', 'email',]
#details.html
<h1>Enter the details</h1>
<form action="{% url 'auto:info' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Go" />
</form>
if form.is_valid():
form.save()
You should use the_form instead of form since that's what you called the output of info(...)
I am trying to use django's form module to create and display a form. The following code I have executes without errors but an HTML form is not populated.
I have made sure that I am loading correct template. I also am certain that correct view is triggered when I go to a certain URL. I am posting some relevant code below from views, model, forms, and template files. I did debugging for quite a bit by trial-and-error but could not get to the root of issue.
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from app.forms import RegistrationForm
def registration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
pass
else:
''' user is not submitting the form, show them a blank registration form '''
form = RegistrationForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
register.html
{% extends "base.html" %}
{% block content %}
<form action="/register/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
form.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from app.models import Agent
class RegistrationForm(ModelForm):
username = forms.CharField( label=(u'User Name'), required=True )
first_name = forms.CharField( label=(u'First Name'), required=True )
last_name = forms.CharField( label=(u'Last Name'), required=True )
birthday = forms.DateField( label=(u'Date of birth'), required=True )
email = forms.EmailField( label=(u'Email Address'), required=True )
password = forms.CharField( label=(u'Password'), widget=forms.PasswordInput(render_value=False), required=True )
password_confirm = forms.CharField( label=(u'Confirm Password'), widget=forms.PasswordInput(render_value=False), required=True )
class Meta:
model = Agent
#exclude = ['username',]
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken, please select another.")
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['password_confirm']:
raise forms.ValidationError("The passwords did not match. Please try again.")
return self.cleaned_data
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Agent(models.Model):
username = models.OneToOneField(User)
birthday = models.DateField()
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField()
def __unicode__(self):
return self.last_name + ", " + self.first_name
Had to add content block ref in base.html
{% block content %}
{% endblock %}