what does these lines of code mean in Django View: i couldn't find a details explanation, I came to Django from a Laravel background, so I can understand the models and relationships... thanks
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
customer = request.user.customer
The request object has a user, the user is the authenticated user (if no user is authenticated then the AnonymousUser object is returned instead). In this example the User model (i.e. the user table) has a field called customer and we are accessing that field.
product = Product.objects.get(id=productId)
Here we are simply querying the Product table for a specific product with the given productId. Note, Django will raise an error if two records are returned when you use the .get() method (i.e. if two rows in the Product table have the same productId.
order, created = Order.objects.get_or_create(customer=customer, complete=False)
Next we use the get_or_create() method to look up an order based off of the customer (the value of which we extracted above. If an order cannot be found we will create one instead. The value of createdwill be True if a neworder` was created or False if one already existed.
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
Just as above we are getting or creating an OrderItem using the order and product fields.
Related
I am using flask-admin to have easy edits on my DB model. It is about renting out ski to customers.
This is my rental view (the sql_alchemy DB model is accordingly):
class RentalView(ModelView):
column_list = ("customer", "from_date", "to_date", "ski", "remarks")
...
customer and ski are relationship fields to the respective model. I want to only show these ski in the edit view that are not rented by others in this time period.
I have been searching everywhere how to dynamically set the choices of the edit form but it simply does not work fully.
I tried doing
def on_form_prefill(self, form, id):
query = db.session.query... # do the query based on the rental "id"
form.ski.query = query
and this correctly shows the filtered queries. However, when submitting the form, the .query attribute of the QuerySelectField ski is None again, hence leading to a query = self.query or self.query_factory() TypeError: 'NoneType' object is not callable error. No idea why the query is being reset?!
Does anybody know a different strategy of how to handle dynamic queries, based on the edited object's id?
Use this pattern, override the view's edit_form method, instance the default edit form (by calling the super() method then modify the form as you wish:
class RentalView(ModelView):
# setup edit forms so that Ski relationship is filtered
def edit_form(self, obj):
# obj is the rental instance being edited
_edit_form = super(RentalView, self).edit_form(obj)
# setup your dynamic query here based on obj.id
# for example
_edit_form.ski.query_factory = lambda: Ski.query.filter(Ski.rental_id == obj.id).all()
return _edit_form
I am implementing a User referral system, which existing users can refer other people to register an account with the link they provided. After the new user registers, the new user will be stored to the field 'referred_who' of the existing user.
I have tried using the following method:
class CustomUser(AbstractBaseUser):
...
referred_who = models.ManyToManyField('self', blank=True, symmetrical=False)
class ReferralAward(View):
def get(self, request, *args, **kwargs):
referral_id = self.request.GET['referral_id']
current_referred = self.request.GET['referred']
// referrer
user = get_user_model().objects.filter(referral_id=referral_id)
// user being referred
referred_user = get_user_model().objects.filter(username=current_referred)
for item in user:
previous_referred = item.referred_who
previous_referred.add(referred_user[0])
user.update(referred_who=previous_referred)
And I got the following error:
Cannot update model field <django.db.models.fields.related.ManyToManyField: referred_who> (only non-relations and foreign keys permitted).
I am not sure if this method even works. I have check the Django Admin backend and I realized the 'Referred who' field actually contains all the users. It seems that it only highlightes the user being referred instead of only showing the referred users.
Also, I tried to access the 'referred_who' field in the back-end and it returns 'None'.
Is there a way to stored the users in the 'referred_who' field so that I can see all of the user being referred and access them in the back-end? For instance:
referral_id = self.request.GET['referral_id']
user = get_user_model().objects.filter(referral_id=referral_id)
print(user[0].referred_who)
Can someone show me a better way to do it? Thanks a lot!
You ask how to create a 1-Many field, but in your models you're trying to create m2m. Just change field to FK.
referred_who = models.ForeignKey('self', blank=True).
In case you need to have multiple fks to the same model, you need to specify related_name as well. You can use name of the field for it. More in docs.
I have a django page that displays a list of links. Each link points to the detail page of the respective object. The link contains the pk/id of that object (something like ../5/detailObject/). The list is generated on the backend and has some filtering baked into it, e.g. only generate a link if that object has state x, etc.
Clicking on the links works, but users can still manipulate the url and pass a valid link with an incorrect state (a wrong pk/id is being handled with the get or 404 shortcut).
What is the best practice for handling this kind of scenario with django? Should that kind of filtering be placed in the object's model class instead of using function-based views as I do now?
Function based view:
If you want to restrict a set of objects to a particular user (for instance a user's orders), then you would need to set up the Order model to foreign key to the User model and then look up the order by both id and user:
views.py:
def get_order(request, id=0)
if request.method == 'GET':
try:
order = Order.objects.get(user=request.user, pk=id)
except Order.DoesNotExist:
return redirect(...)
And set up a url to handle:
url(r'^order/(?P<id>\d+)/$', views.get_order, name='get_order_by_id'),
As far as adding a slug field on the model after the fact, set up a second url:
url(r'^order/(?P<slug>[\w-]+)/$', views.get_order, name='get_order_by_slug')
And change the above view logic to first do a lookup by pk if pk is greater than 0 and then redirect back to the function using the slug from the looked up order (this assumes all looked-up records have slugs):
def get_order(request, slug='', id=0)
if request.method == 'GET':
try:
if id > 0:
order = Order.objects.get(user=request.user, pk=id)
return redirect(reverse('get_order_by_slug'), permanent=True, slug=order.slug)
order = Order.objects.get(user=request.user, slug=slug)
except Order.DoesNotExist:
return redirect(...)
You should also put unique=True on the slug field and ensure that the user is authenticated by placing the #login_required decorator on your view.
To restrict orders by a particular status, you could:
Create a set of statuses for your Order model, and then you could:
Pass a value for a kwarg in the view when you filter, or
Create a custom manager on the Order model
There are several ways you could create your statuses:
as a set of choices on the Order model
use the SmartChoices library
as a database field
If you create choices on the Order model, it could be something like this:
class Order(models.model):
STATUSES = (
('PLCD', 'Placed'),
('INTR', 'In Transit'),
('DLVR', 'Delivered')
)
status = models.CharField(max_length=4, default='', choices=STATUSES)
An acquaintance who is a very seasoned Django professional told me about the SmartChoices library. I have not used it yet but would like to try it at some point. The database field option would be my least preferred way of doing this because that seems to me like moving programming variables into the database; however, it would work.
I'm using haystack with whoosh, trying to restrict search results to entries created by the currently logged in user only.
The category model, for which I created an index, has a foreign key:
user = models.ForeignKey(User, editable=False)
And in my custom search view I want to filter like this:
searchqueryset = SearchQuerySet().filter(user=request.user.id)
form = SearchForm(request.GET, searchqueryset=searchqueryset, load_all=True)
if form.is_valid():
query = form.cleaned_data['q']
results = form.search()
In the database there is one entry for table category:
id name user_id
1 test10 1
And the current user id is indeed 1.
But I get No results.
When I do this:
searchqueryset = None
I get the "test10" category entry.
So does anyone know why the user id filter isn't working as expected?
Are you sure that the "user" in your Haystack index holds the integer value of user id? Perhaps it has some other user data(such as username) there, so the comparison simply does not work?
By default the Django user object returns the user name, not the user id.
Certainly not a new question I think, but here it goes:
In my Django based Order system each user (who is not staff) is related to a CustomerProfile object which matches that user to the correct Customer object. This customer users can log in and view outstanding Invoices. To view a customer's invoices you navigate to something like this:
/invoices/customer/97/
(Customer Invoice #97)
Which is fine but I need to incorporate some authentication so a user who is part of a Customer's profile can't view another customer's invoices by manually entering /invoices/customer/92/ for example (invoice 92 belongs to another customer).
I've got this but it's really not good code (and doesn't work):
def customer_invoice_detail(request, object_id):
user = threadlocals.get_current_user()
try:
userprofile = UserProfile.objects.get(user=user)
user_customer = userprofile.customer.id
except UserProfile.DoesNotExist:
user_customer = None
if (request.user.is_authenticated() and user_customer is not null) or request.user.is_staff():
invoice = CustomerInvoice.objects.get(pk=object_id)
product_list = CustomerInvoiceOrder.objects.filter(invoice=object_id)
context = {
'object': invoice,
'product_list': product_list,
}
return render_to_response("invoices/customer_invoice_detail.html", context, context_instance=RequestContext(request))
else:
return HttpResponse("You are not authorised to view this invoice")
Must be a better/easier way to deal with this - any ideas?
Cheers
Add a field to your invoice model called user:
user = models.ForeignKey(User, related_name="invoices")
then retrieve records for a specific user like this:
invoice = CustomerInvoice.objects.get(pk=object_id, user=request.user)
Retrieving invoices for a given user is then trivial with the reverse relation:
request.user.invoices.all()
Also, look at the #login_required decorator.
I'd recommend making some business logic for your customer model. This way you could have a get_invoices() method that returns a list of invoices for that customer only. This method in turn would call a is_authenticated() method that ensures that the current state allows retrieval of protected customer data, or raises an exception.
With this, no matter where your code tries to get invoices for a customer, an exception will always be thrown if the current state does not have access to the invoices, and you won't have to worry about inconsistent behavior as long as you use these methods.