Getting error during adding a comment as notnull - python

I don't understand why I am getting this one I tried making null=True, blank=True but still, it does not solve my error, at last, I thought of sending it here ...!! please tell me where I am going wrong
Models.py
class Certification(models.Model):
id = models.UUIDField(default=uuid.uuid4,
unique=True, primary_key=True, editable=False)
course_name = models.CharField(max_length=255)
course_image = models.ImageField()
course_taken = models.CharField(max_length=255)
mentor_name = models.CharField(max_length=20, blank=True, null=True)
slug = models.SlugField(unique=True, null=True)
#body = RichTextField()
body = RichTextUploadingField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.course_name
class Comment(models.Model):
certificate = models.ForeignKey(Certification, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
body = models.TextField(null=True, blank=True)
forms.py
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = '__all__'
exclude = ['certificate']
def __init__(self, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update(
{'class': 'form-control form-control-sm',})
self.fields['body'].widget.attrs.update(
{'class': 'form-control form-control-sm',})
Views.py
def certificatePage(request,pk):
certi = Certification.objects.get(id=pk)
count = certi.comment_set.count()
comments = certi.comment_set.all()
form = CommentForm()
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.certi = certi
comment.save()
context = {
"certi": certi,
'count':count,
'comments':comments,
'form':form
}
return render (request, 'base/certificate.html',context)
Click On The Image To See The Error

Related

How Can I Integrate Flutterwave Paymwnt Gate Way with Django

I am working on a Django Project where I want to collect payment in Dollars from Applicants on the portal, and I don't know how to go about it. Though I have been following an online tutorial that shows how to do it but the result I am having is different with the recent error which says 'module' object is not callable.
Remember that I have tested my configured environment and also imported it into my views on top of the page.
Profile model code:
class Profile(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
surname = models.CharField(max_length=10, null=True)
othernames = models.CharField(max_length=30, null=True)
gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
nation = models.CharField(max_length=255, choices=NATION, blank=True, null=True)
state = models.CharField(max_length=20, null=True)
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=16, null=True)
image = models.ImageField(default='avatar.jpg', upload_to ='profile_images')
def __str__(self):
return f'{self.applicant.username}-Profile'
Education/Referee Model code:
class Education(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
qualification = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True)
instition = models.CharField(max_length=40, null=True)
reasons = models.CharField(max_length=100, null=True)
matnumber = models.CharField(max_length=255, null=True)
reference = models.CharField(max_length=100, null=True)
refphone = models.CharField(max_length=100, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return f'{self.applicant}-Education'
Submitted Model code:
class Submitted(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
confirm = models.BooleanField()
approved = models.CharField(max_length=20, null=True)
date = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.application == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.applicant
def __str__(self):
return f'Application Number: {self.application}-{self.applicant}'
Scholarship Model code:
class Scholarship(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null = True)
name = models.CharField(max_length=100, null = True)
description = models.CharField(max_length=200, null = True)
category = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True)
amount = models.FloatField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'WASU Scholarship: {self.name}-{self.name}'
My View for printing slip:
def AppSlip(request):
check_submited = Submitted.objects.get(applicant=request.user)
check_education = Education.objects.get(applicant = request.user)
candidate_edu = check_education.qualification
scholarship = Scholarship.objects.get(category=candidate_edu)
context = {
'candidate_edu':candidate_edu,
'scholarship':scholarship,
}
return render(request, 'user/slip.html', context)
My view for applicant to fill form for payment which I want their Profile captured automatically in the form:
def scholarship_detail(request, pk):
data = Scholarship.objects.get(id=pk)
if request.method=='POST':
form = PaymentForm(request.POST)
if form.is_valid():
user = Profile.objects.get(applicant=request.user)
name= user.surname
email = form.cleaned_data['email']
amount = form.cleaned_data['amount']
phone = form.cleaned_data['phone']
context = {'applicant':name, 'email':email, 'amount':amount, 'phone':phone}
return process_payment(request, context)
else:
form = PaymentForm()
ctx={
'form':form,
'product':data,
}
return render(request, 'user/scholarship.html', ctx)
My form code for Payment: How can query logged in user profile and fill into name, email, phone, amount from Scholarship Model into amount form filled.
class PaymentForm(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
email = forms.EmailField()
phone=forms.CharField(max_length=15)
amount = forms.FloatField()
View code for processing Payment (Where I am suspecting the error). Though I have configured my env using django-dotenv with the Flutterwave Secret Key in it.
#login_required(login_url='user-login')
def process_payment(request, newContext={}):
auth_token= dotenv('SECRET_KEY')
hed = {'Authorization': 'Bearer ' + auth_token}
data = {
"tx_ref":''+str(math.floor(1000000 + random.random()*9000000)),
"amount":amount,
"currency":"KES",
"redirect_url":"http://localhost:8000/callback",
"payment_options":"card",
"meta":{
"consumer_id":23,
"consumer_mac":"92a3-912ba-1192a"
},
"customer":{
"email":email,
"phonenumber":phone,
"name":name
},
"customizations":{
"title":"WASU Scholarship 2022",
"description":"Best store in town",
"logo":"https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg"
}
}
url = ' https://api.flutterwave.com/v3/payments'
response = requests.post(url, json=data, headers=hed)
response=response.json()
link=response['data']['link']
return link
My payment Response View:
#require_http_methods(['GET', 'POST'])
def payment_response(request):
status=request.GET.get('status', None)
tx_ref=request.GET.get('tx_ref', None)
print(status)
print(tx_ref)
return HttpResponse('Finished')
Anticipating your prompt answers. Thanks

Django Formset: Add lines from an existing product catalog?

I have got a form with a formset that allows me to add some lines to it. I can add some simple lines. But I also wanted to add some products from a product catalog.
So the process will be as following:
User create a new purchase order (Working)
User add lines as explained below (Working)
User a button add lines from existing product catalog. The user will then browse or filter the product, he wants to order and add it to the purchase order.
I know what I am trying to do is wrong as I guess we can not have two def get_context_data(self, **kwargs): in the function. What would be the idea to be able to add products from the catalog in my formset?
Many Thanks,
Product list
models.py
class BaseProduct(models.Model):
"""
Abstract base product model class providing the base fields and methods
"""
supplier = models.CharField(max_length=300, blank=True, null=True)
manufacturer = models.CharField(max_length=300, blank=True, null=True)
product_range = models.CharField(max_length=300, blank=True, null=True)
part_number = models.CharField(_('Item Code'), max_length=255, blank=True, null=True)
description = models.CharField(_('description'), max_length=255, blank=True, null=True)
Orders
views.py
class OrderCreate(CreateView):
model = Order
template_name = 'accounting/orders/create_order.html'
form_class = OrderForm
success_url = None
def get_context_data(self, **kwargs):
data = super(OrderCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['lines'] = OrderLineFormSet(self.request.POST)
else:
data['lines'] = OrderLineFormSet()
return data
def get_context_data(self, **kwargs):
data = super(OrderCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['productlines'] = OrderProductLineFormSet(self.request.POST)
else:
data['productlines'] = OrderProductLineFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
lines = context['lines']
with transaction.atomic():
form.instance.created_by = self.request.user
self.object = form.save()
if lines.is_valid():
lines.instance = self.object
lines.save()
return super(OrderCreate, self).form_valid(form)
def get_success_url(self):
return reverse('accounting:detail_order', kwargs={'order_id': self.object.pk})
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(OrderCreate, self).dispatch(*args, **kwargs)
models.py
class OrderLine(models.Model):
order = models.ForeignKey('Order', on_delete=models.CASCADE, related_name="has_lines", blank=True, null=True)
order_item = models.CharField(max_length=100, verbose_name="Line", blank=True, null=True)
tax_rate = models.ForeignKey('TaxRate', on_delete=models.CASCADE, blank=True, null=True)
total = models.CharField(max_length=250, blank=True, null=True)
description = models.CharField(max_length=100, blank=True, null=True)
unit_price_excl_tax = models.DecimalField(max_digits=8,decimal_places=2, blank=True, null=True)
quantity = models.DecimalField(max_digits=8,decimal_places=2,default=1, blank=True, null=True)
def total(self):
total = Decimal(str(self.unit_price * self.quantity))
return total.quantize(Decimal('0.01'))
def __unicode__(self):
return self.description
class Meta:
pass
class OrderProductLine(models.Model):
order = models.ForeignKey('Order', on_delete=models.CASCADE, related_name="has_lines", blank=True, null=True)
baseproduct = models.ForeignKey('BaseProduct', on_delete=models.CASCADE, related_name="has_product_lines", blank=True, null=True)
order_item = models.CharField(max_length=100, verbose_name="Product_Line", blank=True, null=True)
tax_rate = models.ForeignKey('TaxRate', on_delete=models.CASCADE, blank=True, null=True)
total = models.CharField(max_length=250, blank=True, null=True)
description = models.CharField(max_length=100, blank=True, null=True)
unit_price_excl_tax = models.DecimalField(max_digits=8,decimal_places=2, blank=True, null=True)
quantity = models.DecimalField(max_digits=8,decimal_places=2,default=1, blank=True, null=True)
def total(self):
total = Decimal(str(self.unit_price * self.quantity))
return total.quantize(Decimal('0.01'))
def __unicode__(self):
return self.description
class Meta:
pass
forms.py
class OrderLineForm(forms.ModelForm):
class Meta:
model = OrderLine
exclude = ()
OrderLineFormSet = inlineformset_factory(
Order, OrderLine, form=OrderLineForm,
fields=['order_item', 'description','quantity','unit_price_excl_tax','tax_rate'], extra=1, can_delete=True
)
class OrderProductLineForm(forms.ModelForm):
class Meta:
model = OrderProductLine
exclude = ()
OrderProductLineFormSet = inlineformset_factory(
BaseProduct, OrderProductLine, form=OrderProductLineForm,
fields=['supplier', 'part_number','quantity','unit_price_excl_tax','tax_rate'], extra=1, can_delete=True
)
To fix the issue with your view you can combine the two get_context_data methods, but I am not sure if this will fix all the issues you are having
def get_context_data(self, **kwargs):
data = super(OrderCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['lines'] = OrderLineFormSet(self.request.POST)
data['productlines'] = OrderProductLineFormSet(self.request.POST)
else:
data['lines'] = OrderLineFormSet()
data['productlines'] = OrderProductLineFormSet()
return data
More generally, it looks like you are trying to edit two models at the same time utilizing the ModelForm class. The best way to do this is to have two model forms submit through the same form rather than utilizing formsets. There is a good example of this here taken from this SO post. You should be able to find more details on this implementation in the two links.

Need help writing a Unit Test in Django

Good day everybody.
I need to test a view, and I got stuck ( I am a django newbie).
I got through all other url and view tests, but I'm really not sure how to write this one.
I tried writing it on my own, I read through the testing docs, I even tried testing this using model_mommy ( but I got a custom HTML field in my models ) which is not supported by mommy. I tried with mommy Recipes, also without luck. I really gotta do this test today, it's a part of a task I was given.
here is the view :
class CommentCreateView(CreateView):
def get(self, request, *args, **kwargs):
context = {'form': CommentForm()}
return render(request, 'news/add_comment_to_article.html', context)
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
article = get_object_or_404(Article, pk=kwargs.get('pk'))
print(article)
comment = form.save(commit=False)
comment.post = article
comment.save()
return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk}))
else:
form = CommentForm()
return render(request, 'news/add_comment_to_article.html', {'form': form})
and here are my models:
class Article(models.Model):
title = models.CharField('title', max_length=200, blank=True)
slug = AutoSlugField(populate_from='title', default="",
always_update=True, unique=True)
author = models.CharField('Author', max_length=200, default="")
description = HTMLField()
is_published = models.BooleanField(default=False)
article_text = HTMLField('Article text', default="")
pub_date = models.DateTimeField(default=datetime.now, blank=True)
article_category = models.ForeignKey(Category, on_delete="models.CASCADE", blank=True, null=True, default="")
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta(object):
ordering = ['my_order']
def __str__(self):
print(self.image.all())
return self.title
class ArticleImages(models.Model):
article = models.ForeignKey(Article, on_delete="models.CASCADE", related_name="image")
image = models.ImageField("image")
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
def image_tag(self):
return mark_safe('<img src="/media/%s" width="150" height="150" />' % (self.image))
image_tag.short_description = 'Image'
class Meta(object):
ordering = ['my_order']
def __str__(self):
return self.image.url
class Comment(models.Model):
post = models.ForeignKey('Article', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=datetime.now, blank=True)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
I would REALLY appreciate someone helping me out here.
Thank you, and have a good day !

Put request.user.email inside another model field

I try to get user email from user model and put it in a field on another model the code is working and the counter count perfect but the add line not this is the code:
models.py
class Posts(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(blank=True, max_length=100)
slug = models.SlugField(null=True, blank=True)
contain = models.TextField(blank=True)
post_image = models.ImageField(upload_to="post_img", default='post_img/humanity.jpg')
post_published = models.DateTimeField(blank=True, auto_now_add=True)
post_updated = models.DateTimeField(blank=True, auto_now=True)
post_deleted = models.BooleanField(default=False)
post_approved = models.BooleanField(default=False)
post_sponsored = models.CharField(max_length=100, null=True, blank=True, default = None)
post_sponsored_accepted = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if not self.slug:
self.slug= slugify(self.title)
super(Posts, self).save(*args, **kwargs)
def __str__(self):
return f'Author: {self.author}, Title:{self.title}, Posted: {self.post_published}'
views.py
def post_check(request, pk):
pos = Posts.objects.get(pk=pk)
u = UserProfile.objects.get(user=request.user)
if u.sp_counter < 3:
pos.post_sponsored = request.user.email
u.sp_counter += 1
u.save()
messages.success(request, 'طلبك قيد المراجعة، الرجاء انتظار الموافقة')
return redirect('index')
else:
messages.warning(request, 'وصلت الحد الاقصى للكفالات')
return redirect('index')

Pre populate image field in django form not working

I'm trying to pre populate an image field in a django form, however, I can't seem to get it working. Here's what I've done:
Views.py
class EditUnpublished(TemplateView):
template_name = 'adminpage/editUnpublished.html'
def get(self, request, id):
if not is_authenticated(request.user):
return render(request, template_name_not_authenticated)
post = Unpublished.objects.get(id=id)
form = PublishForm(
{
'title': post.title,
'text': post.text,
'user': post.user,
'image': post.image.url,
'users': post.users,
'tags': post.tags,
'copyeditor': post.copyeditor,
'comments': post.comments,
}
)
if not(request.user == post.copyeditor):
form.fields['comments'].widget.attrs['readonly'] = True
context = {
'post': post,
'form': form
}
return render(request, self.template_name, context)
Forms.py
class PublishForm(forms.ModelForm):
title = forms.CharField(required=False)
text = forms.TextInput()
image = forms.ImageField(required=False)
users = forms.ModelChoiceField(queryset=User.objects.all(),
widget=forms.Select(), required=False)
tags = forms.ModelChoiceField(queryset=Tags.objects.all(),
widget=forms.Select(), required=False)
copyeditor = forms.ModelChoiceField(queryset=User.objects.filter(groups__name__in=['Editor']),
required=False, to_field_name="id")
comments = forms.CharField(widget=forms.Textarea(), required=False)
class Meta:
model = PostsTwo
fields = ('title', 'text', 'image', 'users', 'copyeditor',
'tags', 'comments')
Models.py
class Unpublished(models.Model):
title = models.CharField(max_length=500)
user = models.ForeignKey(User, related_name="owner", default=None,
on_delete=models.CASCADE, blank=True, null=True)
text = models.TextField()
image = models.FileField(upload_to='img', default='img/None/no-
img.jpg', blank=True, null=True)
created_at = models.DateTimeField(default=datetime.now, blank=True)
users = models.ForeignKey(User, related_name='contributors',
on_delete=models.CASCADE, blank=True, null=True)
tags = models.ForeignKey(Tags, on_delete=models.CASCADE,
blank=True, null=True, unique=False)
copyeditor = models.ForeignKey(User, unique=False,
limit_choices_to={'groups__name': "Editor"}, on_delete=models.CASCADE,
blank=True, null=True)
comments = models.CharField(max_length=500000, blank=True,
null=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "Unpublished"
What I want is that when a user clicks in to a post, a form with all existing data, that's in the database, is pre populated. Everything except the image is being pre populated. What can I do? :)

Categories