The App is A Blog Post App That is Working fine Locally But After I Deployed It To Heroku, The App Cannot run. I did more Than a week trying to fix it through the views and models with no success.
This Is The Error When Trying To Open The App
views.py
from django.shortcuts import render,get_object_or_404, get_list_or_404
from posts.models import Post, Category
# Create your views here.
import datetime
def index(request):
now = datetime.datetime.now()
big_slider_list = Post.objects.filter(category__name='Big_Slider')
news_box_list = Post.objects.filter(category__name='People')
cote_divoire_list = Post.objects.filter(category__name="CĂ´te d'Ivoire").exclude(position=1)
block1_big = Post.objects.filter(position=1)
culture_list = Post.objects.filter(category__name="Culture").exclude(position=2)
block2_big = Post.objects.filter(position=2)
sport_list = Post.objects.filter(category__name="Sports").exclude(position=3)
block3_big = Post.objects.filter(position=3)
infrast_et_devel_list = Post.objects.filter(category__name="Infrastructures Et DĂ©velopements")
context = {
'now': now,
'big_slider_list': big_slider_list[:10],
'news_box_list': news_box_list[:4],
'cote_divoire_list': cote_divoire_list[:4],
'block1_big': block1_big[0],
'culture_list': culture_list[:3],
'block2_big': block2_big[0],
'sport_list': sport_list[:3],
'block3_big': block3_big[0],
'infrast_et_devel_list': infrast_et_devel_list[:3],
}
return render(request, 'home/index.html', context)
models.py :
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your models here.
User = get_user_model()
STATUS = (
(0, "Draft"),
(1, "Publish")
)
POSITIONS = [
(0, ' '),
(1, 'BIG_BLOCK_1'),
(2, 'BIG_BLOCK_2'),
(3, 'BIG_BLOCK_3'),
(4, 'BIG_BLOCK_4'),
]
class Author(models.Model):
name = models.CharField(max_length=50)
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(null=True, blank=True)
email = models.EmailField(unique=True)
active = models.BooleanField(default=False)
created_on = models.DateTimeField(auto_now_add=True)
last_logged_in = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
class Category(models.Model):
country = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE,)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('posts:post_by_category', args=[self.slug])
class Tag(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE,)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('posts:post_by_tag', args=[self.slug])
class Post(models.Model):
status = models.IntegerField(choices=STATUS, default=0)
position = models.IntegerField(choices=POSITIONS, default=0)
title = models.CharField(max_length=300)
short_title = models.CharField(max_length=200)
display_image = models.ImageField(null=True, blank=True)
post_image = models.ImageField(null=True, blank=True)
content = models.TextField(max_length=8000)
slug = models.SlugField(max_length=300, unique=True)
updated_on = models.DateTimeField(auto_now=True, auto_now_add=False)
created_on = models.DateTimeField(auto_now=False, auto_now_add=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE,)
category = models.ForeignKey(Category, on_delete=models.CASCADE,)
tags = models.ManyToManyField(Tag,)
comment_count = models.IntegerField(default=0)
class Meta:
ordering = ['-created_on']
verbose_name = "All Post"
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('posts:post_detail', kwargs={'slug': self.slug})
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
It's something to do with the migrations. Your local DB has all the migrations applied, while your Database on Heroku doesn't have the post field. Maybe you added/edited the field later so your two DBs are out of sync. Since this seems to be a new project without data it would be easier for you to heroku reset your heroku database and push the local db to heroku. Here are the instructions: https://devcenter.heroku.com/articles/heroku-postgres-import-export
Related
Here is what appears when i try to use python manage.py makemigrations
traceback error
Here is models.py code
----------------------code-------------------------------------
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=255, unique=True)
class Meta:
verbose_name_plural = 'categories'
# def get_absolute_url(self):
# return reverse("store:category_list", args=[self.slug])
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator')
title = models.CharField(max_length=255)
author = models.CharField(max_length=255,default='admin')
description = models.TextField(blank=True)
image = models.ImageField(upload_to='images/')
slug = models.SlugField(max_length=255)
price = models.DecimalField(max_digits=4, decimal_places=2)
in_stock = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'Products'
ordering = ('-created',)
def __str__(self):
return self.title
------------------code end-------------------------------
im new and i dont know whats the problem
I have this in models and I want to create a signal that when someone follows someone, a thread is automatically created between that person and the person they followed. The models are in 2 different apps, one from the social network and the other from the chat.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.CharField(default='Hola, este es mi Blooby!!!', max_length=100)
image = models.ImageField(default='default.png')
def __str__(self):
return f'Perfil de {self.user.username}'
def following(self):
user_ids = Relationship.objects.filter(from_user=self.user)\
.values_list('to_user_id', flat=True)
return User.objects.filter(id__in=user_ids)
def followers(self):
user_ids = Relationship.objects.filter(to_user=self.user)\
.values_list('from_user_id', flat=True)
return User.objects.filter(id__in=user_ids)
class Post(models.Model):
timestamp = models.DateTimeField(default=timezone.now)
content = models.TextField(max_length=300)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
liked = models.ManyToManyField(User, default=None, blank=True)
class Meta:
ordering = ['-timestamp']
def __str__(self):
return self.content
#property
def num_likes(self):
return self.liked.all().count()
LIKE_CHOICES = (
('Like', 'Like'),
('Unlike', 'Unlike'),
)
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
value = models.CharField(choices=LIKE_CHOICES ,default='Like', max_length=10)
class Relationship(models.Model):
from_user = models.ForeignKey(User, related_name='relationships', on_delete=models.CASCADE)
to_user = models.ForeignKey(User, related_name='related_to', on_delete=models.CASCADE)
def __str__(self):
return f'{self.from_user} to {self.to_user}'
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.ForeignKey(User,related_name="user_name" , on_delete=models.CASCADE)
body = models.TextField()
timestamp = models.DateTimeField(default=timezone.now)
The models of the app chat , here is the thread
class ThreadManager(models.Manager):
def by_user(self, **kwargs):
user = kwargs.get('user')
lookup = Q(first_person=user) | Q(second_person=user)
qs = self.get_queryset().filter(lookup).distinct()
return qs
class Thread(models.Model):
first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person')
second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,
related_name='thread_second_person')
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = ThreadManager()
class Meta:
unique_together = ['first_person', 'second_person']
class ChatMessage(models.Model):
thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.CASCADE, related_name='chatmessage_thread')
user = models.ForeignKey(User, on_delete=models.CASCADE)
message = models.TextField()
timestamp = models.DateTimeField(default=timezone.now)
I m new to Django and I am learning it through a project but m stuck with this error which says that NoReverseMatch at /product/create/
here is my models.py file
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
# Create your models here.
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='category_created')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null= True,blank=True)
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail',
args=[self.slug])
This is my views.py but I m not sure if there is something wrong with my views
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from .models import Category, Product
class CategoryList(ListView):
model = Category
class CategoryDetail(DetailView):
model = Category
class ProductList(ListView):
model = Product
class ProductDetail(DetailView):
model = Product
class ProductCreate(CreateView):
model = Product
fields = ["category", 'name', 'image', 'description', 'price', 'stock','available', 'negiotiable']
class ProductUpdate(UpdateView):
model = Product
fields = ['name', 'image', 'description', 'price', 'stock','available', 'negiotiable']
class ProductDelete(DeleteView):
model = Product
success_url = reverse_lazy('product_list')
I can't tell if this is the problem without the traceback or urls.py but I'm guessing you need to auto-generate the slug field by overriding the save method in the Product model. Instructions here: http://fazle.me/auto-generating-unique-slug-in-django/
Or you could try this:
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null= True,blank=True)
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail', args=[self.slug])
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Product, self).save(*args, **kwargs)
Note that this way you will have to change db_index to unique for the name field.
I get an error, when I run this command python manage.py makemigrations blog in python django in models.py
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.Post', related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()`enter code here`
def __str__(self):
return self.text
There a couple of issues with your code:
Indentation
User class import
use Blog instead of blog.Blog
a quick fix:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()`enter code here`
def __str__(self):
return self.text
I have a Django 'add business' view which adds a new business with an inline 'business_contact' form.
The form works fine, but I'm wondering how to write up the unit test - specifically, the 'postdata' to send to self.client.post(settings.BUSINESS_ADD_URL, postdata)
I've inspected the fields in my browser and tried adding post data with corresponding names, but I still get a 'ManagementForm data is missing or has been tampered with' error when run.
Anyone know of any resources for figuring out how to post inline data?
Relevant models, views & forms below if it helps. Lotsa thanks.
MODEL:
class Contact(models.Model):
""" Contact details for the representatives of each business """
first_name = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
business = models.ForeignKey('Business')
slug = models.SlugField(max_length=150, unique=True, help_text=settings.SLUG_HELPER_TEXT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
phone = models.CharField(max_length=100, null=True, blank=True)
mobile_phone = models.CharField(max_length=100, null=True, blank=True)
email = models.EmailField(null=True)
deleted = models.BooleanField(default=False)
class Meta:
db_table='business_contact'
def __unicode__(self):
return '%s %s' % (self.first_name, self.surname)
#models.permalink
def get_absolute_url(self):
return('business_contact', (), {'contact_slug': self.slug })
class Business(models.Model):
""" The business clients who you are selling products/services to """
business = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=100, unique=True, help_text=settings.SLUG_HELPER_TEXT)
description = models.TextField(null=True, blank=True)
primary_contact = models.ForeignKey('Contact', null=True, blank=True, related_name='primary_contact')
business_type = models.ForeignKey('BusinessType')
deleted = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
address_1 = models.CharField(max_length=255, null=True, blank=True)
address_2 = models.CharField(max_length=255, null=True, blank=True)
suburb = models.CharField(max_length=255, null=True, blank=True)
city = models.CharField(max_length=255, null=True, blank=True)
state = models.CharField(max_length=255, null=True, blank=True)
country = models.CharField(max_length=255, null=True, blank=True)
phone = models.CharField(max_length=40, null=True, blank=True)
website = models.URLField(null=True, blank=True)
class Meta:
db_table = 'business'
def __unicode__(self):
return self.business
def get_absolute_url(self):
return '%s%s/' % (settings.BUSINESS_URL, self.slug)
VIEWS:
def business_add(request):
template_name = 'business/business_add.html'
if request.method == 'POST':
form = AddBusinessForm(request.POST)
if form.is_valid():
business = form.save(commit=False)
contact_formset = AddBusinessFormSet(request.POST, instance=business)
if contact_formset.is_valid():
business.save()
contact_formset.save()
contact = Contact.objects.get(id=business.id)
business.primary_contact = contact
business.save()
#return HttpResponse(help(contact))
#business.primary = contact.id
return HttpResponseRedirect(settings.BUSINESS_URL)
else:
contact_formset = AddBusinessFormSet(request.POST)
else:
form = AddBusinessForm()
contact_formset = AddBusinessFormSet(instance=Business())
return render_to_response(
template_name,
{
'form': form,
'contact_formset': contact_formset,
},
context_instance=RequestContext(request)
)
FORMS:
class AddBusinessForm(ModelForm):
class Meta:
model = Business
exclude = ['deleted','primary_contact',]
class ContactForm(ModelForm):
class Meta:
model = Contact
exclude = ['deleted',]
AddBusinessFormSet = inlineformset_factory(Business,
Contact,
can_delete=False,
extra=1,
form=AddBusinessForm,
)
The problem is you have not included the management form in your data. You need to include form-TOTAL_FORMS (total number of forms in the formset, default is 2), form-INITIAL_FORMS (the initial number of forms in the formset, default is 0) and form-MAX_NUM_FORMS (the maximum number of forms in the formset, default is '').
See the Formset documentation for more information on the management form.