Django "ProgrammingError at /create-post" usnig heroku postgres as database host - django

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

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()

Django email address not showing in admin

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)

Getting OperationalError in django

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.

Django ModelForm some fields aren't saved

I'm using a ModelForm in Django but some fields are not saved to the database...
models.py file
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.forms import ModelForm
# Create your models here.
class Bill(models.Model):
image_name = models.CharField(max_length=150)
upload_date = models.DateTimeField(default=timezone.now)
image = models.ImageField()
description = models.TextField(blank=True)
result = models.CharField(max_length=1000)
uploaded_by = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
def __str__(self):
return str(self.result + self.description)
forms.py file
from django import forms
from django.db import models
from django.forms import ModelForm
from .models import Bill
class BillForm(ModelForm):
class Meta:
model = Bill
fields = ['image', 'description']
exclude = ['result', 'image_name', 'upload_date', 'uploaded_by']
views.py file
def upload(request):
if request.method == 'POST':
form = BillForm(request.POST, request.FILES)
if form.is_valid():
form.image_name = request.FILES['image']
form.upload_date = datetime.now()
form.uploaded_by = request.user
form.result = "something"
form.save()
return redirect('cism-home')
else:
form = BillForm()
return render(request, 'auth/upload.html', {'form': form})
So the image and description fields are saved but other fields are not. Any ideas why is that?
Your form is excluding some fields, so you can't "access" those fields using:
form.upload_date (for example), because they don't exists.
What you can do is:
if form.is_valid():
bill = form.save(commit=False)
bill.image_name = request.FILES['image']
bill.upload_date = datetime.now()
bill.uploaded_by = request.user
bill.result = "something"
bill.save()
If you want a quick description about what "commit=False" do, you can check:
Django ModelForm: What is save(commit=False) used for?

Add model relation to ModelForm before saving

models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=32)
class Article(models.Model):
author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
content = models.TextField()
forms.py
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['content']
In my web application, the author logs in and writes an article. So clearly, when the author is presented with an ArticleForm, he/she does not need to fill in the author field in the ArticleForm because the application already knows who the author is through the use of session variables.
This is the way I tried to add the author:
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Article
from .forms import ArticleForm
#login_required
def new_article(request):
author_name = request.session['author_name']
author = Author.objects.get(name=author_name)
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.author = author # I suspect the mistake is here
# I also tried form.author = author.id
form.save()
return redirect('success')
else:
form = ArticleForm()
return render(request, 'writings/new_article.html', {'form': form})
When I look at the database table, the author_id column is always NULL. What is wrong with my approach? How do I add a model relation before saving a ModelForm?
Capture the object returned from form.save(commit=False) and modify that rather than the form. EG:
if form.is_valid():
article = form.save(commit=False)
article.author = author
article.save()
return redirect('success')