When i am trying to access the Home page i am getting the following error
OperationalError at /
no such column: articles_article.author_id
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Article(models.Model):
author = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
thumbnail = models.ImageField(default='default.png', blank=True, upload_to='profile_pics')
def __str__(self):
return self.title
def __repr__(self):
return self.title
def snippet(self):
return self.body[:50]+'...'
def getslug(self):
return self.title.lower().replace(' ', '-')
djangonautic\views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.apps import apps
def about(request):
return render(request, "about.html")
def home(request):
article_model = apps.get_model('articles', 'Article')
articles = article_model.objects.all()[0:3]
return render(request, "home.html", {'articles': articles})
articles\views.py
from django.shortcuts import render, redirect
from .models import Article
from .forms import ArticleForm
from django.utils import timezone
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required(login_url='users:login')
def article_list(request):
articles = Article.objects.all().order_by('date')
return render(request, "articles.html", {'articles': articles })
#login_required(login_url='login')
def article_details( request, slug, pk):
article = Article.objects.get(pk = pk)
return render(request, "article_details.html", {'article': article})
#login_required(login_url='login')
def create_article(request):
if request.method == 'POST':
form = ArticleForm(request.POST, request.FILES or None)
if form.is_valid():
article = form.save(commit=False)
article.date = timezone.now()
article.slug = Article.getslug(article)
article.author = request.user
article.save()
return redirect('articles:details', slug=article.slug, pk=article.pk)
else:
form = ArticleForm()
return render(request, 'create_article.html', {'form': form})
admins.py
from django.contrib import admin
from .models import Article
# Register your models here.
admin.site.register(Article)
I have run python manage.py makemigrations and python manage.py migrate commands but the issue still persists.
0001_initial.py
# Generated by Django 3.0.5 on 2020-05-10 18:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.SlugField()),
('body', models.TextField()),
('date', models.DateTimeField(auto_now_add=True)),
('thumbnail', models.ImageField(blank=True, default='default.png', upload_to='profile_pics')),
('author', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
you need to delete your previous migration files and again run
python manage.py makemigrations
python manage.py migrate
it seems you have added new column in existing table.
I guess i solved this issue. I deleted the previously added articles and then i deleted the db.sqlite3 file. Then i ran the migration again and it worked. Not sure if deleting the articles was the correct approach, but that was the only one i could think of.
Please let me know if there was any other way to resolve this error without having to delete the articles.
Related
[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()
I am trying to create a blog website in django using postgres with heroku in the cloud. When trying to submit the post using forms from django I get this error "ProgrammingError at /create-post
column "title" of relation "main_post" does not exist
LINE 1: INSERT INTO "main_post" ("author_id", "title", "description"... "
This is my view for creating posts
from django.shortcuts import render, redirect
from .forms import RegisterForm, PostForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, logout, authenticate
#login_required(login_url="/login")
def home(request):
return render(request, 'main/home.html')
#login_required(login_url="/login")
def create_post(request):
if request.method =='POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect("/home")
else:
form = PostForm()
return render(request, 'main/create_post.html', {"form": form})
This is my forms.py file
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Post
class RegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "description"]
This is my Post model
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title + "\n" + self.description
This is the error
enter image description here
Delete your migrations folder and re-migrate like this:
python manage.py makemigrations appname
python manage.py sqlmigrate appname 0001
python manage.py migrate
And then try
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.
Literaly like title say...check the picture. When i try to make new Post it says i made it but it wont show up on admin page nor in detail.html.
http://prntscr.com/n0pfrv
here is my code for post model
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(help_text="A short label, generally used in URLs.",default='', max_length=100)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date_posted']
def save(self):
slug = self.title
def get_absolute_url(self):
return reverse('detail', kwargs={'slug':self.slug})
def __str__(self):
return self.title
admin.py
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'slug', 'date_posted', 'author']
list_filter = ['title', 'date_posted']
prepopulated_fields = { 'slug': ('title',)}
admin.site.register(Post, PostAdmin)
views.py in app called blog were i have model Post also
from django.contrib import messages
from . models import Post
from django.core.mail import send_mail
from django.views.generic import DeleteView, ListView
def index_view(request):
return render(request, 'blog/index_view.html')
def blog_view(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/blog_view.html', context)
class PostDetailView(DeleteView):
model = Post
template_name = 'blog/detail.html'
context_object_name = 'post'
If you need any other of my code im gonna post it
You don't actually save the data in your save(self) method:
def save(self):
slug = self.title
super(Post, self).save(*args, **kwargs)
You should call the real save method as mentioned in the docs:
Overriding predefined model methods
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)