I'm using Model forms to add a row to a table in Django,
here are my views and forms file
views.py
def add_ad_mod(request):
current_user = request.user
current_ip = get_client_ip(request)
selected = Temp.objects.filter(created_by_ip=current_ip).order_by('-created_at')[0]
selected_category = selected.cat
selected_town = selected.town
if request.method == 'POST':
add_ad_mod_form = AddAdModForm(request.POST, request.FILES, cat=selected_category, loc=selected_town)
if add_ad_mod_form.is_valid():
model_instance = add_ad_mod_form.save(commit=False)
model_instance.created_by = current_user.email
model_instance.category = selected_category
model_instance.town=selected_town
if request.user.is_superuser:
model_instance.is_active = True
else:
model_instance.is_active = False
add_ad_mod_form.save()
return redirect('dashboard')
else:
add_ad_mod_form = AddAdModForm(cat=selected_category, loc=selected_town)
context = {
'add_ad_mod_form': add_ad_mod_form,
'selected_category': selected_category,
'selected_town': selected_town,
}
return render(request, 'add_ad_mod.html', context)
I am using views.py to send a variable as you see to the form itself
forms.py
class AddAdModForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
current_categ = kwargs.pop('cat')
current_loc = kwargs.pop('loc')
super(AddAdModForm, self).__init__(*args, **kwargs)
self.fields['sub_category'] = forms.ModelChoiceField(label="Sniffer", queryset=SubCate.objects.filter(main_category=current_categ))
self.fields['sub_location'] = forms.ModelMultipleChoiceField (widget=forms.CheckboxSelectMultiple,label="Sniffer", queryset=SubLoc.objects.filter(main_town=current_loc))
title = forms.CharField(
widget=forms.TextInput(
attrs={
'placeholder': 'Ad Title here',
'style': 'width: 100%; max-width: 800px;'
}
)
)
description = forms.CharField(
widget=forms.Textarea(
attrs={
'placeholder': 'Ad description is here',
'style': 'width: 100%; max-width: 800px;'
}
)
)
image = forms.ImageField(required=True)
image2 = forms.ImageField(required=False)
image3 = forms.ImageField(required=False)
image4 = forms.ImageField(required=False)
image5 = forms.ImageField(required=False)
address = forms.CharField(max_length=100,
widget=forms.Textarea(
attrs={
'placeholder': 'Detailed Address is here ',
'style': 'width: 100%; max-width: 800px;'
}
)
)
class Meta:
model = Item
fields = ['title', 'sub_category', 'price', 'description', 'sub_location', 'address', 'image', 'image2', 'image3', 'image4',
'image5', 'phone']
And here is my models.py file:
class Category(models.Model):
category_name = models.CharField(max_length=60)
def __str__(self):
return self.category_name
class Town(models.Model):
town_name = models.CharField(max_length=300)
def __str__(self):
return self.town_name
class SubCate(models.Model):
sub_category_name = models.CharField(max_length=100)
main_category = models.ForeignKey(Category, on_delete=CASCADE)
def __str__(self):
return self.sub_category_name
class SubLoc(models.Model):
sub_location_name = models.CharField(max_length=100)
main_town = models.ForeignKey(Town, on_delete=CASCADE)
def __str__(self):
return self.sub_location_name
class Item(models.Model):
category = models.ForeignKey(Category, on_delete=CASCADE)
sub_category = models.ManyToManyField(SubCate)
title = models.CharField(max_length=250)
description = models.TextField(max_length=1200)
price = models.IntegerField(default=0)
town = models.ForeignKey(Town, on_delete=CASCADE)
sub_location = models.ManyToManyField(SubLoc)
address = models.TextField(max_length=100)
image = models.ImageField(upload_to='media/', null=False, blank=False)
image2 = models.ImageField(upload_to='media/', null=True, blank=True)
image3 = models.ImageField(upload_to='media/', null=True, blank=True)
image4 = models.ImageField(upload_to='media/', null=True, blank=True)
image5 = models.ImageField(upload_to='media/', null=True, blank=True)
created_by = models.CharField(max_length=600)
created_at = models.DateField(auto_now=True)
phone = models.IntegerField(default=0)
is_active = models.BooleanField(default=False)
is_deleted = models.BooleanField(default=False)
def __str__(self):
return self.title
Despite the items is added to the database and if I reloaded my website I can see the item posted - it gives me the error instead of redirecting normally (The error is not in the page user redirected to after submitting, as I can browse into it normally )
Traceback:
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\lito\Desktop\DJ\JEHLUM - Copy - Copy\web_site\views.py" in add_ad_mod
219. add_ad_mod_form.save()
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in save
457. self._save_m2m()
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in _save_m2m
439. f.save_form_data(self.instance, cleaned_data[f.name])
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related.py" in save_form_data
1619. getattr(instance, self.attname).set(data)
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py" in set
947. objs = tuple(objs)
Exception Type: TypeError at /add_ad/mod/
Exception Value: 'SubCate' object is not iterable
As I mentioned in the comments, it looks like both of these fields should be multiple choice, since they are both representing ManyToManyFields in the model.
self.fields['sub_category'] = forms.ModelMultipleChoiceField(label="Sniffer", queryset=SubCate.objects.filter(main_category=current_categ))
self.fields['sub_location'] = forms.ModelMultipleChoiceField (widget=forms.CheckboxSelectMultiple,label="Sniffer", queryset=SubLoc.objects.filter(main_town=current_loc))
Also as mentioned, you need to call save on the model instance, and save_m2m on the form:
if add_ad_mod_form.is_valid():
model_instance = add_ad_mod_form.save(commit=False)
...
model_instance.save()
add_ad_mod_form.save_m2m()
return redirect('dashboard')
Related
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.
I'm creating an ebay style website that auctions off items. I have a form that takes in the values for the listing required by the model. The form renders well but when I submit the form I get the error:
<class 'TypeError'> views.py 80 ("l = Listing(title=title, description=description, url=url, user=user_id, category=category)")
forms.py
class NewListingForm(forms.Form):
title = forms.CharField(max_length=200)
description = forms.CharField(max_length=500)
url = forms.URLField()
bid = forms.DecimalField(decimal_places=2, max_digits=10)
category = forms.ModelChoiceField(queryset=Category.objects.all())
views.py
** added around line that's throwing the error
def newListing(request):
try:
if request.method == "POST":
newListingForm = NewListingForm(request.POST)
if newListingForm.is_valid():
title = newListingForm.cleaned_data['title']
description = newListingForm.cleaned_data['description']
url = newListingForm.cleaned_data['url']
bid = newListingForm.cleaned_data['bid']
category = newListingForm.cleaned_data['category']
current_user = request.user
user_id = current_user.id
**l = Listing(title=title, description=description, url=url, user=user_id, category=category)**
l.save()
b = Bid(price=bid, bid_count=0)
b.listing.add(l)
b.save()
return HttpResponseRedirect(reverse("index"))
else:
newListingForm = NewListingForm()
return render(request, "auctions/newListing.html", {
'form': newListingForm
})
except Exception as exc:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
newListingForm = NewListingForm()
return render(request, 'auctions/newListing.html', {
'form': newListingForm
})
models.py
class Listing(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=500)
url = models.URLField()
user = models.ForeignKey('User', on_delete=models.CASCADE, name='author')
category = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="")
def __str__(self):
return f'{self.id}: {self.title}'
class Bid(models.Model):
price = models.DecimalField(decimal_places=2, max_digits=10)
bid_count = models.IntegerField()
listing = models.ForeignKey('Listing', on_delete=models.CASCADE, name='listing', default="")
def __str__(self):
return f'{self.slug} ({self.price})'
User is a keyword, so I was getting an error from that.
I have a webapp where we can create communities with django as a backend, but when i try to send a POST to create a community, I get:
community_configuration: ["Incorrect type. Expected pk value, received str."]
My POST:
{
title: knkn kn .k jbjnmn,
logo: [object File],
is_active: true,
description: test,
welcome_message: Welcome message,
org_id: 114,
community_configuration: About us,Community news,FAQs,Supporters,Resources,
}
Here are my serializers:
class MicroConfigurationSerializer(serializers.ModelSerializer):
class Meta:
model = MicroConfiguration
fields = [
'name',
]
def to_representation(self, instance):
return instance.name
class CommunityConfigurationSerializer(serializers.ModelSerializer):
micro_configurations = MicroConfigurationSerializer(many=True, read_only=True)
class Meta:
model = CommunityConfiguration
fields = '__all__'
class CommunitySerializer(serializers.ModelSerializer):
logo = serializers.SerializerMethodField()
organisation = serializers.SerializerMethodField()
community_configuration = CommunityConfigurationSerializer()
class Meta:
model = Community
fields = (
...
etcetc
...
)
Heres my model:
class MicroConfiguration(core_models.BaseModel):
name = models.CharField(max_length=32, unique=True)
permissions = models.ManyToManyField(Permission)
def __str__(self):
return self.name
class CommunityConfiguration(core_models.BaseModel):
name = models.CharField(max_length=32)
micro_configurations = models.ManyToManyField(MicroConfiguration)
permission_group = models.ForeignKey(
Group,
on_delete=models.SET_NULL,
null=True
)
def __str__(self):
return self.name
class Community(core_models.BaseModel):
accounts = models.ManyToManyField(
settings.AUTH_USER_MODEL,
through='associates.AccountCommunity',
through_fields=('community', 'account')
)
goals = models.ManyToManyField(Goal, through='associates.CommunityGoal')
type = models.ManyToManyField(CommunityType, through='CommunityAttribute')
communities = models.ManyToManyField(
'self',
through='associates.CommunityCommunity',
symmetrical=False,
)
crossposts = models.ManyToManyField(
Action,
through='activities.CommunityCrosspost',
through_fields=('community', 'action'),
related_name='communities',
)
title = models.CharField(max_length=64)
logo = models.ImageField(null=True, blank=True)
intro_media = models.ForeignKey(
'associates.MediaStore',
null=True,
on_delete=models.SET_NULL
)
website_url = models.CharField(max_length=256, blank=True)
is_invite_only = models.BooleanField(default=False)
description = models.TextField(blank=True)
intro_message = models.TextField(blank=True)
welcome_message = models.TextField(blank=True)
signup_autojoin = models.BooleanField(default=False)
community_configuration = models.ForeignKey(
CommunityConfiguration,
default=1,
null=True,
on_delete=models.SET_NULL,
help_text='Do not edit directly, create a new custom config instead, \
as it is reference by difference community.',
)
objects = models.Manager()
associates = AssociationManager()
#property
def url(self):
return reverse(
'communities:detail',
kwargs={
'id': self.id,
}
)
class Meta:
verbose_name = 'Community'
verbose_name_plural = 'Communities'
def __str__(self):
return self.title
Here's my views:
class CommunityCreateAPIView(CreateAPIView):
serializer_class = CommunityCreateSerializer
def create(self, request, **kwargs):
organisation_id = request.data.get('org_id')
micro_configurations_qd = request.data.copy()
micro_configurations = micro_configurations_qd.pop('community_configuration', False)
if micro_configurations:
micro_configurations = micro_configurations[0].split(',')
user = request.user
data = {}
permitted = AccountOrganisation.objects.filter(
account=user,
organisation_id=organisation_id,
is_active=True,
association__permissions__codename='add_community',
).exists()
if not permitted and not request.user.is_superuser:
data['message'] = 'Action not allowed'
return Response(
data=data,
status=status.HTTP_400_BAD_REQUEST,
)
response = super().create(request, **kwargs)
if response.status_code == 400:
data['message'] = 'Failed to update community'
return Response(
data=data,
status=status.HTTP_400_BAD_REQUEST,
)
community_id = response.data.get('id')
OrganisationCommunity.objects.create(
community_id=community_id,
organisation_id=organisation_id,
)
association = Group.objects.get(name='Community Admin')
AccountCommunity.objects.create(
community_id=community_id,
account=user,
association=association,
)
if micro_configurations:
com_config_qs = CommunityConfiguration.objects.filter(
micro_configurations__name__in=micro_configurations
).annotate(
num_micro_config=Count('micro_configurations__name')
).filter(
num_micro_config=len(micro_configurations)
)
community_configuration = None
if micro_configurations:
for com_config in com_config_qs:
micro_config_count = com_config.micro_configurations.count()
if micro_config_count == len(micro_configurations):
community_configuration = com_config
break
if community_configuration:
Community.objects.filter(
pk=community_id
).update(
community_configuration=community_configuration
)
elif micro_configurations:
micro_qs = MicroConfiguration.objects.filter(
name__in=micro_configurations
)
community_config = CommunityConfiguration.objects.create(
name='Custom'
)
community_config.micro_configurations.set(micro_qs)
community_config.save()
Community.objects.filter(
pk=community_id
).update(
community_configuration=community_config
)
return response
I've been stuck with this for hours, any help?
Your serializer expects a pk (or id) of the community_configuration instance.
basically you have it set up so that you need to create a community_configuration entry first, then fetch the id of the new created entry and use that id when creating your community.
If you want to have the community_configuration instance to be created while creating the community then an option to do that would be to override the create method in the serializer and extract the community_configuration data then create a new entry for that model and use it, something like this
class CommunitySerializer(serializers.ModelSerializer):
# .. put your serializer code here
def create(self, validated_data):
community_configuration= validated_data.pop('community_configuration')
config_instance, created = CommunityConfiguration.objects.get_or_create(<community_configuration>) # modify this however you need to create the CommunityConfiguration instance
community_instance = community.objects.create(**validated_data, community_configuration=config_instance)
return community_instance
you will need to probably modify the code for it to follow your needs.
I didn't read all of your models, not sure how you are gonna create the nested models from the input value but you get the point.
Hi? I'm new to web development can you plz help me whats the problem with my file?
I don't know why is this, I have defined my category model properly and imported it. I have also defined book_category. Im stuck
views.py: the error is found here
class AddBookIndexView(View):
def get(self, request):
booksQS = Books.objects.all()
authorsQS = Author.objects.all()
categoryQS = Category.objects.all()
print(authorsQS)
print(categoryQS)
print(booksQS)
return render(request, 'addbook.html')
def post(self, request):
form = BooksForm(request.POST, request.FILES)
if form.is_valid():
book_category = request.POST.get('book_category')
firstname = request.POST.get('Firstname')
lastname = request.POST.get('Lastname')
author = Author.objects.filter(Q(firstname__icontains = firstname) & Q(lastname__icontains = lastname))
if author:
print(author)
else:
form = AuthorForm(firstname= firstname, lastname=lastname)
form.save()
category = Category.objects.filter(Q(book_category__icontains = book_category))
if category:
print(category)
else:
form = CategoryForm(book_category= book_category)#this is where the error
form.save()
author = Author.objects.filter(Q(firstname__icontains = firstname) & Q(lastname__icontains = lastname))
category = Category.objects.filter(Q(book_category__icontains = book_category))
for a in author:
print(a.book_author_id)
for c in category:
print(c.book_category_no)
book_title = request.POST.get('book_title')
book_cover = request.FILES.get('book_cover')
book_file = request.FILES.get('book_file')
book_year = request.POST.get('book_year')
book_tags = request.POST.get('book_tags')
book_summary = request.POST.get('book_summary')
form = Books(book_title = book_title, book_author_id = Author.objects.get(book_author_id = a.book_author_id), book_cover = book_cover,
book_file = book_file, book_year = book_year, book_summary = book_summary, book_category_no = Category.objects.get(book_category_no = c.book_category_no),
is_bookmarked = 0, is_downloaded = 0, is_read = 0, is_deleted = 0)
form.save()
return HttpResponse('Book Saved!')
else:
print(form.errors)
return HttpResponse('Not Valid')
This is what my models.py looks like:
from django.db import models
from django.utils import timezone
class Category(models.Model):
# book_category_no = models.CharField(primary_key=True, max_length=50)
book_category_no = models.AutoField(primary_key=True)
book_category = models.CharField(max_length=100)
class Meta:
db_table = "Category"
class Books(models.Model):
# book_id = models.CharField(primary_key=True, max_length=50)
book_id = models.AutoField(primary_key=True)
book_title = models.CharField(max_length = 100)
book_author_id = models.ForeignKey(Author, on_delete=models.CASCADE)
book_cover = models.ImageField(upload_to='media/')
book_file = models.FileField(upload_to='media/')
book_year = models.DateField()
book_tags = models.CharField(max_length = 100)
book_summary = models.CharField(max_length = 100)
book_category_no = models.ForeignKey(Category, on_delete=models.CASCADE)
date_added = models.DateField(default=timezone.now)
# book_info = models.CharField(max_length = 100, default="")
is_bookmarked = models.BooleanField()
is_downloaded = models.BooleanField()
is_read = models.BooleanField()
is_deleted= models.BooleanField(default=False)
class Meta:
db_table = "Books"
Traceback
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py" in dispatch
97. return handler(request, *args, **kwargs)
File "C:\ARMS\projectarms\arms\views.py" in post
315. form = CategoryForm(book_category= book_category)
Exception Type: TypeError at /arms/addbook/
Exception Value: init() got an unexpected keyword argument 'book_category'
`
Most certainly your Category or CategoryForm model is missing a field book_category which you use here:
category = Category.objects.filter(Q(book_category__icontains = book_category))
I want to make simple blog with posts and tags, but i have a problem with adding tags from ModelMultipleChoiceField... after calling .is_valid(), cleaned_data should have selected tags but instead it is None.
print(form.cleaned_data)
returns:
{'description': u'xyz', 'title': u'xyz', 'haslo': u'', 'tags': None}
I have tried to change it to simple ChoiceField with initial choices from table but with same result.
My models:
class Tag(models.Model):
nazwa = models.CharField(max_length=24)
def __str__(self):
return self.nazwa
def __unicode__(self):
return self.nazwa
class Post(models.Model):
tytul = models.CharField(max_length=200)
skrocona_tresc = models.CharField(max_length=350, blank=True)
tresc = models.TextField(blank=True)
haslo = models.CharField(max_length=24, blank=True)
data = models.DateTimeField(auto_now=False, auto_now_add=True)
id_user = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.ManyToManyField(Tag)
Form:
class PostAddForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}),required=False)
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}),required=False)
description = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}),required=False)
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all(), required=False)
class Meta:
model = Post
fields = [
'title',
'password',
'description',
'tags'
]
and view:
def add_post(request):
forma_PA = PostAddForm(request.POST or None)
if request.is_ajax():
if forma_PA.is_valid():
post = forma_PA.save(commit=False)
post.tresc = request.POST.get('html')
post = Post(tytul=forma_PA.cleaned_data.get('title'),
id_user_id=request.user.id,
skrocona_tresc=forma_PA.cleaned_data.get('description'),
tresc=request.POST.get('html'),
haslo=forma_PA.cleaned_data.get('password'),
)
post.save()
tagi = forma_PA.cleaned_data['tags']
print(forma_PA.cleaned_data)
if(tagi):
post.tags.add(tagi)
context = {
'form': forma_PA
}
return render(request, 'Blog/add_post.html', context)
i am just starting with Django ;/