How to test related models in Django v3 - python

I am trying to test Destination and Comment models and check if they are related in the test.
I have already tested the Destinations models and it pass the test with the approach:
def test_destinations_model(self):
destination = Destinations.objects.create(
tour_title = 'test1',
booking_start_date='2021-05-30',
booking_end_date= '2022-05-30',
price=2000,
description='test1',
author='test1',
image='image.png'
)
destination.save()
self.assertEquals(destination.tour_title, 'test1')
self.assertEquals(destination.booking_start_date, '2021-05-30')
self.assertEquals(destination.booking_end_date, '2022-05-30')
self.assertEquals(destination.price, 2000)
self.assertEquals(destination.description, 'test1')
self.assertEquals(destination.author, 'test1')
self.assertEquals(destination.image, 'image.png')
However, I don't know how to test the Comment model since it is related to the Destinations one. I have done the following approach but the test is failing with the following message:
#message of failing test for test_comment_model
self.assertEquals(destination, comment)
AssertionError: <Destinations: test1> != <Comment: Comment test1 by John>
#Failling test:
def test_comment_model(self):
#post not needed to test as foreignKey
destination = Destinations(
tour_title = 'test1',
booking_start_date='2021-05-30',
booking_end_date= '2022-05-30',
price=2000,
description='test1',
author='test1',
image='image.png'
)
destination.save()
comment = Comment(
post=destination,
name = 'John',
email = 'any#email.com',
comment = 'test1',
created_on = timezone.now(),
active = False,
)
comment.save()
self.assertEquals(destination, comment)
class Destinations(models.Model):
author = models.CharField(max_length=200, unique=False)
tour_title = models.CharField(max_length=250)
description = RichTextUploadingField()
image = models.ImageField(upload_to='tour_images', blank=True)
location = models.CharField(max_length=250)
booking_start_date = models.DateField()
booking_end_date = models.DateField()
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return self.tour_title
class Comment(models.Model):
post = models.ForeignKey(Destinations,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
comment = 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.comment, self.name)

I am still not sure what exactly you want to test but if you want to check if Comment is related to destination you could check by following
self.assertEquals(destination, comment.post)

Related

model.objects.all() doesn't find anything when foreign key in model

when I load the website i get this error
my models.py file looks like:
# Create your models here.
class Information(models.Model):
id = models.CharField(max_length=200, primary_key=True)
title = models.CharField(max_length=500)
link = models.CharField(max_length=100)
summary = models.CharField(max_length=1000)
published = models.CharField(max_length = 100)
def __str__(self):
return self.title
class Search(models.Model):
id = models.CharField(max_length=100, primary_key=True)
searched_titles = models.CharField(max_length=100)
searched_topics = models.CharField(max_length=100)
number_found_articles = models.IntegerField()
def __str__(self):
return self.id
class Article_search(models.Model):
id = models.AutoField(primary_key=True)
found_articles = models.ForeignKey(
Information, on_delete=models.CASCADE)
search_details = models.ForeignKey(
Search, on_delete=models.CASCADE)
def __str__(self):
return self.id
in my view.py file:
def show_articles_with_this_filter_id(request):
all = Article_search.objects.all()
print(all)
return render(request, 'show_article.html')
when I get to the print statement I get the error shown in the picture:
Unknown column 'database_article_search.found_articles_id' in 'field list'
why is the part _id pasted behind found_articles?
this is the error i get when i remove the id from article_search
id error when printing Article_search.objects.all()
# Create your models here.
class Information(models.Model):
title = models.CharField(max_length=500)
link = models.CharField(max_length=100)
summary = models.CharField(max_length=1000)
published = models.CharField(max_length = 100)
def __str__(self):
return self.title
class Search(models.Model):
searched_titles = models.CharField(max_length=100)
searched_topics = models.CharField(max_length=100)
number_found_articles = models.IntegerField()
def __str__(self):
return self.searched_titles
class Article_search(models.Model):
found_articles = models.ForeignKey(
Information, on_delete=models.CASCADE)
search_details = models.ForeignKey(
Search, on_delete=models.CASCADE)
Make model like this and then run two commands
1.python manage.py makemigrations and then 2.python manage.py migrate
"In your views.py file"
def show_articles_with_this_filter_id(request,id):
all = Article_search.objects.filter(id=id)
print(all)
return render(request, 'show_article.html')

OperationalError at /admin/app/review/ no such column: app_review.startup_id

I keep getting this error whenever I open my Django admin page and click these models.
Here is my models.py
from django.db import models
from django.utils import timezone
from django.utils.crypto import get_random_string
import string
import random
code = get_random_string()
class Startup(models.Model):
code = models.CharField(max_length=12, default=code, unique=True)
name = models.CharField(max_length=30)
lead = models.CharField(max_length=50, unique=True)
problem = models.CharField(max_length=100)
solution = models.CharField(max_length=100)
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class Idea(models.Model):
startup = models.ForeignKey(Startup, on_delete=models.CASCADE)
summary = models.CharField(max_length=100)
attachment = models.FileField(upload_to='attachments/idea')
member = models.CharField(max_length=50, unique=True)
date = models.DateTimeField(default=timezone.now)
DRAFT = 'DRAFT'
REVISED = 'REVISED'
FINAL = 'FINAL'
TYPE_CHOICES = [
(DRAFT, 'Draft'),
(REVISED, 'Revised'),
(FINAL, 'Final'),
]
type = models.CharField(max_length=7, choices=TYPE_CHOICES, default=DRAFT)
def __str__(self):
return self.summary
class Comment(models.Model):
startup = models.ForeignKey(Startup, on_delete=models.CASCADE)
idea = models.ForeignKey(Idea, on_delete=models.CASCADE)
comment = models.CharField(max_length=100)
member = models.CharField(max_length=50, unique=True)
date = models.DateTimeField(default=timezone.now)
GOOD = 'GOOD'
FINE = 'FINE'
BAD = 'BAD'
RATING_CHOICES = [
(GOOD, 'Good'),
(FINE, 'Fine'),
(BAD, 'Bad'),
]
rating = models.CharField(max_length=4, choices=RATING_CHOICES, default=GOOD)
def __str__(self):
return self.comment
class Product(models.Model):
startup = models.ForeignKey(Startup, on_delete=models.CASCADE)
attachment = models.FileField(upload_to='attachment/product')
version = models.IntegerField()
changes = models.CharField(max_length=100)
member = models.CharField(max_length=50, unique=True)
date = models.DateTimeField(default=timezone.now)
INITIAL = 'INITIAL'
IMPROVE = 'IMPROVE'
FINISHED = 'FINISHED'
STAGE_CHOICES = [
(INITIAL, 'Initial'),
(IMPROVE, 'Improve'),
(FINISHED, 'Finished'),
]
stage = models.CharField(max_length=9, choices=STAGE_CHOICES, default=INITIAL)
def __str__(self):
return self.changes
class Review(models.Model):
startup = models.ForeignKey(Startup, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
review = models.CharField(max_length=100)
member = models.CharField(max_length=50, unique=True)
date = models.DateTimeField(default=timezone.now)
GOOD = 'GOOD'
FINE = 'FINE'
BAD = 'BAD'
RATING_CHOICES = [
(GOOD, 'Good'),
(FINE, 'Fine'),
(BAD, 'Bad'),
]
rating = models.CharField(max_length=4, choices=RATING_CHOICES, default=GOOD)
def __str__(self):
return self.review
Did you run migrations when you added these models?
./manage.py makemigrations
./manage.py migrate
and did you add "app" to INSTALLED_APPS
Whenever you make changes in your models, run:
$ python manage.py makemigrations
$ python manage.py migrate
to apply the changes in the DB.
Migrations | Django documentation
You might have made changes to the model and migrated again which would have caused problems in existing instances of the model or newly created model. So in your migrations.py folder delete the latest migrations and try remigrating
check this similar solution :
operational errors: no such column solution

Django - Null value in column "imageLink" violates not-null constraint

I've been trying to setup an upload possibility for a form (with the intent to upload pictures) to a database, which is linked to other data in the list but every time I try to run it, it won't ignore the null that is suppose to be the picture. I've been reading up and trying to get this fixed for a solid day and a half but there isn't a lot of documentation to be found on this subject. Am I missing a place where the file needs to be uploaded to and/or is there a way to ignore the null if there hasn't been a photo added to the list?
Error message:
IntegrityError at /createproduct/
null value in column "imageLink" violates not-null constraint
DETAIL: Failing row contains (81, Comedy, Comic, DC, 5, Engels, 5, Henk, haHAA, null, 808, 2000-04-02).
Form snippet 1:
class PRegistrationForm(ModelForm):
ProductsEntry = Products(prodNum=products.id, prodName=products.prodName, prodPrice=products.prodPrice,
prodStock=products.prodStock)
ProductsEntry.save()
ProdData = ProductDetails(prodNum=products(prodNum=products.id), genre=products.genre,
type=products.type, publisher=products.publisher,
totalPages=products.totalPages, language=products.language,
rating=products.rating, author=products.author, desc=products.desc,
imageLink=products.imageLink, pubDatum=products.pubDatum)
ProdData.save()
if commit:
products.save()
return products
Form snippet 2:
class ProductDetails(forms.Form):
products_prodName = forms.CharField(required=True, max_length=200)
products_prodPrice = forms.DecimalField(required=True, max_digits=5, decimal_places=2)
products_prodStock = forms.IntegerField(required=True, max_value=5000, min_value=1)
products_genre = forms.CharField(required=False, max_length=15)
products_type = forms.CharField(required=False, max_length=15)
products_publisher = forms.CharField(required=True, max_length=30)
products_totalPages = forms.IntegerField(required=True, max_value=2000, min_value=1)
products_language = forms.CharField(required=False, max_length=25)
products_rating = forms.IntegerField(required=False, max_value=5, min_value=1)
products_author = forms.CharField(required=True, max_length=30)
products_desc = forms.CharField(required=True, max_length=2000)
products_imageLink = forms.FileField(allow_empty_file=True, required=False)
products_pubDatum = forms.DateField(required=False)
def __init__(self, *args, **kwargs):
super(ProductDetails, self).__init__(*args, **kwargs)
self.fields['products_prodName'].label = "Titel:"
self.fields['products_prodPrice'].label = "Prijs:"
self.fields['products_prodStock'].label = "Quantiteit:"
self.fields['products_genre'].label = "Genre:"
self.fields['products_type'].label = "Type:"
self.fields['products_publisher'].label = "Uitgever:"
self.fields['products_totalPages'].label = "Bladzijden:"
self.fields['products_language'].label = "Taal:"
self.fields['products_rating'].label = "Score:"
self.fields['products_author'].label = "Schrijver:"
self.fields['products_desc'].label = "Beschrijving:"
self.fields['products_imageLink'].label = "Foto:"
self.fields['products_pubDatum'].label = "Uitgeefdatum:"
Models:
class Products(models.Model):
class Meta:
verbose_name_plural = "Products"
prodNum = models.IntegerField(primary_key=True)
prodName = models.CharField(max_length=200)
prodPrice = models.DecimalField(max_digits=5, decimal_places=2)
prodStock = models.IntegerField()
def __str__(self):
return (str(self.prodNum))
class ProductDetails(models.Model):
class Meta:
verbose_name_plural = "Product details"
prodNum = models.ForeignKey(Products, db_column='prodNum')
genre = models.CharField(max_length=50)
type = models.CharField(max_length=50, default="Comic")
publisher = models.CharField(max_length=50)
totalPages = models.IntegerField()
language = models.CharField(max_length=25, default="Engels")
rating = models.IntegerField()
author = models.CharField(max_length=50)
desc = models.TextField()
imageLink = models.CharField(max_length=300)
pubDatum = models.CharField(max_length=30, default="1 januari, 1990")
You haven't added null= True to your field, default is False.
As in the docss
null
If True, Django will store empty values as NULL in the database. Default is False.
So this should work:
imageLink = models.CharField(null=True, max_length=300)

Django how to get values by user_ID

I'm trying to get all of a users reports and pass them to the page template. My question is how do I filter by user_id=1?
views.py
data = report.objects.values()
return render(request,'list.html',data)
models.py
class user(models.Model):
firstname = models.CharField(max_length=250)
lastname = models.CharField(max_length=250)
email = models.CharField(max_length=250)
password = models.CharField(max_length=250)
newsletter = models.BooleanField(default=0)
accountlevel = models.BigIntegerField(default=1)
reportsCreated = models.BigIntegerField(default=0)
class report(models.Model):
user = models.ForeignKey(user, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
dateran = models.DateField()
fromdate = models.DateField()
todate = models.DateField()
state = models.IntegerField()
graphURL = models.CharField(max_length=1000)
reporttype = models.CharField(max_length=250)
In your views.py you can filter values by user id.
Refer following code
data = report.objects.filter(user__id=your_user_id).values()
return render(request,'list.html',data)
Got it to work, I was missing the context,
data = Report.objects.filter(user__id=1).values()
context = {'data': data}
return render(request,'list.html',context)
Thank you call for your help :)

Not Null Constraint Fail

I looked at a ton of these issues on stack overflow, but none of the solutions seemed to help me. I've tried Null=True and Blank=True as well as default=None and they all give errors. Anyone have any ideas? Thanks so much!
The error I'm getting is this:
NOT NULL constraint failed: first_app_trip.messages_id
My models:
class Trip(models.Model):
title = models.CharField(max_length = 50)
destination = models.CharField(max_length = 255)
description = models.TextField()
start_date = models.DateField(auto_now_add=False)
end_date = models.DateField(auto_now_add=False)
creator = models.ForeignKey(User, related_name="created_trips")
participants = models.ManyToManyField(User, related_name="joined_trips", default=None)
messages = models.ForeignKey(Message, related_name="messages", default=None )
notes = models.ForeignKey(Note, related_name="notes", default=None)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now_add = True)
class Message(models.Model):
content = models.TextField()
author = models.ForeignKey(User, related_name="author")
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now_add = True)
class Note(models.Model):
content = models.CharField(max_length=45)
user = models.ForeignKey(User, related_name="notes")
My Views:
def create(request):
user = current_user(request)
print user.id
return render(request, 'first_app/create_trip.html')
def add(request):
user = current_user(request)
print user
trip = Trip.objects.create(
title = request.POST.get('title'),
destination = request.POST.get('destination'),
description = request.POST.get('description'),
start_date = request.POST.get('start_date'),
end_date = request.POST.get('end_date'),
creator = user
)
print trip
return redirect('/user_profile')
Python case sensitive
try it
class Trip(models.Model):
messages = models.ForeignKey(Message, related_name="messages", null=True, blank=True )
# in this line case sensitive ^^^^^^^^^^^^^^^^^^^
next:
./manage.py makemigrations first_app
./manage.py migrate first_app
after it try your action

Categories

Resources