for example i have a model with booleanfield
class Item(BaseModel):
name = models.CharField(max_length=255)
pending = models.BooleanField(default=False)
if user creates new item from admin panel pending field is false and this item won't display on website until other user set this field into True, but this user mustn't be allowed to make change on pending field on his items but he can do this activity on other users items. any solutions?
There are a number of ways to implement this, depending on how you are ultimately going to end up using it. The most straightforward is to add a foreignkey on your Item to the user (assuming you use django auth).
from django.contrib.auth.models import User
class Item(BaseModels):
created_by = models.ForeignKey(User)
name = models.CharField(max_length=255)
pending = models.BooleanField(default=False)
assuming this only ever gets exposed via views, then you can just do:
def some_view(request):
if item_being_edited.created_by = request.user and not item_being_edited.pending:
#rejection goes here
#do stuff
as a sidenote, change your pending field. Either have pending = True mean an item is pending, or have it to be approved = False. It will make things easier later if it makes sense to read it in your head without gymnastics.
Related
I have a built-in User table and a Note table associated with it by key.
class Note(models.Model):
header = models.CharField(max_length=100)
note_text = models.TextField()
data = models.DateField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
That is, a registered user may have several notes. How do I get all these notes from this particular user (who has now visited his page)? I need to get these notes in views.py.
I tried different ways, don't know how to do that.
Hope this answer finds you well ...
First, you already have a user object in your request. But, still you want to filter out notes for other users too, then do
get_user = User.objects.get(id=id) # For any random user
get_user = request.user # For authenticated user
After getting the user, you simply filter it with the Note model like this ...
get_notes = Note.objects.filter(user=get_user)
You are good to go!
Say you have 2 ecom related models: User and Order.
On the Order, you want to keep the User's data because there's a transaction that occurred, and you'd most likely like to keep the customers info, however, you'd also like to allow the customer to delete their account should they choose.
For example, the way I see it is something like:
from django.contrib.auth import get_user_model
from django.db import models
class Order(models.Model):
customer_email = models.EmailField()
customer_first_name = models.CharField(max_length=50)
customer_last_name = models.CharField(max_length=50)
customer = models.ForeignKey(get_user_model(), on_delete=SET_NULL)
def clean(self):
if not self.customer_first_name:
self.customer_first_name = self.customer.first_name
if not self.customer_last_name:
self.customer_last_name = self.customer.last_name
if not self.customer_email:
self.customer_email = self.customer.email
def save(self, *args, **kwargs):
self.full_clean()
return super().save(*args, **kwargs)
But that seems like a bunch of duplication.
Is there a way to go about building that without duplication, or do you just have to live with writing the same fields from the User model but with different names?
If your customer wants to delete his account, you just set is_active=False and an inactive user cant log in to your system any more. that's a best practice.
Delete a user record from your database is not a good decision.
This way you don't need to store the reference of a customer to another table when the user deletes their account. is_active=False we mean it we deleted the custom.
Here you go for such example in another post:
Django-- Deactivate User account instead of deleting it
I am learning django framework, and currently I am facing a problem.
There are two models
class User(models.Model):
name = models.CharField(max_length=30)
...
class Action(models.Model):
user = models.Foreign(User)
action = models.CharField(max_length=30)
createTime = models.DateTimeField(default=django.utils.timezone.now)
Each action from each user is inserted into Action Model, therefore, there are lots of records of each user in Action by different createTime.
Now, I would like to list the latest action of each user, but I have no idea to implement it.
Try something like:
from django.db.models import F, Max
actions = Action.objects.annotate(
most_recent=Max('user__action__createTime')
).filter(createTime=F('most_recent'))
You can query Action with the user you want info on, like this
actions = Action.objects.filter(user=selected_user).order_by("-createTime")
This will sort user actions by date in descending order, to get the latest action:
actions.first()
I am building a django web app which requires a one to many model relationship. I read the docs and it says to use a ForeignKey in the model field.
In my case every user needs to have a one to many field with the job model which will keep track of completed jobs by that user.
Which in django I believe is represented like so:
class User(AbstractBaseUser, PermissionsMixin):
...
job_history = models.ForeignKey(Job, on_delete=models.CASCADE)
The job model looks like this:
class Job(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="jobs")
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=30)
description = models.TextField()
pay = models.FloatField()
category = models.CharField(max_length=3, choices=JOB_CATEGORY_CHOICES)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('jobs:detail', kwargs={
'job_pk': self.id
}
)
In my view I want to add a job to the job_history one to many field. I do not know how to write this however. This is my view so far:
#login_required
def job_hire(request, account_pk, job_pk):
user = get_object_or_404(account_pk)
job = get_object_or_404(job_pk)
# I now need to save the job object in the one to many field of the user object. But how?
messages.success(request, "You have hired an applicant.")
return HttpResponseRedirect(reverse('jobs:find'))
How do I add the job to the one to many field in the user model to save the users jobs?
It is redundant that a User points to a Job and a Job points to a User as you can follow relationships backward.
The user field on the Job should be enough.
You still can lookup all jobs for a User via:
user = User.objects.first()
user.jobs.all() # shows all jobs for the user.
(Note that it would be user.job_set.all() if you hadn't set a related name to jobs)
So in your view this should be enough:
#login_required
def job_hire(request, account_pk, job_pk):
user = get_object_or_404(User, pk=account_pk)
job = get_object_or_404(Job, pk=job_pk)
job.user = user
job.save()
Actually you don't even need to fetch a User-Instance from the database but can do this:
#login_required
def job_hire(request, account_pk, job_pk):
job = get_object_or_404(Job, pk=job_pk)
job.user_id = account_pk
job.save()
Edit:
In case you want to keep both user fields and want to associate a job with a user the mechanics are still the same:
#login_required
def job_hire(request, account_pk, job_pk):
user = get_object_or_404(User, pk=account_pk)
user.job_history_id = job_pk
# or:
# job =get_object_or_404(Job, pk=job_pk)
# user.job_history = job
user.save()
I think it looks good so far. What you'll want to do is first create Job object.
job=Job(user=..., etc.)
job.save()
Then you add that job to User object.
user=User(job_history=job, ...)
user.save()
I am using Django Rest Framework to provide API to a mobile app. I have two models, Order and User. Order has a foreign key relation to User.
For about 1% or so of all my order objects, the User field is null. I've been testing this behavior using cURL.
If I do a cURL without a user object, it tells me "This field is required".
If done with a wrong user object, it tells me that the object does not exist. Both of these are the intended and expected behaviors.
I'm trying to figure out how it is possible for some of the Order objects to be saved without a user field. Is there something I'm not taking into account?
My views:
class OrderList (generics.ListCreateAPIView):
model = Order
serializer_class = OrderSerializer
And serializer:
class OrderSerializer (serializers.ModelSerializer):
user = serializers.SlugRelatedField(slug_field = 'user')
partial = True
class Meta:
model = Order
Models:
class User (models.Model):
uid = models.CharField(max_length =200, unique=True)
class Order (models.Model):
uid = models.ForeignKey (User, related_name = "orders", verbose_name = "User",blank=True, null=True)
You could use two different ModelSerializer classes, one for creation, that makes sure, that an Order object can't be created without a related User and one for updating orders, that passes required=False to the related field's constructor, so that you still can save existing orders that haven't a related User.
Try adding default=None to your models.ForeignKey declaration. You could also just create an anonymous user in the users table and when the user isn't specified it could set the anonymous user instead.