django view create model object - python

my site uses a rating feature where users are able to create a request for a new category, afterwards at least 100 users have to rate on this request, if 100/100 users have rated positiv for this request, the category should get created but i don't know how i can create the category model instance after the rating has reached 100/100 Positive votes.
views.py
def category_request_up_vote (request, pk):
category_request = get_object_or_404(CategoryRequests, pk=pk)
try:
if request.method == 'GET':
if category_request.author == request.user:
messages.error(request, 'You are trying to vote a request you created by your own. Thats not possible (Transmision ignored).')
return redirect('category_request_detail', pk=category_request.pk)
if CategoryRequests_Vote.objects.filter(voter=request.user, voted=category_request).exists():
messages.error(request, 'You already Voted this request. Double votes are not allowed (Transmision ignored).')
return redirect('category_request_detail', pk=category_request.pk)
else:
if category_request.up_vote == 100:
print("So what should i do now?")
else:
category_request.up_vote = F('up_vote') + 1
category_request.save()
CategoryRequests_Vote.objects.create(voter=request.user, voted=category_request)
messages.success(request, 'You have successfully Provided an Up-Vote for this Request.')
return redirect('category_request_detail', pk=category_request.pk)
else:
messages.error(request, 'Uuups, something went wrong, please try again.')
return redirect('category_request_detail', pk=category_request.pk)
except:
messages.error(request, 'Uuups, something went wrong, please try again.')
return redirect('category_request_detail', pk=category_request.pk)
models.py
class Category(models.Model):
title = models.CharField(max_length=30, verbose_name="Title")
description = models.TextField(max_length=200, null=True, blank=False)
cover = fields.ImageField(blank=False,
null=False,
upload_to=get_file_path_static_glued,
validators=[default_image_size, file_extension_category_cover],
dependencies=[FileDependency(
processor=ImageProcessor(format='PNG', quality=99, scale={
'max_width': 700, 'max_height': 700}))])
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.post = None
self.post_sell_multiple = None
def __str__(self):
return self.title
#classmethod
def get_indexable(cls):
return cls.objects.all()
#classmethod
def configure_mapping(cls, mapping):
# mapping is an elasticsearch_dsl Mapping object
mapping.field('title', 'string')
return mapping
class CategoryRequests(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=20, verbose_name="Title")
description = models.TextField(max_length=200, null=True, blank=True)
cover = fields.ImageField(
null=True,
blank=True,
upload_to=get_file_path_user_uploads,
validators=[default_image_size, default_image_file_extension],
dependencies=[FileDependency(processor=ImageProcessor(
format='PNG', quality=99, scale={'max_width': 700, 'max_height': 700}))])
published_date = models.DateField(auto_now_add=True, null=True)
status = StatusField(default='Waiting')
STATUS = Choices('Waiting', 'Rejected', 'Accepted')
up_vote = models.IntegerField(default=0)
down_vote = models.IntegerField(default=0)
def publish(self):
self.published_date = timezone.now()
self.save()
class Meta:
verbose_name = "Category Request"
verbose_name_plural = "Category Request(s)"
ordering = ['title']
def __str__(self):
return self.title

The CategoryRequest model has the fields that the Category model requires, such as title, description, etc.
Use simple django ORM for this, inside your if category_request.up_vote == 100:
you can write,
category=Category.objects.create(title=category_request.title,description=category_request.description) ,
add the other fields that the Category model needs
and in the next line category.save(). So now the category is created.

Related

Filtering Forms in Django

I am making a small project to rate salesmen. I have regions and each region has its salesmen. So, if region "blahblah" is selected, form should show salesmen choices which are related to that region. I have found some answers via stackoverflow, but it still shows all salesmen, regardless of their regions.
My model is this:
class Region(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
def __str__(self):
return self.name
class Salesman(models.Model):
region = models.ForeignKey(Region,
related_name='region',
on_delete=models.CASCADE)
name = models.CharField(max_length=40)
surname = models.CharField(max_length=40)
def __str__(self):
return self.name
class Rating(models.Model):
RATING_CHOICES = [(i, str(i)) for i in range(1,6)]
salesman = models.ForeignKey(Salesman,
related_name='salesman',
on_delete=models.CASCADE)
phone = models.CharField(max_length=15, blank=True)
rating = models.IntegerField(choices=RATING_CHOICES, blank=False)
sent_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.phone
I found modified __init__ method for my forms.py:
class RateAddForm(forms.ModelForm):
class Meta:
model = Rating
def __init__(self, region_id=None, **kwargs):
super(RateAddForm, self).__init__(**kwargs)
if region_id:
self.fields['salesman'].queryset = Salesman.objects.filter(region=region_id)
And also my views.py is this:
def report_add(request, region_id):
if request.method == 'POST':
print(region_id)
form = RateAddForm(request.POST, region_id=region_id)
if form.is_valid():
message = "Thanks!"
form.save()
return HttpResponse(message)
else:
print("Something went wrong!")
form = RateAddForm()
else:
form = RateAddForm(request.POST)
return render(request,
'account/report.html',
{'form': form})
It still shows me all salesmen on my database, even if i choose a region. How to solve this problem that form should show only salesmen of selected region. Thanks in advance!
Try setting the self.base_fields['salesman'].queryset instead of
self.fields['salesman'].queryset (i.e "base_fields" instead of "fields").
(That's what I do when I need to filter in Admin forms)

How do I fail the booking if the booked boolean field is set to True in django?

I am having trouble making if/else work in my django app, I want to check if a listing is booked, booked is a boolean field and the listing is a foreign key to the Booking class where the user selects a listing to book. Now I just want to know how that foreign key can be checked if the listing is booked so it fails to book and gives an error.
views.py
#login_required
def profile(request):
if request.method == "GET":
tickets = models.Booking.objects.all().filter(user=request.user)
return render(request, "profile.html", {'form': forms.BookingForm(), 'tickets': tickets})
else:
try:
form = forms.BookingForm(request.POST)
new_ticket = form.save(commit=False)
new_ticket.user = request.user
new_ticket.save()
messages.success(request, 'Booking Created Successfully')
return redirect('profile')
except ValueError:
return render(request, 'profile.html', {'form': forms.BookingForm()})
models.py
class Listing(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=755)
price = MoneyField(max_digits=5, decimal_places=2)
booked = models.BooleanField(default=False)
seller = models.ForeignKey(User, on_delete=models.CASCADE)
# avail_days = models.ForeignKey(Days, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Booking(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listing = models.ForeignKey(Listing, on_delete=models.CASCADE) # how to check if listing is booked and deny if it is True ?
# day = models.OneToOneField(Days, on_delete=models.CASCADE)
date_booked = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
If you want to use booked field in Listing model, you can do this (you can also render Listing objects with booked=False):
views.py
#login_required
def profile(request):
if request.method == "GET":
tickets = models.Booking.objects.all().filter(user=request.user)
return render(request, "profile.html", {'form': forms.BookingForm(), 'tickets': tickets})
else:
try:
form = forms.BookingForm(request.POST)
new_ticket = form.save(commit=False)
# here you can do something like
if new_ticket.listing.booked:
messages.error(request, 'Booked Already')
return redirect('profile')
new_ticket.user = request.user
new_ticket.save()
messages.success(request, 'Booking Created Successfully')
return redirect('profile')
except ValueError:
return render(request, 'profile.html', {'form': forms.BookingForm()})
models.py
class Listing(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=755)
price = MoneyField(max_digits=5, decimal_places=2)
booked = models.BooleanField(default=False)
seller = models.ForeignKey(User, on_delete=models.CASCADE)
# avail_days = models.ForeignKey(Days, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Booking(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listing = models.ForeignKey(Listing, on_delete=models.CASCADE) # how to check if listing is booked and deny if it is True ?
# day = models.OneToOneField(Days, on_delete=models.CASCADE)
date_booked = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
self.listing.booked = True
self.listing.save()
super().save(*args, **kwargs)

what am I doing wrong at the moment to validate my lesson class?

I want to validate if my lesson material belongs to a xyz user with pro right it will show the correct conent, but if not it will display become a member , but however I am getting if I change id membership to pro or vice versa it always true the statement
def get(self, request):
template = loader.get_template(self.template_name)
template_member = loader.get_template(self.template_payment)
#rendering the template in HttpResponse
lesson = Lesson.objects.first()
user_membership = UserMembership.objects.filter(user=self.request.user).first()
user_membership_type = user_membership.membership.membership_type
lesson_allowed_mem_types = lesson.allowed_memberships.all()
if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists():
return HttpResponse(template.render())
else:
return HttpResponse(template_member.render())
models
class Lesson(models.Model):
allowed_memberships = models.ManyToManyField(Membership)
class Membership(models.Model):
membership_type = models.CharField(
choices=MEMBERSHIP_CHOICES,
default='Free',
max_length=30)
def __str__(self):
return self.membership_type
class UserMembership(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user.email
Aren't you just trying to see if the user has a Membership?
if UserMembership.objects.filter(
user=request.user,
membership__membership_type="PAID MEMBER",
).exists():
# user is member
return HttpResponse(template.render())
else:
# user is not a member
return HttpResponse(template_member.render())

Django model foreignkey always defaults no matter what user is logged in

I have this django model for questions.
class Question(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.SET_NULL)
question_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False)
question = models.CharField(max_length=150, null=False)
question_description = FroalaField()
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
question_image = models.ImageField(upload_to=get_upload_path, blank=True, null=True)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
dynamic_link = models.CharField(max_length=225, null=False, default="")
question_type = models.CharField( max_length=50, null=False, choices=QUESTIONSTYPE_LIST)
question_status = models.CharField(max_length=150, null=False, default="unapproved")
is_active = models.BooleanField(default=False)
objects = QuestionManager()
class Meta:
ordering = ['-updated_at']
def __str__(self):
return self.question_id
def get_absolute_url(self):
kwargs = {
'questiontype': slugify(self.question_type),
'questionid': self.question_id,
'slug': slugify(self.question)
}
return reverse("questions:detail", kwargs=kwargs)
Everything seems to be working okay, except that the user user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.SET_NULL)
always saves but the default which is 1. So no matter which user is logged in and in session, it always defaults to 1.
I am using classed-based-views and the user is a CustomUser.
I have the customUser set in settings.py auth_model_user as:
AUTH_USER_MODEL = 'users.CustomUser'
Here is the form for Question:
class QuestionCreationUpdateForm(forms.ModelForm):
question = forms.CharField(widget=forms.TextInput(attrs={
'class': 'frm-input',
'placeholder': _('Enter question title'),
'autocomplete': 'off'
}))
question_type = forms.ChoiceField(choices=QUESTIONSTYPE_LIST, widget=forms.Select(attrs={'class': 'frm-input'}))
question_description = forms.CharField(widget=FroalaEditor)
def __init__(self, *args, **kwargs):
super(QuestionCreationUpdateForm, self).__init__(*args, **kwargs)
class Meta:
model = Question
fields = ('question', 'question_description', 'question_type')
And the question CreateView:
# Add Question View
#method_decorator(login_required, name='dispatch')
class AskQuestionView(CreateView):
template_name = 'ask_question.html'
form_class = QuestionCreationUpdateForm
model = Question
def form_valid(self, form):
try:
return super(AskQuestionView, self).form_valid(form)
except IntegrityError:
context = {
'msg': _('We don\'t allow continues posting! Take a break. Try again later!')
}
return render(self.request, "500.html", context)
def get_success_url(self):
return self.object.get_absolute_url()
If I do a request.user in the views.py file, I always get the right user.
So why is my model behaving this odd?
As I can see, you need to assign the User object to form instance. Like this:
#method_decorator(login_required, name='dispatch')
class AskQuestionView(CreateView):
...
def form_valid(self, form):
try:
obj = form.save(commit=False)
obj.user = self.request.user
return super(AskQuestionView, self).form_valid(obj)
except IntegrityError:
context = {
'msg': _('We don\'t allow continues posting! Take a break. Try again later!')
}
return render(self.request, "500.html", context)
# ^^ consider using a 400 error response, as 500 is for server error response. 400 is for bad request
...
You are not assigning any user to Question.user. You need to assign the current user to that field.
#method_decorator(login_required, name='dispatch')
class AskQuestionView(CreateView):
template_name = 'ask_question.html'
form_class = QuestionCreationUpdateForm
model = Question
def form_valid(self, form):
try:
form.instance.user = self.request.user
return super(AskQuestionView, self).form_valid(form)
except IntegrityError:
context = {
'msg': _('We don\'t allow continues posting! Take a break. Try again later!')
}
return render(self.request, "500.html", context)
Further read Models and request.user

Django filter with ForeignKey not working

I am building ecommerce and having trouble creating dashboard for sellers. No matter how I try to get filter processed orders so I can show sold products to sellers I couldn't make it happen. Some help will be a great relief. Following is my Seller Mixin I am trying to create:
mixins.py
class SellerAccountMixin(LoginRequiredMixin, object):
account = None
products = []
transactions = []
orders = []
def get_account(self):
user = self.request.user
accounts = SellerAccount.objects.filter(user=user)
if accounts.exists() and accounts.count() == 1:
self.account = accounts.first()
return accounts.first()
return None
def get_products(self):
account = self.get_account()
products = Product.objects.filter(seller=account)
self.products = products
return products
def get_all_products(self):
account = self.get_account()
products = Product.objects.all()
self.products = products
return products
def get_sold_products(self):
orders = UserCheckout.objects.get(user_user=self.user)
return orders
seller/views.py:
class SellerDashboard(SellerAccountMixin, FormMixin, View):
form_class = NewSellerForm
success_url = "/seller/"
def post(self, request, *args, **kwargs):
user = self.user
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def get(self, request, *args, **kwargs):
apply_form = self.get_form() #NewSellerForm()
account = self.get_account()
exists = account
active = None
context = {}
if exists:
active = account.active
if not exists and not active:
context["title"] = "Apply for Account"
context["apply_form"] = apply_form
elif exists and not active:
context["title"] = "Account Pending"
elif exists and active:
context["title"] = "Dashboard"
#products = Product.objects.filter(seller=account)
context["products"] = self.get_products()
context["today_sales"] = self.get_today_sales()
context["sold_products"] = self.get_sold_products()
#context["total_profit"] = self.get_total_profit()
else:
pass
return render(request, "sellers/dashboard.html", context)
Above is my seller app and I am bringing the products model with simple features. The problem is that its not letting me get processed orders with UserCheckout model in Orders app. Following is a snapshot of Orders app.
Orders/models.
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
email = models.EmailField(unique=True)
def __unicode__(self):
return self.email
ADDRESS_TYPE = (
('billing', 'Billing'),
('shipping', 'Shipping'),
)
class UserAddress(models.Model):
user = models.ForeignKey(UserCheckout)
type = models.CharField(max_length=120, choices=ADDRESS_TYPE)
street = models.CharField(max_length=120)
city = models.CharField(max_length=120)
state = models.CharField(max_length=120)
zipcode = models.CharField(max_length=120)
def __unicode__(self):
return self.street
def get_address(self):
return "%s, %s, %s, %s" %(self.street, self.city, self.state, self.zipcode)
CHOICES = (
('CreditCard', "CreditCard"),
('Cash On Delivery', 'Cash On Delivery'),
('PayPal', 'PayPal'),
)
ORDER_STATUS_CHOICES={
('created','Created'),
('paid','Paid'),
}
class Order(models.Model):
status = models.CharField(max_length=120, choices=ORDER_STATUS_CHOICES, default='created')
cart = models.ForeignKey(Cart)
user = models.ForeignKey(UserCheckout, null=True)
billing_address = models.ForeignKey(UserAddress, related_name='billing_address', null=True)
shipping_address = models.ForeignKey(UserAddress, related_name='shipping_address', null=True)
shipping_total_price = models.DecimalField(max_digits=50, decimal_places=2, default=5.99)
user_seller = models.ForeignKey(settings.AUTH_USER_MODEL)
order_total = models.DecimalField(max_digits=50, decimal_places=2, )
order_id = models.CharField(max_length=20, null=True, blank=True)
paymethod = models.CharField(max_length=120, choices=CHOICES, default='CreditCard')
seller = models.ForeignKey(SellerAccount, null=True)
def __unicode__(self):
return str(self.cart.id)
I can get multiple products but I need to filter products by seller and orders by seller. After trying multiple times I always get stuck with error:
user has to be a UserCheckout instance:
User "Admin": Must be a "User" instance.
and
'SellerDashboard' object has no attribute 'user'
I need to filter products by seller.
I need filter orders with paid status by the seller.
Seller Account Model:
class SellerAccount(models.Model):
user = models.ForeignKey(User)
managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="manager_sellers", blank=True)
#orders = models.ManyToManyField(Order)
active = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
def __unicode__(self):
return str(self.user.username)
def get_absolute_url(self):
return reverse("products:vendor_detail", kwargs={"vendor_name": self.user.username})
I am stuck so bad that I don't have courage to continue with django anymore. Please help.

Categories

Resources