Put request.user.email inside another model field - python

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')

Related

Problem with saving object in django-rest-framework

This is my view where I save Order object with values from frontend:
#api_view(['POST'])
#permission_classes([AllowAny])
def generate_bank_transfer_order(request):
if request.method == "POST":
body = json.loads(request.body)
first_name = body.get("firstName")
last_name = body.get("lastName")
full_name = f"{first_name} {last_name}"
today = datetime.now()
transaction_id= f'00{today.strftime("%S%M%H%d%m%y")}'
code_base = body.get('code')
try:
code = Code.objects.get(code = code_base)
new_order = Order(email=body.get("email"), message=body.get("message"),
city=body.get("city"), adress=body.get("adress"), postal_code=body.get("postalCode"),
phone=body.get("phone"), full_name=full_name, product_names=body.get("cart"),
shipment_fee=body.get("shipmentFee"), shipment_method=body.get("shipmentMethod"),
transaction_id=transaction_id, total_price=body.get("price"), code=code)
new_order.save()
return JsonResponse({"success":new_order.transaction_id})
except ObjectDoesNotExist:
new_order = Order(email=body.get("email"), message=body.get("message"),
city=body.get("city"), adress=body.get("adress"), postal_code=body.get("postalCode"),
phone=body.get("phone"), full_name=full_name, product_names=body.get("cart"),
shipment_fee=body.get("shipmentFee"), shipment_method=body.get("shipmentMethod"),
transaction_id=transaction_id, total_price=body.get("price"))
new_order.save()
return JsonResponse({"success":new_order.transaction_id})
This is my Order model:
class Order(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, blank=True, null=True)
message = models.TextField(max_length=1000, blank=True, null=True)
email = models.EmailField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=75, default='')
adress = models.CharField(max_length=100)
postal_code = models.CharField(max_length=6)
phone = models.CharField(primary_key=True, max_length=9, validators=[RegexValidator(r'^\d{9}$/')])
full_name = models.CharField(max_length=100)
product_names = models.TextField(max_length=5000)
shipment_fee = models.IntegerField(default=0)
shipment_method = models.CharField(blank=True, null=True, max_length=50)
code = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True)
transaction_id = models.CharField(max_length=150, default=0)
total_price = models.DecimalField(default=0, max_digits=12, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
accepted = models.BooleanField(default=False)
shipped = models.BooleanField(default=False)
def __str__(self):
return f"{self.email} : {self.transaction_id}"
def save(self):
if not self.created_at:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(Order, self).save()
This piece of code is not perfect, but it saves the data I need. The problem is when I want to save another order, the previous one get updated instead of the next one being created. Any thoughts about what did I do wrong?
Try passing in arguments to the save method as described in the docs:
def save(self, *args, **kwargs):
if not self.created_at:
self.created_at = timezone.now()
self.updated_at = timezone.now()
super().save(*args, **kwargs)
I would also clean up the try/get:
new_order = Order(email=body.get("email"), message=body.get("message"),
city=body.get("city"), adress=body.get("adress"), postal_code=body.get("postalCode"),
phone=body.get("phone"), full_name=full_name, product_names=body.get("cart"),
shipment_fee=body.get("shipmentFee"), shipment_method=body.get("shipmentMethod"),
transaction_id=transaction_id, total_price=body.get("price"))
try:
code = Code.objects.get(code=code_base)
new_order.code = code
except ObjectDoesNotExist:
pass
new_order.save()
return JsonResponse({"success":new_order.transaction_id})

IsOwnerOrReadOnly permission

I'm trying to do crud API with IsOwnerOrReadOnly permission but other users can still delete posts from the others. Could you please have a look? I have no clue what goes wrong. My guess is that it has something to do with this line
return obj.author == request.user.userprofile
// permissions.py
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self,request,view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.author == request.user.userprofile
// views.py
class PostDetail(APIView):
permission_classes = [
permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,
]
def get_obj(self, pk):
try:
return Post.objects.get(id=pk)
except Post.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
post = self.get_obj(pk)
serializer = PostSerializer(post)
return Response(serializer.data)
def put(self, request, pk, format=None):
post = self.get_obj(pk)
serializer = PostSerializer(post, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
post = self.get_obj(pk)
post.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
// models.py
class Post(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
author = models.ForeignKey(Profile,on_delete=models.CASCADE)
title = models.CharField(max_length=200, blank=True, null=True)
content = models.TextField(blank=True, null=True)
tags = models.ManyToManyField('Tag',blank=True)
answers = models.IntegerField(default=0)
last_modified = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Profile(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE)
name = models.CharField(max_length=200, blank=True, null=True)
email = models.EmailField(max_length=200, blank=True, null=True)
location = models.CharField(max_length=200, blank=True, null=True)
intro = models.CharField(max_length=200, blank=True, null=True)
bio = models.TextField(blank=True, null=True)
profile_image = models.ImageField(default=None, upload_to='profile/', blank=True, null=True)
github = models.CharField(max_length=200, blank=True, null=True)
linkedin = models.CharField(max_length=200, blank=True, null=True)
created = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.user.username)
I think the object permission is never called, Try to explicitly call the APIVIew check_object_permissions in the get_obj method.
def get_obj(self, pk):
obj = get_object_or_404(Post, pk=pk)
self.check_object_permissions(self.request, obj)
return obj
https://www.django-rest-framework.org/api-guide/permissions/#object-level-permissions

Getting error during adding a comment as notnull

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

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.

Doesn't save data django Foreignkey model

I've two model. I would like to save data from ForeignKey model. I'm created a modelform and save with my main foreignkey model. But I got this error ValueError at /c/customer/1/
Cannot assign "'1'": "BillingData.customer" must be a "CustomerData" instance.
I created Django model form and hocked up with view.
models.py file
class CustomerData(models.Model):
customer_name = models.CharField(max_length=100)
customer_no = models.CharField(max_length=100, default='', blank=True)
mobile_number = models.IntegerField()
alternative_phone = models.IntegerField(null=True, blank=True)
union_name = models.ForeignKey(UnionName, on_delete=models.SET_NULL, null=True)
word_name = models.ForeignKey(UnionWordName, on_delete=models.SET_NULL, null=True)
full_address = models.CharField(max_length=200, null=True, blank=True)
create_date = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return '%s, Mobile: %s' % (self.customer_name, self.mobile_number)
def get_absolute_url(self):
return reverse('customer_data', kwargs={'pk': self.pk})
class BillingData(models.Model):
bill_no = models.CharField(max_length=100, default='', blank=True)
customer = models.ForeignKey(CustomerData, on_delete=models.CASCADE)
sales_person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
customer_money = models.IntegerField()
create_date = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return '%s %s' % (self.customer.customer_name, self.create_date.date())
def get_absolute_url(self):
return reverse('customers.views.BillingPage', kwargs={'pk': self.pk})
forms.py file
class BillCreateForms(forms.ModelForm):
bill_no = forms.CharField(max_length=100)
customer = forms.ChoiceField(choices=[(x.id, x.customer_name) for x in CustomerData.objects.all()])
customer_money = forms.IntegerField()
def save(self, commit=True):
instance = super(BillCreateForms, self).save(commit=False)
customer_pk = self.cleaned_data['customer']
instance.customer = CustomerData.objects.get(pk=customer_pk)
instance.save(commit)
return instance
class Meta:
model = BillingData
fields = ('bill_no', 'customer', 'customer_money',)
views.py file
class CustomerDataView(FormMixin, generic.DetailView):
model = CustomerData
form_class = BillCreateForms
template_name = "customers/customerdata_detail.html"
print(form_class)
success_url = '/c/'
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
I expect data save with foreignkey relation data. But doesn't save here.
You can't fix this problem in the save method, because the error happens before it gets that far.
You should be using a ModelChoiceField, not a ChoiceField. Not only would this fix the problem, it would also let you remove your entire save method.
customer = forms.ModelChoiceField(queryset=CustomerData.objects.all())
Change this line
instance.customer = CustomerData.objects.get(pk=customer_pk)
to
instance.customer_id = CustomerData.objects.get(pk=customer_pk).pk
Model:
class Blog(models.Model):
# ...
pass
class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, null=True)
Set object
b = Blog.objects.get(id=1)
e = Entry.objects.get(id=234)
b.entry_set.add(e)

Categories