NOT NULL constraint failed: statussaver_post.user_id - python

I'm trying to save a user post data through a modelform in django. Unfortunately, I stumbled to NOT NULL constraint failed:statussaver_post.user_id. Here's my post model.
class post(models.Model):
content=models.TextField(null=True,blank=True)
title = models.CharField(max_length=200,null=True,blank=True)
vedio = models.FileField(upload_to='vedios', blank=True, null=True)
img = models.ImageField(upload_to='images', null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return self.title
I handle the request in views.py as shown below.
def userpost(request):
if request.method=='POST':
form=uploadform(request.POST,request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form=uploadform()
return render(request,'statussaver/u.html',{'form':form,})
The form in the code above is called from forms.py as presented below.
from django import forms
from .models import post
class uploadform(forms.ModelForm):
class Meta:
model=post
fields= '__all__'
What should I do to fix this error ?

Related

Attribute Error When Clicking Model in Admin Section of Django

I'm using Django and I'm getting the error AttributeError at /admin/network/post/
'Post' object has no attribute 'user'
The strange thing is this error happens when I'm looking at the admin section, and clicking 'Posts.' I only have models for users and posts. Not sure how to fix this error because so far I've never gotten an error like this when clicking it in the admin section of the site: http://127.0.0.1:8000/admin/
I think the issue is in my model because the view for creating a post works totally fine.
models.py
class User(AbstractUser):
pass
class Post(models.Model):
text = models.TextField(max_length=500, blank=True, null=True)
username = models.ForeignKey('User', on_delete=models.CASCADE,
related_name='author',
null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
like = models.ManyToManyField(
User, blank=True, related_name="liked_user")
def __str__(self):
return self.user.username
class Follow(models.Model):
target = models.ForeignKey('User', on_delete=models.CASCADE,
related_name='followers')
follower = models.ForeignKey('User', on_delete=models.CASCADE,
related_name='targets')
views.py
def make_post(request):
if request.method == "GET":
form_for_post = {'form': PostForm()}
return render(request, "network/make_post.html", form_for_post)
else:
form = PostForm(request.POST)
if form.is_valid():
text = form.cleaned_data['text']
new_post = Post.objects.create(
text=text,
username=request.user,
)
return render(request, "network/make_post.html", {
"new_post": new_post,
})
You defined the field that refs to a User in the Post model to be username, not user, although user should be a better idea.
You thus should implement the __str__ method as:
class Post(models.Model):
# …
username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True)
# …
def __str__(self):
return self.username.username
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

search_field cannot accept query from User model

i tried to make search field to search by author in the admin panel but i got an error
Related Field got invalid lookup: icontains
i follow the documentation and other stackoverflow question but it doesn't work
#model.py
from django.contrib.auth import get_user_model
User = get_user_model()
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.user)
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(verbose_name='content')
date_published = models.DateTimeField(auto_now_add=True)
date_edited = models.DateTimeField(auto_now=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField(blank=True)
def __str__(self):
return self.title
#admin.py
from django.contrib import admin
from .models import Post, Author,
class PostAdmin(admin.ModelAdmin):
list_display = ['title',
'date_published',
'date_edited',
'author', ]
search_fields = ['title',
'author__user',]
admin.site.register(Post, PostAdmin)
admin.site.register(Author)
it works when i changed the search_field[1] to author__id, but since it only accept id, it can't get the username. any idea how to solve it? should i make custom user model?

ValueError: Cannot create form field for 'author' yet, because its related model 'settings.AUTH_USER_MODEL' has not been loaded yet

I am trying to set up a basic blog with a custom auth model. I am trying to get a simple form to work but somehow I am not able to make it work. I am not sure what is causing the error. This is a fresh app and a fresh project I am working on.
I tried to reference from the docs but I am not sure what I am doing incorrect. How can i fix this error? Thanks in advance
Docs: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project
Similar questions: Cannot create form field for 'created_by' yet, because its related model 'users.User' has not been loaded yet
My Current Code
models.py
class User(AbstractUser):
pass
class Post(models.Model):
author = models.ForeignKey('settings.AUTH_USER_MODEL')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
forms.py:
from blog.models import User
class PostForm(forms.ModelForm):
image = forms.CharField(
widget=forms.FileInput(attrs={'class': 'form-control'}),required=False)
class Meta():
model = Post
fields = ('author','title', 'text','image')
widgets = {
'title': forms.TextInput(attrs={'class': 'textinputclass'}),
}
views.py
from blog.forms import PostForm, CommentForm
class CreatePostView(LoginRequiredMixin,CreateView):
...
form_class = PostForm
model = Post
def form_valid(self,form):
if self.request.POST:
post = form.save()
return HttpResponseRedirect('/')
settings.py:
AUTH_USER_MODEL = 'blog.User'
admin.py:
from .models import User
from django.contrib.auth.admin import UserAdmin
admin.site.register(User,UserAdmin)
You should use settings.AUTH_USER_MODEL, not the string 'settings.AUTH_USER_MODEL':
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL)

Automatically attaching the logged in user to a post he/she creates

What a want to do: When a user is logged in, and he or she makes a post, the name of that user should automatically be assigned in my database posts.
What it's doing: It's not adding a user automatically, but i am able to assign a user manually, so I'm accessing the user database, and seeing whom i can attach to a newly made post.
My question is then, how can i get this process done automatically?
Here is my code from the model.py in the posts app:
from __future__ import unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.contrib.auth.models import User
User = settings.AUTH_USER_MODEL
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
#email = models.EmailField(null=True, blank=True, default=None)
user = models.ForeignKey(User, null=True,)
#upload = models.FileField(null=True, blank=True, default=None)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"id":self.id})
class Meta:
ordering = ["-timestamp", "-updated"]
I am getting the user class via User = settings.AUTH_USER_MODEL and the AUTH_USER_MODEL is referring in settings.py to a class called MyUser in another models.py who originates from an app called accounts.
here is the code from that class:
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
is_admin = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'email'
Here is the code from views.py in the posts app:
def post_create(request):
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# Message succes
messages.success(request, "Succesfully Created ")
return HttpResponseRedirect(instance.get_absolute_url())
else:
messages.error(request, "Not Succesfully created")
context = {
'form': form,
}
return render(request, app_name+"/post_form.html", context)
Here is the forms.py in the posts app:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = {
"title",
"content",
"user",
#"email",
#"upload",
}
Here are two pictures to illustrate my problem:
The post create site
The django administration
Let me now if any more code is needed, appreciate any feedback as well.
I don't have a lot of rep on stack overflow so please let me know if this is poorly explained, and i shall re right it.
Simply change:
instance = form.save(commit=False)
instance.save()
to
instance = form.save(commit=False)
if request.user.is_authenticated():
instance.user = request.user
instance.save()
If user is logged in, i think the Combobox should not
appear, so you can do that on forms.py
forms.py
class PostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(PostForm, self).__init__(*args, **kwargs)
if not self.user.is_authenticated():
self.fields['user'] = forms.ModelChoiceField(
required=True,
queryset=User.objects.all())
class Meta:
model = Post
fields = {
"title",
"content",
# "user",
#"email",
#"upload",
}
on views.py
def post_create(request):
form = PostForm(request.POST or None, user = request.user)
if form.is_valid():
if request.user.is_authenticated():
form.instance.user = request.user
form.save()
...
return render(request, app_name+"/post_form.html", context)
If you want the Combobox has selected with the user logged in, you can pass initial data on views.py, like this:
def post_create(request):
if request.method == 'GET':
form = PostForm(initial = {'user' : request.user})

Django contact form confirmation email

I'm relatively new to django and building my first app.
Tried searching through the site, but for the life of me cannot find the relevant information needed.
I'm looking to have a confirmation email sent to the entered email address on a contact form. I've seen examples of sending to a chosen address, or to user, but I can't seem to work out how to send mail to the email entered on the form.
Any help is greatly appreciated!
models.py:
from django.db import models
class Quote(models.Model):
name = models.CharField(max_length=200, blank=False, null=False, verbose_name="your name")
email = models.EmailField(max_length=255, blank=False, null=False)
created_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
forms.py:
class QuoteForm(forms.ModelForm):
class Meta:
model = Quote
views.py:
class QuoteView(CreateView):
model = Quote
form_class = QuoteForm
template_name = "quote/quote.html"
success_url = "/quote/success/"
def form_valid(self, form):
super(QuoteView,self).form_valid(form)
return HttpResponseRedirect(self.get_success_url())
class QuoteSuccessView(TemplateView):
template_name = "quote/quote-complete.html"
You can access validated form data (coerced to the fields respective types) via the cleaned_data attribute as shown in the form docs
https://docs.djangoproject.com/en/dev/topics/forms/#processing-the-data-from-a-form
from django.core.mail import send_mail
def form_valid(self, form):
super(QuoteView,self).form_valid(form)
send_mail("Foo", "bar", 'from#example.com', [form.cleaned_data['email']])
return HttpResponseRedirect(self.get_success_url())

Categories

Resources