I have a model for musics and a model for comment of musics:
class music(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published'),)
music = models.FileField()
music_image = models.ImageField(upload_to="images/")
singer_name = models.CharField(max_length=100)
music_name = models.CharField(max_length=100)
text_of_music = models.TextField()
create = models.DateField(auto_now_add=True, blank=True, null=True)
update = models.DateField(auto_now=True, blank=True, null=True)
publish = models.DateField(default=timezone.now, blank=True, null=True)
slug = models.CharField(max_length=250, unique_for_date='publish')
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager()
published = PublishedManager()
class Meta:
ordering = ('-publish',)
def get_absolute_url(self):
return reverse('music:music_detail',
kwargs={"id":self.id})
class comment(models.Model):
# Foreignkey for each music
For = models.ForeignKey(music, on_delete=models.CASCADE, related_name='post')
body = models.CharField(max_length=500)
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
and this is my view:
def music_Detail(request, id=None):
user = request.user
template_name = 'music/music_detail.html'
Music = music.objects.all().filter(id=id)
new_comment = None
Comment = comment.objects.all().filter(active=True)
form = comment_form(data=request.POST)
if request.method == 'POST':
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.For = Music
new_comment.save()
form = comment_form()
return render(request, template_name, {'Music': Music, 'Comment': Comment, 'form': form})
Well, I get this error when I comment:
Cannot assign "<QuerySet [<music: m, majid kharatha>]>": "comment.For" must be a "music" instance.
How can I solve this problem and how can I display the information of the user who left this comment?
As the error says, you'll have to assign a single Music, not a queryset.
Instead of filter()ing to get a new queryset containing a single music,
Music = music.objects.all().filter(id=id)
you want to get() a single one:
Music = music.objects.get(id=id)
Related
So I am trying to figure out why my dropdown menu will not display the list of collections for the user to pick from.
Form Screenshot: [1]: https://i.stack.imgur.com/UIrq6.png
Here is the Form.py file class used for this problem:
class ProductForm(ModelForm):
class Meta:
model = listing
fields = 'all'
_---------------------------------------------
Here is the user form VIEW:
def index(request):
form = ProductForm
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'index.html', context)
Here is also the code for the 2 models here:
class Collection(models.Model):
title = models.CharField(max_length=255)
def __str__(self) -> str:
return self.title
class Meta:
ordering = ['title']
class listing(models.Model):
image = models.ImageField(blank=True, null=True)
name = models.CharField(max_length=255)
description = models.TextField()
unit_price = models.DecimalField(max_digits=6, decimal_places=2, validators=[MinValueValidator(1)])
inventory = models.IntegerField()
last_update = models.DateTimeField(auto_now=True)
collection = models.ForeignKey(Collection, on_delete=models.PROTECT, blank=True, null=True)
vendors = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=False)
I'm somewhat new to django and just trying to understand why for the form it won't display the list of collections in the dropdown.
I am getting Issue while edit a record based on CHatquestion ID, if option is null then i need to add a record based on same chatquestion id, if chatqustion id exist in option it will work,
i am trying to multiple way to solve this issue but still can't find solution.
Models.py # thease are all 3 models
class Problem(models.Model):
Language = models.IntegerField(choices=Language_CHOICE, default=1)
type = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return self.type
class ChatQuestion(models.Model): # Eding record based on chatquestion id
question = RichTextField(null=True, blank=True)
problem_id = models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
)
def __str__(self):
return self.question
is_first_question = models.BooleanField(default=False)
class Option(models.Model):
option_type = models.CharField(max_length=250, null=True, blank=True)
question_id = models.ForeignKey(
ChatQuestion,
models.CASCADE,
verbose_name='Question',
null=True,
blank=True
)
problem=models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
null=True,
blank=True
)
next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True,
related_name='next_question')
def __str__(self):
return self.option_type
forms.py
class EditQuestionForm(forms.ModelForm):
class Meta:
model = ChatQuestion
fields =('question','problem_id')
class EditOptionForm(forms.ModelForm):
class Meta:
model = Option
fields =('option_type',)
views.py
def question_edit(request,id=None):
if id is not None:
queryset = get_object_or_404(ChatQuestion,pk=id)
queryset1=get_object_or_404(Option,question_id=queryset )
else:
queryset = None
queryset1 = None
if request.method=="POST":
form = EditQuestionForm(request.POST ,instance=queryset)
form1=EditOptionForm(request.POST, instance=queryset1)
if form.is_valid() and form1.is_valid():
question=form.cleaned_data['question']
option_type=form1.cleaned_data['option_type']
if id:
queryset.question=question
queryset.save()
queryset1.option_type=option_type
queryset1.save()
messages.success(request,'Sucessful')
return redirect('/fleet/list_chatbot')
else:
print(form.errors)
messages.error(request,'Please correct following',form.errors)
elif id:
form = EditQuestionForm(instance=queryset)
form1=EditOptionForm(instance=queryset1)
if not queryset1:
form1=EditOptionForm()
else:
form = EditQuestionForm()
form1=EditOptionForm()
context={
'form':form,
'form1':form1
}
return render(request,'chatbot/question_edit.html',context=context)
I'm currently processing a payment thing for an online subscription service and in order to get the users info to send this stuff, I have a payment form.
But, for some reason the payment form is not saving to the users account. Everything else actually processes and the only error I can trigger is a 'NOT NULL constraint failed: memberships_usermembership.user_id'
Here's what I have in my view -
#login_required()
def payments(request):
user_membership = get_user_membership(request)
selected_membership = get_selected_membership(request)
form = SubscriptionForm()
if request.method == "POST":
form_data = {
'full_name': request.POST['full_name'],
'email': request.POST['email'],
'phone_number': request.POST['phone_number'],
'country': request.POST['country'],
'postcode': request.POST['postcode'],
'town_or_city': request.POST['town_or_city'],
'street_address1': request.POST['street_address1'],
'street_address2': request.POST['street_address2'],
'county': request.POST['county'],
}
token = request.POST['stripeToken']
form = SubscriptionForm(form_data)
if form.is_valid():
customer = stripe.Customer.retrieve(
user_membership.stripe_customer_id)
customer.source = token
customer.save()
subscription = stripe.Subscription.create(
customer=user_membership.stripe_customer_id,
items=[
{"plan": selected_membership.stripe_plan_id},
]
)
user_membership = get_user_membership(request)
selected_membership = get_selected_membership(request)
user_membership.membership = selected_membership
user_membership.save()
form.save(commit=True)
subscription_id = subscription.id
sub, created = Subscription.objects.get_or_create(
user_membership=user_membership)
sub.stripe_subscription_id = subscription_id
sub.active = True
sub.save()
try:
del request.session['selected_membership_type']
except BaseException:
pass
return render(request, 'memberships/update-success.html')
else:
return redirect(reverse('membership_list'))
context = {
'selected_membership': selected_membership,
'form': form,
}
return render(request, 'memberships/payment.html', context)
When the form.save() is the line above the return(render) line, it will process everything as normal, and the form information just wont save into the DB.
It flashes the NOT NULL error when the form.save() line is where it in in the code above.
Any ideas how to get this working?
Thanks!
EDIT: Here's a link to the entire error in Django - http://dpaste.com/140VD8M
& a screenshot of it too!
Here's my models -
class Membership(models.Model):
membership_type = models.CharField(
choices=MEMBERSHIP_CHOICES,
default='Free',
max_length=30)
price = models.IntegerField(default=15)
description = models.TextField(default="DESCRIPTION")
image_url = models.URLField(max_length=1024, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
stripe_plan_id = models.CharField(max_length=40)
def __str__(self):
return self.membership_type
class UserMembership(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
full_name = models.CharField(max_length=50, null=True, blank=True)
email = models.EmailField(max_length=254, null=True, blank=True)
phone_number = models.CharField(max_length=20, null=True, blank=True)
country = CountryField(blank_label='Country', default="Ireland")
postcode = models.CharField(max_length=20, null=True, blank=True)
town_or_city = models.CharField(max_length=40, null=True, blank=True)
street_address1 = models.CharField(max_length=80, null=True, blank=True)
street_address2 = models.CharField(max_length=80, null=True, blank=True)
county = models.CharField(max_length=80, null=True, blank=True)
stripe_customer_id = models.CharField(max_length=40)
membership = models.ForeignKey(
Membership, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user.username
def post_save_usermembership_create(
sender, instance, created, *args, **kwargs):
user_membership, created = UserMembership.objects.get_or_create(
user=instance)
if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id == '':
new_customer_id = stripe.Customer.create(email=instance.email)
free_membership = Membership.objects.get(membership_type='Free')
user_membership.stripe_customer_id = new_customer_id['id']
user_membership.membership = free_membership
user_membership.save()
post_save.connect(post_save_usermembership_create,
sender=settings.AUTH_USER_MODEL)
class Subscription(models.Model):
user_membership = models.ForeignKey(
UserMembership, on_delete=models.CASCADE)
stripe_subscription_id = models.CharField(max_length=40)
active = models.BooleanField(default=False)
def __str__(self):
return self.user_membership.user.username
& here's my user membership def -
#login_required()
def get_user_membership(request):
user_membership_qs = UserMembership.objects.filter(user=request.user)
if user_membership_qs.exists():
return user_membership_qs.first()
return None
Instead of collecting all the form fields individually, you should be able to just pass the request.POST to the form like so:
form_data = request.POST
token = request.POST['stripeToken']
form = SubscriptionForm(form_data)
Other than that, without seeing the exact error message, there isn't much more to tell. If you update your question I will update my answer.
EDIT:
Without seeing your model and what get_user_membership() returns, it looks like you are missing a User object in a UserMembership class (but I can't tell without seeing more):
user_membership.user = request.user
Or something like that.
Hello I have this error when I start saving a form.
Cannot assign "<SimpleLazyObject: <User: admin>>": "Project.manager" must be a "Profil" instance.
I have two applications account and project
account.model.py
class Profil(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo_path = time.strftime('photo/%Y/%m/%d')
photo = models.ImageField(upload_to=PathAndRename(photo_path), blank=True, null=True)
antity = models.CharField(max_length=50, choices=ENTITY_TYPE, default=ENTITY_TYPE[0])
biography = models.TextField(blank=True, max_length=500)
location = models.CharField(max_length=30, blank=True, default='Congo-BZV')
facebook_url = models.URLField(default='', blank=True)
twitter_url = models.URLField(default='', blank=True)
inscrit_newsletter = models.BooleanField(default=True)
def __str__(self):
return "Profil de {0}".format(self.user.username)
project.model.py
class Project( models.Model):
manager = models.ForeignKey('accounts.Profil', related_name='project', on_delete=models.CASCADE)
title = models.CharField(max_length = 100)
slug = models.SlugField(unique=True)
image_path = time.strftime('images/%Y/%m')
main_image = models.ImageField(upload_to=PathAndRename(image_path), blank=True)
slogan = models.CharField(max_length=300, blank=True)
description = RichTextUploadingField(blank = True, null=True)
project.views.py
def project_new(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
project = form.save(commit = False)
project.manager = request.user
project.save()
else:
form = ProjectForm()
return render(request, 'project/project_new.html', {'form': form})
project.forms.py
class ProjectForm(forms.ModelForm):
title = forms.CharField(label='Titre')
description = forms.CharField(widget=CKEditorUploadingWidget())
category = forms.ModelChoiceField(queryset = Category.objects.all(), label='Catégorie')
#description = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20}))
class Meta:
model = Project
fields = ('title', 'nb_days', 'slogan', 'category', 'description')
I would like every user or manager to be linked to the project they post via a form.
How could I link the two models by saving a model?
Thank you
insted of
project.manager = request.user
you should use:
project.manager = request.user.profil
I keep getting error messages and have no idea why. I think it has to do with the variable for instance, but i see a lot of examples all over the internet that work the same way.
models.py
class Establishments(models.Model):
title = models.CharField(max_length=255)
town = models.ForeignKey(Town, on_delete=SET_NULL, null=True)
addrstreet = models.CharField(max_length=255)
addrzip = models.CharField(max_length=12)
telephone = models.CharField(max_length=15)
email = models.CharField(max_length=255)
chamberofcomnr = models.CharField(max_length=25)
description = models.TextField(max_length=255)
website = models.CharField(max_length=255)
categorie = models.ForeignKey(Establishmentcategory, on_delete=SET_NULL, null=True)
pub_date = models.DateTimeField('date published')
drupuser = models.ForeignKey(Drupalusers, on_delete=SET_NULL, null=True)
druppublished = models.BooleanField()
drupurl = models.CharField(max_length=255)
drupnodeid = models.IntegerField()
def __str__(self):
return self.title
class Impcalendar(models.Model):
establishment = models.ForeignKey(Establishments, on_delete=SET_NULL, null=True)
active = models.BooleanField()
prio = models.IntegerField()
url = models.CharField(max_length=255)
check_intervalh = models.IntegerField()
check_fixedh = models.IntegerField()
log = models.BooleanField()
cuttag = models.CharField(max_length=255)
cuttxt = models.CharField(max_length=255)
cuttxtend = models.CharField(max_length=255)
comment = models.CharField(max_length=255)
page = models.TextField()
pageold = models.TextField()
change = models.TextField()
pagedate = models.DateTimeField()
pagedatenext = models.DateTimeField()
status = models.IntegerField()
errors = models.IntegerField()
def __str__(self):
return str(self.id)
urls.py
path('calendar/<int:calendar_id>/', views.calendaredit, name='calendaredit')
views.py
def calendaredit(request, calendar_id):
calendar = get_object_or_404(Impcalendar, pk=calendar_id)
print (calendar.url)
form = ImpcalendarForm(request.POST or None, instance=calendar)
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
print (form.url)
# check whether it's valid:
if form.is_valid():
#calendar.establishment = form.cleaned_data['
calendar = form.save(commit=false)
calendar.active = form.cleaned_data['active']
calendar.save()
return redirect('handmatig')
return render(request, 'import_calendar/handmatig_edit.html', {'form': form})
forms.py
class ImpcalendarForm(forms.Form):
establishment = forms.ModelChoiceField(queryset = Establishments.objects.all())
page = forms.CharField(widget=forms.Textarea)
pageold = forms.CharField(widget=forms.Textarea)
change = forms.CharField(widget=forms.Textarea)
class Meta:
model = Impcalendar
fields = '__all__'
So i want to have a record page, listing all the records already works, where i can edit the form. It needs to show the record as a Django form. It crashes on the line;
form = ImpcalendarForm(request.POST or None, instance=calendar)
If i print the variable calendar or calendar.url i get the correct data.
The error message is;
TypeError: __init__() got an unexpected keyword argument 'instance'
Spend a week debugging. Now escalading. ;-)
Your form subclasses forms.Form instead of forms.ModelForm.
Normal forms don't take model instances, and neither do they have an inner Meta class.