I created a Projects model
class Projects(models.Model):
name = models.CharField(max_length=257, unique=True, null=False)
description = models.TextField()
active_issue_count = models.IntegerField(default=0) # functiona bağlanmalı
solved_issue_count = models.IntegerField(default=0) # functiona bağlanmalı
is_active = models.BooleanField()
start_date = models.DateTimeField()
deadline = models.DateTimeField()
and I want to use this project model Projects.objects.all() with this code but when I typed in pyCharm shows me this suggestion
but while I try to use this model
class User(AbstractUser, PermissionsMixin):
objects = UserManager()
related_group = models.CharField
current_project = models.ForeignKey(to='core.Project',
related_name='current_project', on_delete=models.PROTECT, null=True)
total_worked_project = models.IntegerField(default=0) # functiona bağla
active_work_project_count = models.IntegerField(default=0) # functiona bağla
REQUIRED_FIELDS = ['email']
`
I can use User.objects.all() without suggestion what should I do anyone can help me ?
PyCharm just don't follow some object's relation. Here it has no clue that this Model class has related Manager, that you can call with objects.
You can ignore it in PyCharm so it will not bother you.
More actions... => Ignore (...)
Related
I'm trying to create a todo list as part of an application that is used to prompt a user what they must complete before the application is assessed. To achieve this I have created a TaskList model and a Task model belonging to a TaskList.
When I create a new TaskList instance (on a new application) I want to prepopulate the list with some default Tasks that will always be present on every new application. I'm relatively new to Django and Python, so I'm just looking for a push in the right direction.
Is there some kind of Django model initialize function I can override on the TaskList to create these default tasks?
Edit: Django Model Fields
class AssessmentTaskList(models.Model):
title = models.CharField(max_length=140)
assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
class Task(models.Model):
title = models.CharField(max_length=140)
task_list = models.ForeignKey(AssessmentTaskList, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
due_date = models.DateField(blank=True, null=True)
completed = models.BooleanField(default=False)
completed_date = models.DateField(blank=True, null=True)
created_by = models.ForeignKey(User, limit_choices_to={
'groups__name': 'Assessment Staff'}, on_delete=models.SET_NULL, null=True, related_name="applicant_task_created_by")
system_created = models.BooleanField(default=False)
note = models.TextField(blank=True, null=True)
priority = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
staff_task = models.BooleanField(default=False)
You can either load the initial data along with migrations or provide separate fixtures with manage.py loaddata fixturefile.json:
https://docs.djangoproject.com/en/dev/howto/initial-data/
I'd suggest using the fixtures as long as you're just populating the initials and not changing the existing data in some way. In this case, the initial load would be an optional step and could be omitted in production/testing environments (migrations are always mandatory for execution).
EDIT: Actually what you need is to leverage the functionality of Django Signals (specifically django.db.models.signals.post_save model signal):
#receiver(post_save, sender=AssessmentTaskList)
def pre_populate_tasks(sender, instance: AssessmentTaskList, created: bool = False, **kwargs):
if created:
# put the pre-filled tasks here
default_tasks = [Task(task_list=instance, ...)]
Task.objects.bulk_create(default_tasks)
I'm trying to perform a reversed query for a manytomany fields in Django, but it keeps gives me nothing, here is my code
models.py
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=120)
image = models.ImageField(upload_to='products')
branch = models.ManyToManyField(Branch, related_name='branches')
class Branch(models.Model):
area = models.ForeignKey(Area, on_delete=CASCADE)
name = models.CharField(max_length=1200)
phone = models.CharField(max_length=30, null=True, blank=True)
address = models.CharField(max_length=1200, null=True, blank=True)
tax_value = models.DecimalField(decimal_places=2, max_digits=4)
views.py
for branch in product_object.branches.all():
print(branch)
The branch is always nothing !!
For some reason, the related name is not calling it anymore. I called it using the model name (lower cased).
This is how it worked
for branch in product_object.branch.all():
Just to complete your answer above, I think the way you have your model set up is a little misleading and confusing. I think this would improve clarity:
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=120)
image = models.ImageField(upload_to='products')
branches = models.ManyToManyField(Branch, related_name='products')
Since you have a many to many field, a product can have multiple branches, the attribute name should reflect that
When you use the related_name, this would be if you are going from the m2m object. For example, if you have a branch, you could get all it's products by doing branch.products
I'm making a task tracker webapp (the full source code is also available) and I have a database structure where each task has a title, a description, and some number of instances, that can each be marked incomplete/incomplete:
class Task(models.Model):
title = OneLineTextField()
description = models.TextField(blank=True)
class TaskInstance(models.Model):
task = models.ForeignKey(Task, on_delete=models.CASCADE)
is_complete = models.BooleanField()
The task and the instances can be shared separately, although access to the instance should imply read access to the task. This is intended for classroom situations, where the teacher creates a task and assigns it to their students.
class TaskPermission(models.Model):
task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='permissions')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='task_permissions_granted')
shared_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True, related_name='task_permissions_granting')
can_edit = models.BooleanField(default=False)
class Meta:
unique_together = 'task', 'user', 'shared_by',
class TaskInstancePermission(models.Model):
task_instance = models.ForeignKey(TaskInstance, on_delete=models.CASCADE, related_name='permissions')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='task_instance_permissions_granted')
shared_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True, related_name='task_instance_permissions_granting')
can_edit = models.BooleanField(default=False)
class Meta:
unique_together = 'task_instance', 'user', 'shared_by',
My question is how to create a form for TaskInstances with fields for its is_complete, as well as its Task's title and description. Would something like this work? Or would I need to implement my own save and clean methods?
class TaskForm(ModelForm):
class Meta:
model = TaskInstance
fields = ('is_complete', 'task__title', 'task__description')
I think inlineformset_factory is what I'm looking for!
Actually, it does not seem to be useful: it is for multiple forms of the same type, not different types...
I want to display all the reservations created by the currently logged-in user.
Django model: Filtering by user, always
Documentation: Many-to-one relationships
are some of the links I checked but still haven't been able to solve the problem.
Model.py
class Reservation(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
pickup_date = models.DateField()
pickup_time = models.TimeField(blank=True, null=True)
drop_date = models.DateField()
drop_time = models.TimeField(blank=True, null=True)
drop_location = models.CharField(blank=False, max_length=250, choices=LOCATIONS_CHOICES)
reserved_on = models.DateTimeField(auto_now_add=True)
edited_on = models.DateTimeField(auto_now=True)
views.py
class ReservationList(LoginRequiredMixin,ListView):
model = Reservation
context_object_name = 'reservations'
queryset= Reservation.objects.filter(user=request.user)
urls.py
url(r'^reservations/$', ReservationList.as_view(), name='reservations_list'),
I get this error when I run the server
AttributeError: 'module' object has no attribute 'user'
How do I display only reservations created by the currently logged in user. Any guidance is appreciated.
You should override the get_queryset method of ListView, you can't do it by setting a static property (queryset) on the class. Here's how to do it:
class ReservationListView(LoginRequiredMixin, ListView):
model = Reservation
context_object_name = 'reservations'
def get_queryset(self):
return Reservation.objects.filter(user=self.request.user)
I'm pulling my hair out with this. When I attempt to add a 'Product' from my admin page, I'm getting an IntegrityError: main_product.img may not be NULL.
Models.py
class Product(models.Model):
name = models.CharField(max_length=500)
short = models.CharField(max_length=250)
description = models.TextField()
price = models.DecimalField(max_digits=8, decimal_places=2)
in_stock = models.BooleanField()
def __unicode__(self):
return self.name
class ProductImages(models.Model):
product = models.ForeignKey(Product, blank=True)
img = models.ImageField(upload_to='images', blank=True)
caption = models.CharField(max_length=300, blank=True)
class ProductFeatures(models.Model):
product = models.ForeignKey(Product)
feature = models.CharField(max_length=500)
Admin.py
class ProductFeaturesAdmin(admin.TabularInline):
model = ProductFeatures
extra = 1
class ProductImageAdmin(admin.TabularInline):
model = ProductImages
extra = 1
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'in_stock')
inlines = [ProductFeaturesAdmin, ProductImageAdmin]
admin.site.register(Product,ProductAdmin)
I was using Pillow to resize images when being upload, so I had a custom save() function in my ProductImages model. I removed that thinking it was the problem, but it's still not working. As you can tell, I'm really new to Django and Python. Any and all help appreciated.
Edit: forgot to mention that I've added blank=true and null=true to Product.img, then used South to migrate the table.
Edit 2: This is my new ProductImages model.
class ProductImages(models.Model):
product = models.ForeignKey(Product)
img = models.ImageField(upload_to='images', blank=True, null=True)
caption = models.CharField(max_length=300, blank=True)
I used South and ran:
python manage.py schemamigration main --auto
python manage.py migrate main
Still having the error. If I were to add the img field to my Products model, how would I be able to add multiple imgs in the admin panel?
Actually you need to add null=True in the img field, So make it img = models.ImageField(upload_to='images', blank=True, null=True).
The difference is that because blank=True decides that whether the fields will be required by the forms. blank=False means that field cannot be blank and blank=True means field will not be required.
Regarding null=True sets NULL in column of your DB which will solve your issue.