Django How to add a default Variation when creating a new Item - python

I have created a an item model with variation and variation Manager model.
I want to add a default variation function so that when I create a new item a default of size variations is created small medium and large.
I edited the question by adding a Signal but getting an error so I trying to reach somewhere now I'm getting name 'created' is not defined
Here is the model:
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.DecimalField(decimal_places=2, max_digits=100)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField(unique=True)
image = models.ImageField(blank=False, upload_to='')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("core:product", kwargs={
'slug': self.slug
})
class VariationManager(models.Manager):
def all(self):
return super(VariationManager, self).filter(active=True)
def sizes(self):
return self.all().filter(category='size')
def colors(self):
return self.all().filter(category='color')
VAR_CATEGORIES = (
('size', 'size',),
('color', 'color',),
('package', 'package'),
)
class Variation(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
category = models.CharField(
max_length=120, choices=VAR_CATEGORIES, default='size')
title = models.CharField(max_length=120)
price = models.DecimalField(
decimal_places=2, max_digits=100, null=True, blank=True)
objects = VariationManager()
active = models.BooleanField(default=True)
def __str__(self):
return self.title
#receiver(post_save, sender=Item)
def add_default_Variant(sender, instance, **kwargs):
small_size, size = Variation.objects.get_or_create(
title='Small', item=instance)
medium_size, size = Variation.objects.get_or_create(
title='Medium', item=instance)
large_size, size = Variation.objects.get_or_create(
title='Large', item=instance)
if created:
instance.save()
print(f"default variant created : {variant}")

you can use signals to add what you want DOCS
from django.db.models.signals import post_save
from django.dispatch import receiver
this signal will create a new variant each time you save a new item
you can put in models.py or follow the docs to set it in a separated .py file
#receiver(post_save, sender=Item)
def add_default_Variant(sender, instance, **kwargs):
variant= Variation.objects.create(title="default variant title",item=instance)
Adding your variants
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=Item)
def add_default_Variant(sender, instance, **kwargs):
small_size = Variation.objects.create(product=instance, category='size', title='Small')
medium_size = Variation.objects.create(product=instance, category='size', title='Medium')
large_size = Variation.objects.create(product=instance, category='size', title='Large')

Related

Setup UpdateView in Django with a form that has the __init__ method configured

When I use UpdateView in Django with a form that has the __init__ method configured to customize the ModelMultipleChoiceField querysets do not load the initial values of the instance?
Some context first, I find myself making an application that manages documents associated to subportals, for that each subportal has associated Service Groups and Dependencies.
I need that when a document is loaded, it can be categorized by Service Groups and Dependencies that are only associated to the subportal. I achieved this by using the __init__ method in the forms.
The problem is that when I need to update the document data, the initial values of the model do not appear.
I show the codes
Models.py
class ServiceGroup(models.Model):
subportal = models.ForeignKey(Subportal, null=True, blank=True, on_delete=models.CASCADE)
title = models.CharField(max_length=150, null=False, blank=False)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Dependence(models.Model):
subportal = models.ForeignKey(Subportal, null=True, blank=True, on_delete=models.CASCADE)
title = models.CharField(max_length=150, null=False, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class SubportalDocument(models.Model):
def get_upload_to(instance, filename):
return '{}/documents/{}'.format(instance.subportal.title, filename)
subportal = models.ForeignKey(Subportal, null=True, blank=True, on_delete=models.CASCADE)
showcategory = models.OneToOneField(ShowCategory, null=True, blank=True, on_delete=models.CASCADE)
title = models.CharField(max_length=150, null=False, blank=False)
file = models.FileField(upload_to=get_upload_to, null=False, blank=False)
review_date = models.DateField(null=False, blank=True)
review_nro = models.IntegerField(null=False, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
dependences = models.ManyToManyField(Dependence, related_name='dependencesdoc', blank=True)
servicegroups = models.ManyToManyField(ServiceGroup, related_name='servicegroupsdoc', blank=True)
def __str__(self):
return self.title
Forms.py
class SubportalDocumentForm(forms.ModelForm):
class Meta:
model = SubportalDocument
exclude = ['subportal', 'created_at', 'status']
labels = {
'showcategory':'Categoría de Despliegue:',
'title':'Nombre del Documento:',
'file':'Cargar el archivo:',
'review_nro':'Número de Revisión:',
'review_date':'Fecha de Revisión:',
}
widgets = {
'showcategory':forms.Select(attrs={'class':'form-select'}),
'title':forms.TextInput(attrs={'class':'form-control'}),
'file':forms.FileInput(attrs={'class':'form-control'}),
'review_nro': forms.NumberInput(attrs={'class':'form-control'}),
'review_date': forms.DateInput(format=('%d/%m/%Y'),
attrs={'class':'form-control',
'type':'date'}),
}
servicegroups = forms.ModelMultipleChoiceField(
label='Grupos de Servicios:',
queryset=None,
widget=forms.CheckboxSelectMultiple,
)
dependences = forms.ModelMultipleChoiceField(
label='Dependencias:',
queryset=None,
widget=forms.CheckboxSelectMultiple,
)
def __init__(self, *args, **kwargs):
self.subportal = kwargs.pop('subportal')
super(SubportalDocumentForm, self).__init__(*args, **kwargs)
self.fields['servicegroups'].queryset = ServiceGroup.objects.filter(
subportal=self.subportal)
self.fields['dependences'].queryset = Dependence.objects.filter(
subportal=self.subportal)
self.fields['showcategory'].queryset = ShowCategory.objects.filter(
subportal=self.subportal)
self.fields['servicegroups'].widget.attrs.update({
'class': 'form-check-input',
})
self.fields['dependences'].widget.attrs.update({
'class': 'form-check-input',
})
Views.py
class SubportalDocumentUpdateView(UpdateView):
model = SubportalDocument
form_class = SubportalDocumentForm
template_name = 'portal_manager/create_document.html'
def get_form_kwargs(self, *args, **kwargs):
subportal_id = self.get_object().subportal_id
subportal = get_object_or_404(Subportal, id=subportal_id)
kwargs = {
"subportal": subportal,
}
return kwargs
def dispatch(self, request, *args, **kwargs):
id = self.get_object().subportal_id
self.get_form().fields['servicegroups'].queryset = ServiceGroup.objects.filter(subportal_id=id)
self.get_form().fields['dependences'].queryset = Dependence.objects.filter(subportal_id=id)
return super(SubportalDocumentUpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
id = self.get_object().subportal_id
return reverse_lazy('portal_manager:admin_subportal', kwargs={'id': id})
Urls.py
path('modificar-documento/<int:pk>', views.SubportalDocumentUpdateView.as_view(), name='update_document'),
The result I get is this.
image of the form without the initial values:
Now, if I don't use the __init__ method in the forms to filter the Service Groups and Dependencies by subportal, I get the initial values.
forms.py not init
class SubportalDocumentForm(forms.ModelForm):
class Meta:
model = SubportalDocument
exclude = ['subportal', 'created_at', 'status']
labels = {
'showcategory':'Categoría de Despliegue:',
'title':'Nombre del Documento:',
'file':'Cargar el archivo:',
'review_nro':'Número de Revisión:',
'review_date':'Fecha de Revisión:',
}
widgets = {
'showcategory':forms.Select(attrs={'class':'form-select'}),
'title':forms.TextInput(attrs={'class':'form-control'}),
'file':forms.FileInput(attrs={'class':'form-control'}),
'review_nro': forms.NumberInput(attrs={'class':'form-control'}),
'review_date': forms.DateInput(format=('%d/%m/%Y'),
attrs={'class':'form-control',
'type':'date'}),
}
servicegroups = forms.ModelMultipleChoiceField(
label='Grupos de Servicios:',
queryset=ServiceGroup.objects.all(),
widget=forms.CheckboxSelectMultiple,
)
dependences = forms.ModelMultipleChoiceField(
label='Dependencias:',
queryset=Dependence.objects.all(),
widget=forms.CheckboxSelectMultiple,
)
Ajust Views.py
class SubportalDocumentUpdateView(UpdateView):
model = SubportalDocument
form_class = SubportalDocumentForm
template_name = 'portal_manager/create_document.html'
def dispatch(self, request, *args, **kwargs):
id = self.get_object().subportal_id
self.get_form().fields['servicegroups'].queryset = ServiceGroup.objects.filter(subportal_id=id)
self.get_form().fields['dependences'].queryset = Dependence.objects.filter(subportal_id=id)
return super(SubportalDocumentUpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
id = self.get_object().subportal_id
return reverse_lazy('portal_manager:admin_subportal', kwargs={'id': id})
Image with the expected result but filtering the Service Groups and Dependencies:
If someone could help me or give me a clue about what is happening, I would appreciate it very much, I have been investigating for a long time and I can't get an answer.

Django Creating a new post, but it belongs to none

Creating a new checklist, the checklist get created but I have to go inn admin panel to set what task it belongs to. The task is a foreignkey in the checklist.
views.py
def project_detail(request, slug):
'''
Detailed view of given project
'''
context = {}
project = get_object_or_404(Project, slug=slug)
tasks = Task.objects.filter(task_completed=False, project=project)
context.update({'project': project})
checklist_form = ChecklistForm(request.POST or None)
if request.method == "POST":
# Create new Checklist
if 'save_new_checklist' in request.POST:
if checklist_form.is_valid():
print("\n\n New checklist form is valid")
author = Profile.objects.get(user=request.user)
new_checklist = checklist_form.save(commit=False)
new_checklist.user = author
new_checklist.tasks = tasks
new_checklist.save()
return redirect('project_detail', slug=slug)
context.update({
'tasks': tasks,
'checklist_form': checklist_form,
'title': tasks
})
return render(request, 'projects/tasks.html', context)
models.py
class Task(models.Model):
title = models.CharField(max_length=55, null=True, blank=True)
slug = models.SlugField(max_length=500, unique=True, blank=True)
task_completed = models.BooleanField(default=False)
description = models.TextField(default="Task description")
date = models.DateTimeField(auto_now_add=True)
due_date = models.DateTimeField()
project = models.ForeignKey(Project, blank=True, null=True, related_name='task', on_delete=CASCADE)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Task, self).save(*args, **kwargs)
def __str__(self):
return self.title
class Checklist(models.Model):
title = models.CharField(max_length=55)
slug = models.SlugField(max_length=500, unique=True, blank=True)
date = models.DateTimeField(auto_now_add=True)
due_date = models.DateTimeField()
check_completed = models.BooleanField(default=False)
description = models.TextField(default="Checklist description")
task = models.ForeignKey(Task, blank=True, null=True, related_name='checklist', on_delete=CASCADE)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Checklist, self).save(*args, **kwargs)
def get_url(self):
return reverse('task_detail', kwargs={
'slug':self.slug
})
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('projects/', teams, name='teams'),
path('projects/project/<slug>/', projects, name='projects'),
path('projects/tasks/<slug>/', project_detail, name='project_detail'),
path('projects/checklist/<slug>/', task_detail, name='task_detail'),
]
The form is valid, no errors, the new checklist is created, only that it should be automatically belong to the given task. And it does not, have to go admin panel and choose what task it belongs to.

django ecommerce product db design

I designed a database for my django ecommerce project but it have some problems, the goal of
the this design is to have products with different specifications for example a mobile cell has it's own properties and a television too,
it is my models.py:
'''
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from django.shortcuts import reverse
from model_utils import FieldTracker
from . import uploaders
class Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,
related_name='children')
slug = models.SlugField(max_length=75, unique=True)
tracker = FieldTracker(fields=['name'])
class MPTTMeta:
order_insertion_by = ['name']
def __str__(self):
category_names = [self.name]
node = self
while node.parent:
node = node.parent
category_names.append(node.name)
return ' / '.join(category_names[::-1])
def get_absolute_url(self):
return reverse('product_by_category', args=(self.slug,))
class ProductType(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class ProductSpecifications(models.Model):
name = models.CharField(max_length=50)
product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE,
related_name='specifications')
class Meta:
unique_together = ('name', 'product_type')
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100, unique=True)
product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE,
related_name='products')
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name='products')
price = models.PositiveBigIntegerField()
discount_price = models.PositiveBigIntegerField(null=True, blank=True)
description = models.TextField(null=True, blank=True)
image = models.ImageField(upload_to=uploaders.product_img_uploader)
slug = models.SlugField(max_length=150, unique=True)
tracker = FieldTracker(fields=['slug', 'name', 'product_type'])
def __str__(self):
return self.name
def set_discount(self, percentage):
self.discount_price = self.price * (1 - percentage)
self.save()
#property
def is_discounted(self):
return bool(self.discount_price)
def remove_discount(self):
self.discount_price = None
self.save()
class ProductSpecificationValue(models.Model):
specification = models.ForeignKey(ProductSpecifications, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE,
related_name='specifications')
value = models.CharField(max_length=75, null=True, blank=True)
def __str__(self):
return ''
class Meta:
unique_together = ('specification', 'product')
'''
And admin.py:
'''
from django.contrib import admin
from django.http import HttpResponseRedirect
from mptt.admin import MPTTModelAdmin
from .models import *
from .forms import ProductSpecForm
#admin.register(Category)
class CategoryAdmin(MPTTModelAdmin):
readonly_fields = ('slug',)
class SpecificationInline(admin.TabularInline):
model = ProductSpecifications
extra = 2
#admin.register(ProductType)
class ProductTypeAdmin(admin.ModelAdmin):
inlines = (SpecificationInline,)
class SpecificationValueInline(admin.TabularInline):
model = ProductSpecificationValue
# form = ProductSpecForm
# fields = ('specification', 'value')
# readonly_fields = ('specification',)
#
# def has_add_permission(self, request, obj):
# return False
#
# def has_delete_permission(self, request, obj=None):
# return False
#admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
inlines = (SpecificationValueInline,)
readonly_fields = ('slug',)
# def response_post_save_add(self, request, obj):
# return HttpResponseRedirect(
# reverse("admin:%s_%s_change" % (self.model._meta.app_label,
# self.model._meta.model_name), args=(obj.id,)))
'''
the problem is in product admin panel when you want to add or change a product, I want the select box for specification in SpecificationValueInline form show me only specifications related to the product type not all specifications in db, the lines that I commented in admin.py with some signals and a form was my approach to solve this issue i dont know if it was the best help me please!
signals.py:
'''
from django.dispatch import receiver
from django.db.models.signals import pre_save, post_save
from .models import Category, Product, ProductSpecificationValue, ProductSpecifications
#receiver(pre_save, sender=Product)
#receiver(pre_save, sender=Category)
def initialize_slug(sender, instance, *args, **kwargs):
if (not instance.slug) or (instance.tracker.has_changed('name')):
instance.slug = instance.name.replace(' ', '_')
#receiver(post_save, sender=Product)
def initialize_specifications(sender, instance, created, **kwargs):
if created:
product_type = instance.product_type
for specification in product_type.specifications.all():
ProductSpecificationValue.objects.create(product=instance,
specification=specification)
elif instance.tracker.has_changed('product_type'):
ProductSpecificationValue.objects.filter(product=instance).delete()
product_type = instance.product_type
for specification in product_type.specifications.all():
ProductSpecificationValue.objects.create(product=instance,
specification=specification)
#receiver(post_save, sender=ProductSpecifications)
def add_new_specs_to_related_products(sender, instance, created, **kwargs):
if created:
product_type = instance.product_type
for product in product_type.products.all():
ProductSpecificationValue.objects.create(specification=instance,
product=product)
'''
forms.py:
'''
from django import forms
from django.forms import ModelChoiceField
from .models import ProductSpecificationValue, Product
class ProductSpecForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if hasattr(self.instance, 'product'):
self.fields['specification'] = ModelChoiceField(
queryset=self.instance.product.product_type.specifications.all())
class Meta:
model = ProductSpecificationValue
fields = ('specification', 'value')
'''
you can use formfield_for_foreignkey in SpecificationValueInline
class SpecificationValueInline(admin.TabularInline):
model = ProductSpecificationValue
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "specification":
product_id = request.resolver_match.kwargs.get('object_id')
productType = Product.objects.get(id = product_id).product_type
kwargs["queryset"] = ProductSpecification.objects.filter(product_type=productType)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
mohsen ma answer was usefull I made some changes and it got better but I still doubt it it is enough or best practice, if user changes the product type he/she should stay on change page to fill the specification idk how:
'''
#receiver(post_save, sender=Product)
def sync_specs_with_type(sender, instance, created, **kwargs):
if created or instance.tracker.has_changed('product_type'):
if not created:
instance.specifications.all().delete()
for spec in instance.product_type.specifications.all():
ProductSpecificationValue.objects.create(product=instance, specification=spec)
class SpecificationValueInline(admin.TabularInline):
model = ProductSpecificationValue
extra = 0
def formfield_for_foreignkey(self, db_field, request, **kwargs):
product_id = request.resolver_match.kwargs.get('object_id')
if product_id and db_field.name == "specification":
product_type = Product.objects.get(id=product_id).product_type
kwargs["queryset"] = ProductSpecifications.objects.filter(product_type=product_type)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
#admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
readonly_fields = ('slug',)
inlines = (SpecificationValueInline,)
def response_post_save_add(self, request, obj):
messages.add_message(request, messages.INFO, 'set you product specifications')
return HttpResponseRedirect(
reverse("admin:%s_%s_change" % (self.model._meta.app_label, self.model._meta.model_name), args=(obj.id,)))
def get_inlines(self, request, obj):
if obj:
return super().get_inlines(request, obj)
return ()
'''

django-import-export : import not working

I am trying to populate my database with .csv files with django-import-export module but I keep running in this error
Line number: 1 - maximum recursion depth exceeded while calling a Python object 43, Sicilian, L, 0, 1,7, 45.7
whenever I try to populate my Pizza model through the admin UI.
Here is my CSV
admin.py
from django.contrib.admin import ModelAdmin
from import_export.admin import ImportExportModelAdmin
from .models import Topping, Pizza, Sub, Pasta, Salad, Dinner
class PizzaAdmin(ImportExportModelAdmin):
def save_related(self, request, form, formsets, change):
super(PizzaAdmin, self).save_related(request, form, formsets, change)
form.instance.toppings.add(Topping.objects.get(name='Cheese'))
#admin.register(Sub)
class SubAdmin(ImportExportModelAdmin):
pass
# Register your models here.
admin.site.register(Topping)
admin.site.register(Pizza, PizzaAdmin)
# admin.site.register(Sub)
admin.site.register(Pasta)
admin.site.register(Salad)
admin.site.register(Dinner)
models.py
from django.contrib import admin
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib.auth import get_user_model
# Create your models here.
class Topping(models.Model):
name = models.CharField(max_length=64)
def __str__(self):
return(f"{self.name}")
class Pizza(models.Model):
PIZZA_SIZES = (
('S', 'Small'),
('L', 'Large'),
)
pizza_type = models.CharField(max_length=64)
pizza_size = models.CharField(max_length=1, choices=PIZZA_SIZES)
qty_toppings = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)], default=0)
toppings = models.ManyToManyField(Topping, related_name='pizzas', blank=True)
price = models.FloatField(help_text="Price in $")
def __str__(self):
return f"Size: {self.get_pizza_size_display()}, Type: {self.pizza_type}, Number of Toppings: {self.qty_toppings}, Price: {self.price}, Toppings: {self.toppings.in_bulk()}"
def save(self, *args, **kwargs):
# if 'toppings' not in kwargs:
# kwargs.setdefault('force_insert', True)
# kwargs.setdefault('force_update', True)
super(Pizza, self).save(*args, **kwargs)
self.toppings.add(Topping.objects.get(name='Cheese'))
# kwargs.setdefault('toppings', Topping.objects.get(name='Cheese'))
class Sub(models.Model):
SUBS_SIZES = (
('S', 'Small'),
('L', 'Large'),
)
subs_size = models.CharField(max_length=1, choices=SUBS_SIZES)
name = models.CharField(max_length=64)
price = models.IntegerField(help_text="Price in $")
def __str__(self):
return f"{self.name}, {self.get_subs_size_display()} : {self.price}"
class Pasta(models.Model):
name = models.CharField(max_length=64)
price = models.IntegerField(help_text="Price in $")
def __str__(self):
return f"{self.name} : {self.price}"
class Salad(models.Model):
name = models.CharField(max_length=64)
price = models.IntegerField(help_text="Price in $")
def __str__(self):
return f"{self.name} : {self.price}"
class Dinner(models.Model):
DINNER_SIZES = (
('S', 'Small'),
('L', 'Large'),
)
dinner_size = models.CharField(max_length=1, choices=DINNER_SIZES)
name = models.CharField(max_length=64)
price = models.IntegerField(help_text="Price in $")
def __str__(self):
return f"{self.name}, {self.get_dinner_size_display()} : {self.price}"
class Euser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return(f"{self.id}")
class ShoppingCart(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
pizzas = models.ManyToManyField(Pizza)
subs = models.ManyToManyField(Sub)
pastas = models.ManyToManyField(Pasta)
dinners = models.ManyToManyField(Dinner)
number_of_articles = models.IntegerField(null=True)
price = models.DecimalField(max_digits=5, decimal_places=2, null=True)
def __str__(self):
return(f"{self.user}'s cart")
#receiver(post_save, sender=get_user_model())
def create_user_cart(sender, instance, created, **kwargs):
if created:
ShoppingCart.objects.create(user=instance)
# #receiver(post_save, sender=User)
# def create_user_cart(sender, instance, created, **kwargs):
# if created:
# ShoppingCart.objects.create(user=instance)
# #receiver(post_save, sender=User)
# def save_user_cart(sender, instance, **kwargs):
# instance.shoppingcart.save()
FYI: Used pandas to convert this same .csv to a .json, and I got KeyError encountered while trying to read file: pizza_sicilian.json
Any help will be greatly appreciated
i have faced the same issue
i would rather suggest you
in admin .py
#admin.register(Sub)
class SubAdmin(ImportExportModelAdmin):
list_display=["pizza","other objects in model"]
pass
list_display is a default function an the items should be in a list ...
this solved my issue , i think it will help many viewers!
Thnak you!

bypass validation for form field django

class PostForm(forms.ModelForm):
description = forms.CharField(widget=PagedownWidget(show_preview=False))
class Meta:
model = Post
fields = [
'title',
'image',
'video',
'description',
'public',
'tags',
]
I am trying to bypass the required field for 'video' but having difficulty doing so. Any suggestions would be appreciated.
this is my models.py, hopefully is should help with knowing how to go on this.
from django.db import models
from django.db.models import Count, QuerySet, F
from django.utils import timezone
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
from markdown_deux import markdown
from django.utils.safestring import mark_safe
from embed_video.fields import EmbedVideoField
from taggit.managers import TaggableManager
from comments.models import Comment
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 )
title = models.CharField(max_length=75)
slug = models.SlugField(unique=True)
video = EmbedVideoField()
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
description = models.TextField()
tags = TaggableManager()
public = models.BooleanField(default=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
class Meta:
ordering = ["-created", "-updated" ]
def get_markdown(self):
description = self.description
markdown_text = markdown(description)
return mark_safe(markdown_text)
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
from the docs it looks like it should support empty now since version 0.3, i would suggest trying
video = EmbedVideoField(null=True,blank=True)
the docs say it should function like a URL field, so just the standard notation should be all you need.
good luck!

Categories

Resources