When I run syncdb on my new m2m model I get the error:
Error: One or more models did not validate:
services.service: 'categories' specifies an m2m relation through model Service_Category, which has not been installed
I tried using the example listed on
https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
and when I synced that it worked fine. SO I am not getting something right with my model below. Not really sure why my model isnt working and if its a simple typo or something else. NOTE: The models worked fine using a simple m2m relationship but it doesnt like it this way. Thanks
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255, blank = True, null = True,
help_text='Content for description meta tag')
meta_description = models.CharField(max_length = 255, blank = True, null = True,
help_text = 'Content for description meta tag')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
class Meta:
#app_label = ''
db_table = 'categories'
ordering = ['created_at']
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_category', (), {'category_slug': self.slug})
class Service(models.Model):
name = models.CharField(max_length=255, unique = True)
slug = models.SlugField(max_length=255, unique = True,
help_text = 'Unique value for product page URL, created from name.')
old_price = models.DecimalField(max_digits=9, decimal_places=2,
blank = True, null = True, default = 0.0)
image = models.CharField(max_length=50, blank = True)
is_active = models.BooleanField(default = True)
is_bestseller = models.BooleanField(default = False)
is_featured = models.BooleanField(default = False)
description = models.TextField()
bullet1 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
bullet2 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
bullet3 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
bullet4 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
bullet5 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
micro_current = models.BooleanField(default = False)
meta_keywords = models.CharField(max_length = 255,blank = True, null = True,
help_text = 'Comma Delimited Set of SEO keywords for meta tag')
meta_description = models.CharField(max_length = 255, blank = True, null = True,
help_text = 'Content for description meta tag')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
categories = models.ManyToManyField(Category, through='Service_Category')
class Meta:
#app_label = ''
db_table = 'services'
ordering = ['created_at']
def __unicode__(self):
return self.name
class Service_Category:
category = models.ForeignKey(Category)
service = models.ForeignKey(Service)
micro_current = models.BooleanField(default = False)
class Meta:
#app_label = ''
db_table = 'service_categories'
services.service: 'categories' specifies an m2m relation through model Service_Category, which has not been installed
You missed to define your intermediate model correctly
class Service_Category(models.Model):
category = models.ForeignKey(Category)
service = models.ForeignKey(Service)
micro_current = models.BooleanField(default = False)
class Meta:
#app_label = ''
db_table = 'service_categories'
We have to inherit each of our model which we define from models.Model class.
Rest everything seems to be fine.
Service_Category needs to inherit from models.Model
i.e, class Service_Category(models.Model):
Related
im new in django, and im doing an ecommerce website. I have a problem, When I click on a subcategory its okay, it shows all the products of that subcategory. But I want to click on a category parent and show all the products that his children has, and i dont know how to do that.
Here is my models:
class Category(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True)
title = models.CharField(max_length= 200, null = True)
slug = models.SlugField(max_length=200, null = True)
ordering = models.IntegerField(default = 0)
class Meta:
verbose_name_plural = 'Categories'
ordering = ('ordering',)
def __str__(self):
return self.title
class Product(models.Model):
name = models.CharField(max_length = 255, null = True)
slug = models.SlugField(max_length=200)
category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE)
parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True)
brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE)
description = models.TextField(blank = True, null = True)
price = models.FloatField(null = True)
disccount = models.BooleanField(default = False)
disccount_price = models.FloatField(blank = True, null = True)
image = models.ImageField(upload_to = 'images/',blank = True, null = True)
thumbnail = models.ImageField(upload_to = 'images/', blank = True, null = True)
date_added = models.DateTimeField(auto_now_add = True)
class Meta:
ordering = ('-date_added',)
def __str__(self):
return self.name
Here is my view:
def category_detail(request, slug):
products = Product.objects.all()
subcategories = []
if slug:
category = get_object_or_404(Category, slug=slug)
products = products.filter(category = category)
subcategories = Category.objects.filter(parent = category)
context = {
'category': category,
'subcategories': subcategories,
'products' : products,
}
return render(request, 'category_detail.html', context)
So please I need some help:(
You can filter on Products that belong to a subcategory of a category category with:
products = products.filter(category__parent=category)
or if you want Products that belong to the category or to a category with as parent the category, you can filter with Q objects [Django-doc]:
from django.db.models import Q
products = products.filter(
Q(category__parent=category) |
Q(category=category)
)
I have not been able to resolve this IntegrityError issue in my Django's unittest. Here are my models:
class UserProfile(models.Model):
''' UserProfile to separate authentication and profile '''
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True, blank = True)
# Note: first name and last name is in the custom User model
first_name = models.CharField(max_length = 20, blank = True, null = True)
last_name = models.CharField(max_length = 30, blank = True, null = True)
address = models.CharField(max_length = 100, null=True, blank = True)
address_city = models.CharField(max_length = 30, null = True, blank = True)
metropolitan = models.CharField(max_length = 30, null = True, blank = False)
class Municipality(models.Model):
name = models.CharField(max_length = 50)
abb = models.CharField(max_length = 5)
date_created = models.DateTimeField(auto_now_add = True)
date_modified = models.DateTimeField(auto_now = True)
userprofile = models.ForeignKey('user_profile.UserProfile', blank = False, null = False, related_name = 'userprofile_municipalities', on_delete = models.CASCADE)
class Project(models.Model):
name = models.CharField(max_length = 50)
logo = models.ImageField(null=True, blank = True, width_field = 'logo_width', height_field = 'logo_height')
logo_height = models.IntegerField(default = 40)
logo_width = models.IntegerField(default = 40)
date_created = models.DateTimeField(auto_now_add = True )
date_modified = models.DateTimeField(auto_now = True )
# RELATIONSHIPS:
user_profiles = models.ManyToManyField('user_profile.UserProfile', through = 'ProjectAssociation', through_fields = ('project', 'user_profile' ), blank = True, related_name = 'user_projects')
address = models.OneToOneField(Address, on_delete = models.PROTECT, null = True, blank = True)
municipality = models.ForeignKey('development.Municipality', related_name = 'municipality_projects', null = False, blank = False)
class Job(models.Model):
project = models.OneToOneField('project_profile.Project', blank = False, on_delete = models.CASCADE, related_name = 'job')
...
date_modified = models.DateTimeField(auto_now_add = True)
date_created = models.DateTimeField(auto_now = True)
class Invoice(models.Model):
PO = models.CharField(max_length = 50, blank = False, null = False) # e.g. Mixed Use Residential Commercial Rental Invoice
invoice_type = models.CharField(max_length = 40)
date_created = models.DateTimeField(auto_now = True)
date_modified = models.DateTimeField(auto_now_add = True)
job = models.ForeignKey(DevelopmentProject, related_name = 'job_invoices', blank = True, null = True, on_delete = models.CASCADE)
Invoice_creator = models.ForeignKey('user_profile.UserProfile', related_name = 'created_invoices', blank = True, null = True, on_delete = models.SET_NULL) # ModelForm to enforce If the Invoice creator's account is closed, the corresponding Invoices to be preserved
Invoice_reviewer = models.ForeignKey('user_profile.UserProfile', related_name = 'reviewed_invoices', blank = True, null = True , on_delete = models.SET_NULL ) # The reviewer is not necessary, but
...
In my unittest, I am getting integrity error message even when I try to explicitly assign unique id to the created instance:
class UpdateinvoiceTestCase(TestCase):
''' Unit Test for Updateinvoice View '''
def setUp(self):
self.factory = RequestFactory()
# Create the dependencies
self.userprofile = mommy.make('user_profile.UserProfile')
print ('User profile: ', self.userprofile, ' - userprofile id: ', self.userprofile.id )
self.municipality = mommy.make('development.municipality', userprofile = self.userprofile, _quantity=1)
self.project = mommy.make('project_profile.Project', municipality = self.municipality[0], _quantity=2)
self.job = mommy.make('development.Job', project = self.project[0] )
# Create invoice
self.invoice = mommy.make('development.invoice', job = self.job)
# Passing the pk to create the url
the_uri = reverse('development:update_invoice', args=(self.invoice.pk,))
the_url = 'http://localhost:8000' + reverse('development:update_invoice', args=(self.invoice.pk,))
# Creating a client:
self.response = self.client.get(the_url, follow=True)
def test_url(self):
''' Ensure that the url works '''
self.assertEqual(self.response.status_code, 200)
I have made sure only one test is run using so there is no sharing of the data between different testcases that would throw Django off:
python manage.py test project.tests.test_views.UpdateViewTestCase
I get the the following error message:
IntegrityError: duplicate key value violates unique constraint "development_developmentproject_project_id_key"
DETAIL: Key (project_id)=(1) already exists
I also tried using mommy.make to create project, but I got the same error message. I also tried to specifically assign non-existent ids to the Project creation line, but could not convince Django to stop complaining.
So, Project is being created twice, but I cannot figure out why and where. Any help is much appreciated!
It turned out that I've used signals which created an instance already and I was creating the same instance in my setUpTestData again. The solution was to avoid creating a duplicate instance or simply use get_or_create instead of create or mommy.make
I have the following django models in my Document app
class Section(models.Model):
choices = (
('Haematology', 'Haematology'),
('BloodBank', 'BloodBank'),
('Bacteriology', 'Bacteriology'),
('Parasitoloty', 'Parasitoloty'),
('Chemistry', 'Chemistry'),
('Histopathology', 'Histopathology'),
('Serology', 'Serology'),
('Immunology', 'Immunology'),
)
title = models.CharField(max_length = 50, choices = choices)
class Meta:
verbose_name = "Section"
verbose_name_plural = "Sections"
def __str__(self):
return str(self.title)
class Document(models.Model, instance):
documentSection = models.ForeignKey(Section)
category = models.ForeignKey(DocumentCategory)
title = models.CharField(max_length = 100, default = '')
description = models.TextField(null = True, blank = True, default = '')
documentFile = models.FileField(upload_to = 'uploads/' + instance.documentSection.title)
fileFormat = models.ForeignKey(FileFormat)
uploaded = models.DateField(auto_now_add=True, default=timezone.now)
modified = models.DateTimeField(auto_now=True, default=timezone.now)
uploaded_by = models.ForeignKey(User)
def __str__(self):
return str(self.title)
When i upload Documents i want then to be saved in a folder like 'uploads/documentSection/
or 'uploads/documentSection/%Y/%m/
My problem is i cant figure out how to take the value of the documentSection and parse it to upload_to = 'uploads/documentSection/
I have a model:
class Inventory(models.Model):
title = models.CharField(max_length=100, db_index=True)
product_code = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
description = models.TextField()
cost_ea = models.DecimalField(max_digits=6, decimal_places=2)
cost_ws = models.DecimalField(max_digits=6, decimal_places=2)
quantity = models.IntegerField()
main_image = models.ImageField(upload_to = 'inventory/images/main/', null = True, blank = True)
thumb_image = models.ImageField(upload_to = 'inventory/images/thumbs/', null = True, blank = True)
product_category = models.ForeignKey('inventory.Product_Type')
card_category = models.ForeignKey('inventory.Card_Type')
last_modified = models.DateTimeField(auto_now = True, auto_now_add = True, null = True, blank = True, editable = True)
created = models.DateTimeField(auto_now_add = True, null = True, blank = True, editable = True, default = datetime.datetime.now())
in_stock = models.BooleanField(default = False)
I'd like create a form field something like this (it will be on an intermediate page of an admin action):
form.ChoiceField(choices=Inventory.get_all_verbose_names)
Is there a function that exists to get all verbose names from a model? and if not, how can I go about doing this?
You could try something like
forms.ChoiceField(choices=((f.name, f.verbose_name) for f in Inventory._meta.fields))
Hey i have looked around through some simliar posts here on SO but havent found anything that has solved my problem. I have the following models,
from django.db import models
class Areas(models.Model):
name = models.CharField(max_length = 120)
order_in_sidebar_network = models.IntegerField(blank=True, null=True)
order_in_section_network = models.IntegerField(blank=True, null=True)
def __unicode__ (self):
return self.area_name
class Meta:
verbose_name_plural = "Areas"
verbose_name = "Area"
class Countries(models.Model):
name = models.CharField(max_length = 120, help_text = "The name of the country")
area = models.ForeignKey(Areas, verbose_name = 'Area')
def __unicode__ (self):
return self.name
class Meta:
verbose_name_plural = "Countries"
verbose_name = "Country"
ordering = ['name']
class Offices(models.Model):
country = models.ForeignKey(Countries, verbose_name = 'Country')
name = models.CharField(max_length = 255, help_text = "The name of this office, IE London")
main_office = models.BooleanField(default= False, help_text = "Is this office a key location?", verbose_name = "Key Location")
address_1 = models.CharField(max_length = 255, null = True, blank = True)
address_2 = models.CharField(max_length = 255, null = True, blank = True)
address_3 = models.CharField(max_length = 255, null = True, blank = True)
city = models.CharField(max_length = 255, null = True, blank = True)
postcode = models.CharField(max_length = 20)
tel = models.CharField(max_length = 30, null= True, blank = True, help_text = "Optional telephone contact number")
mobile = models.CharField(max_length = 30, null= True, blank = True, help_text = "Optional mobile contact number")
fax = models.CharField(max_length = 30, null= True, blank = True, help_text = "Optional fax contact number")
data_1 = models.CharField(max_length = 255, null = True, blank = True, help_text = "Optional additional data", verbose_name = "Additional information")
data_2 = models.CharField(max_length = 255, null = True, blank = True, help_text = "Optional additional data", verbose_name = "Additional information")
class Meta:
verbose_name_plural = "Offices"
verbose_name = "Office"
ordering = ['name']
def __unicode__(self):
return self.name
class OfficeMembers(models.Model):
name = models.CharField(max_length = 60, help_text = "Please tell us this person name")
title = models.CharField(max_length = 100, help_text = "The person's title, IE Managing Director")
email = models.EmailField(max_length = 255, null = True, blank = True, help_text = "Optional email address for this person")
email2 = models.EmailField(max_length = 255, null = True, blank = True, help_text = "Optional second email address for this person")
phone = models.CharField(max_length = 30, null = True, blank = True, help_text = "Optional contact number for this person")
mobile = models.CharField(max_length = 30, null = True, blank = True, help_text = "Optional mobile contact number for this person")
office = models.ForeignKey(Offices, null = True)
class Meta:
verbose_name_plural = "Office Memebers"
verbose_name = "Office memebr"
ordering = ['name']
def __unicode__(self):
return self.name
i have the following view set up
def index(request):
cache_key = "world_areas"
cache_time = 60
world_areas_cache = cache.get(cache_key)
#if no cache is set, grab the objects, and set the cache
logger.debug(world_areas)
if not world_areas_cache:
logger.info('No cache found grabbing objects')
world_areas = Areas.objects.select_related().all()
#cache.set(cache_key, world_areas, cache_time)
logger.debug(world_areas)
else:
logger.info("Getting from cache")
world_areas = world_areas_cache
return render_to_response('network/index.html', {'world_areas':world_areas}, context_instance=RequestContext(request))
trying to iterate over the world_areas object like so
{% for area in world_areas %}
produces a template syntax error
'RelatedManager' object is not iterable
Any one got any ideas why this is happeing? really cant seem to get round this! strangley this is working for me in shell :S am i missing something obvious???
Big thanks to anyone able to help!
Call all() to retrieve the elements from the manager.
{% for area in world_areas.all %}
In general, it is better practice to use a values or values_list to pass data from a queryset to a template.
world_areas = Areas.objects.select_related().all().values_list('name', 'order_in_sidebar_network', ...)
Check out the Django docs for info on how to use the values function if you haven't used it before.
I run into this issue by a reckless mistake:
for physicalserver in task.physicalservers:
physicalserver.relieve_task()
The task.physicalservers is RelatedManager object, in my case I should get the task's physicalservers, there should add .all().
for physicalserver in task.physicalservers.all():
You have to iterate over set to get values related to a fk in a model.
class Area(models.Model):
name = models.CharField(max_length = 120)
order_in_sidebar_network = models.IntegerField(blank=True, null=True)
order_in_section_network = models.IntegerField(blank=True, null=True)
class CountryArea(models.Model):
name = models.CharField(max_length = 120)
area = models.ForeignKey(Area, verbose_name = 'Area')
## Assuming you have an object; area
## To get the all the counties related to that area you can do;
{% for obj in area.countryarea_set.all %}
<h4> {{ obj.name }} </h4>
{% endfor %}