im trying to update my model but it just creates another instance and i cant figure out why. i was under the impression that all i needed was:
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
and it would take care of it for me but that doesnt seem to be the case.
im in django 1.11 and running python 3.6. Any and all help is appreciated.
models.py
class Question(models.Model):
class Meta:
ordering = ['-date_updated']
# user = models.ForeignKey(User, related_name="question", default='')
question = models.TextField(unique=False, blank=False, null=False)
question_html = models.TextField(blank=False, null=False)
answer = models.TextField(blank=False, null=False)
answer_html = models.TextField(blank=False,null=False)
date_created = models.DateTimeField(auto_now=True, null=True)
date_updated = models.DateTimeField(auto_now=True, null=True)
def __str__(self):
return self.question
# ^ to display an object in the Django admin site and
# as the value inserted into a template when it displays an object.
def save(self, *args, **kwargs):
self.question_html = misaka.html(self.question)
self.answer_html = misaka.html(self.answer)
super().save(*args, **kwargs)
views.py
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
# fields = ('question', 'answer')
def edit_question(self, request, id):
question = get_object_or_404(Question, id=id)
form = QuestionForm(request.POST, instance=question)
if form.is_valid():
form.save()
forms.py
class QuestionForm(forms.ModelForm):
# your_name = forms.CharField(label='Your name', max_length=100)
class Meta:
fields = ("question", 'answer')
model = models.Question
urls.py
url(r'questionupdate/(?P<pk>\d+)/$', views.QuestionUpdate.as_view(), name='update'),
Related
i'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a "Direct assignment to the forward side of a many-to-many set is prohibited. Use product.set() instead." error
Bellow you can check the code
Models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=255, unique=True, )
description = models.TextField(max_length=1500)
class Meta:
verbose_name_plural = "categories"
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
nominal_price = models.PositiveIntegerField(verbose_name='prix normal',)
reduced_price = models.PositiveIntegerField(blank=True, null=True)
quantity = models.PositiveIntegerField(default=10)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png")
def __str__(self):
return self.name
class Customer(models.Model):
full_name = models.CharField(max_length=150)
address = models.CharField(max_length=1500, null=True)
phone = models.IntegerField()
city = models.CharField(max_length=100)
email = models.EmailField(null=True)
class Order (models.Model):
product = models.ManyToManyField(Product, through='OrderProduct')
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
class OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
Views.py
class ProductDetailView(FormMixin, TemplateView):
model = Product
template_name = 'product.html'
form_class = OrderForm
def get_success_url(self):
return reverse('index')
def post(self, request, *args, **kwargs):
context = self.get_context_data()
form = OrderForm(request.POST)
if context['form'].is_valid():
product = get_object_or_404(Product, name=self.kwargs['product_name'])
customer = form.save()
Order.objects.create(product=product, customer=customer)
return super(TemplateView, self)
def get_context_data(self, **kwargs):
context = super(ProductDetailView, self).get_context_data(**kwargs)
context['product'] = Product.objects.get(name=self.kwargs['product_name'])
context['form'] = self.get_form()
return context
urls.py
path('', views.ProductListView.as_view(), name='index'),
Did i missed something
For handling many-to-many relations, you cannot directly set the product from Order. Also you would need to create the order first before you can set or add a product:
order = Order.objects.create(customer=customer)
order.product.add(product)
I would like to list out the comments on my Post Detail page and wanted to see how I can connect a view to the specific comments for a given post?
Models.py
class Post(models.Model):
owner = models.ForeignKey(
Profile, null=True, blank=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200)
body = models.TextField()
Post_image = models.ImageField(
null=True, blank=True, default='default.jpeg')
create_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post', kwargs={'pk': self.pk})
class Meta:
ordering = ['-create_date']
class Comment(models.Model):
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
text = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
Views.py
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comment_list'] = Post.comment_set.all()
return context
You can access the detail object of the DetailView with self.object:
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comment_list'] = self.object.comment_set.order_by('create_date')
return context
I have this Model that has a foreign Key. I want anytime a user if filling the form, Only the data entered by the user in the foreign key model should be shown to him as a dropdown.
Model.py
class Nomination(models.Model):
fullname = models.CharField(max_length=120)
nominee_id = models.CharField(max_length=100, default=increment_invoice_number, null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image = models.ImageField(upload_to='nominations_images')
slug = models.SlugField(max_length=150, blank=True)
votes = models.IntegerField(default=0, blank=True)
date = models.DateTimeField(auto_now_add=True)
createdby = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
forms.py
class CategoryForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CategoryForm, self).__init__(*args, **kwargs)
# access object through self.instance...
self.fields['createdby'].queryset = Award.objects.filter(createdby=self.instance.user)
class Meta:
model = Category
fields = "__all__"
This is the error I get.
'Nomination' object has no attribute 'user'
I don't understand how you got this error, because you have form for Category model and self.instanse should contain Category object, not Nomination. Anyway, if you have to use current user for form filtering, you can get it as form argument.
forms.py
class MyFilteredForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['createdby'].queryset=Award.objects.filter(createdby=user)
...
views.py
class SomeView(View):
def get(self, request, *args, **kwargs):
form = MyFilteredForm(request.user)
return render(request, 'form.html', {'form': form})
It can contains mistakes, but i think you get my idea.
I tried to add page for posts blog article for my django site.But it's slug model is not autogenerate after add it into the add post page but it work well in admin page.
example in title field when i type how to master python fastly it will auto generated in slug field with "-" in only admin page.but when I type same thing on add post page it won't generate slug automatically.
mycode
models.py
from django.db import models
from django.contrib.auth.models import User
from django_summernote.fields import SummernoteTextField
from django.urls import reverse
from django.template.defaultfilters import slugify
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
title_type = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = SummernoteTextField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
image = models.ImageField(upload_to='images',null=True, blank=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('home')
views.py
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
admin page
And add post page
The slug field should not be editable, remove the 'slug' field from the fields of AddPostView and of the Admin.
class AddPostView(CreateView):
model = Post
fields = ['title', 'title_type', 'author', 'updated_on', 'content',
'created_on', 'status', 'image']
form_class = PostForm
template_name = 'add_post.html'
I have 2 models, Question and Image. I want to create a manager in django admin, to include the fields of Image inside the Question admin panel.
These are the models:
class Question(models.Model):
quiz = models.ManyToManyField(Quiz, blank=True, )
category = models.ForeignKey(Category, blank=True, null=True, )
content = models.CharField(max_length=1000,
blank=False,
help_text="Enter the question text that you want displayed",
verbose_name='Question',
)
explanation = models.TextField(max_length=2000,
blank=True,
help_text="Explanation to be shown after the question has been answered.",
verbose_name='Explanation',
)
class Meta:
verbose_name = "Question"
verbose_name_plural = "Questions"
ordering = ['category']
def __unicode__(self):
return self.content
class Image(models.Model):
TYPE_CHOICES = (
('A','Answer'),
('Q','Question'),
)
image = models.ImageField(upload_to='static/img')
type = models.CharField(max_length=1, choices=TYPE_CHOICES)
question = models.ForeignKey(Question, blank=True, null=True)
answer = models.ForeignKey(Answer, blank=True, null=True)
def __unicode__(self):
return self.type
This is the Question Manager in Django Admin:
class QuizAdminForm(forms.ModelForm):
class Meta:
model = Quiz
questions = forms.ModelMultipleChoiceField(
queryset=Question.objects.all(),
required=False,
widget=FilteredSelectMultiple(verbose_name=('Questions'),
is_stacked=False )
)
def __init__(self, *args, **kwargs):
super(QuizAdminForm, self).__init__(*args, **kwargs)
if self.instance.pk:
self.fields['questions'].initial = self.instance.question_set.all()
def save(self, commit=True):
quiz = super(QuizAdminForm, self).save(commit=False)
if commit:
quiz.save()
if quiz.pk:
quiz.question_set = self.cleaned_data['questions']
self.save_m2m()
return quiz
You are looking InlineModelAdmin models.
class ImageInline(admin.TabularInline):
model = Image
...
class QuestionAdmin(admin.ModelAdmin):
list_display = ('content', 'category', )
list_filter = ('category',)
fields = ('content', 'category', 'quiz', 'explanation')
search_fields = ('content', 'explanation')
filter_horizontal = ('quiz',)
inlines = [AnswerInline, ImageInline]
https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#inlinemodeladmin-objects
Good to see you are using Django Quiz app. I have recently added a lot of changes to it and it would be good if you could contribute anything to the repo:
https://github.com/tomwalker/django_quiz