Hello everyone I'm trying top build a task manager web app using django, I need to assign task to one or multiple users I'm using manytomany relation in models.py and in views.py I'm adding created_by user automatically.
My problem is that when I do that I see that no users selected in assigned users but if I add created by user from the form it worked well.
class Task(models.Model):
task_id = models.AutoField(primary_key=True)
shortcode = models.CharField(max_length=15, unique=True, blank=True, null=True)
task_name = models.CharField(max_length=200)
task_progress = models.ForeignKey(TaskProgressStatus, on_delete=models.CASCADE, blank=True, null=True)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True)
task_priority = models.ForeignKey(TaskPriority, on_delete=models.CASCADE)
assigned_to_employee = models.ManyToManyField(User)
paid = models.BooleanField(default=False)
on_account = models.BooleanField(default=False)
currency = models.ForeignKey(Currency, on_delete=models.CASCADE, blank=True, null=True)
net_amount = models.DecimalField(decimal_places=2, max_digits=20, blank=True, null=True)
vat = models.IntegerField(default=11)
quote_validity = models.CharField(max_length=200, default='1 Month from offer date')
delivered = models.BooleanField(default=False)
delivered_date = models.DateTimeField(null=True, blank=True)
creation_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
due_date = models.DateTimeField(null=True, blank=True)
created_by = models.ForeignKey(User, related_name='created_by_username', on_delete=models.CASCADE, null=True, blank=True)
project = models.ForeignKey(Project, null=True, blank=True, on_delete=models.CASCADE)
file_name = models.FileField(upload_to='projects_files', null=True, blank=True)
notes = models.TextField()
def __str__(self):
return str(self.task_name)
#login_required
def addtask(request):
form = taskForm()
if request.method == 'POST':
form = taskForm(request.POST)
if form.is_valid():
newform = form.save(commit=False)
newform.created_by = request.user
newform.save()
return HttpResponseRedirect(request.path_info)
else:
context = {'form':form}
return render(request, 'tasks/add_task.html', context)
Update
As well pointed out by Ahmed I. Elsayed there is some inconsistency in the title of the question, since the created_by field is actually a ForeignKey, not a ManyToManyField.
That being said, your issue is actually with the foreign key.
My suggestion is to first of all be sure that your form is actually valid. You can do that by printing something inside the if form.is_valid() block.
Related
Please I have a project where I want to hide some fields in a form when the category selected belongs to a particular product type. The type of products is Single and Bundle products. So for instance, if I choose something like pens(Bundle) in the form category I should only see quantity in the form fields but if I select something like Desk(single) all fields should be available to fill. How do I implement this in Django? Thank you
My Model
TYPE =(('Single', 'Single'),('Bundle','Bundle'))
class Category(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
pro_type = models.CharField(max_length=50, choices=TYPE, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
def __str__(self):
return f'{self.name}'
class Product(models.Model):
pro_name = models.CharField(max_length=100, blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
quantity = models.IntegerField(default='0', blank=True, null=True)
issue_to = models.ForeignKey('Order',default='', on_delete=models.CASCADE,blank=True, null=True)
serial_num = models.CharField(max_length=100, blank=True, null=True)
model_num = models.CharField(max_length=100, blank=True, null=True)
storage_size = models.CharField(max_length=50, blank=True, null=True)
My views
def add_products(request):
form = ProductCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
obj = form.save(commit=False)
obj.staff = request.user
obj.save()
return redirect('dashboard-products')
else:
form = ProductCreateForm()
context = {
'form': form,
}
This the views.py file.
How can i display the appointments made by the current logged in user?
def user(request):
client = Client.objects.all()
appointments = Appointment.objects.all()
context = {'appointments': appointments, 'client': client,
}
return render(request, 'users/user.html', context)
Here is my Models.py. I need to display the appointments by a user when they are logged in to their profile.
class Appointment(models.Model):
CATEGORY = (
('Plumbing', 'Plumbing'),
('Electrical', 'Electrical'),
('Cleaning', 'Cleaning'),
)
STATUS = (
('Pending', 'Pending'),
('Delivered', 'Delivered'),
)
user = models.ForeignKey(Client, null=True, on_delete=models.SET_NULL)
name = models.CharField(max_length=200, null=True)
worker = models.ForeignKey(Worker, null=True, on_delete=models.SET_NULL)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
task_date = models.DateField(_("Task Date"), blank=True, null=True)
task_location = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
budget = models.FloatField(null=True)
task_description = models.CharField(max_length=1000, null=True)
task_image = models.ImageField(
null=True, blank=True, help_text='Optional.')
def __str__(self):
return str(self.user)
instead of using all() in your query use filter()
all() gives you all the entries in the table.
do something like this:
appointments = Appointment.objects.filter(user = request.user)
the left side "user" inside the filter must be a column in the Appointment model/table. you can pass multiple parameters inside the filter.
Yea it worked. but i had to create a one to one relatioship between appointment and User
I have been trying to build a search functionality in my app but i have stuck on querying for the foreign key field, as it doesn't return anything and the code shows no error. Below is my code.
forms.py
class StockSearchForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['category', 'item_name']
My view where i implemented the search
views.py
def list_items(request):
header = 'List of items'
form = StockSearchForm(request.POST or None)
queryset = Stock.objects.all()
context = {
"form": form,
"header": header,
"queryset": queryset,
}
#Searching an item and category
if request.method == 'POST':
queryset = Stock.objects.filter(category__name__icontains=form['category'].value(),
item_name__icontains=form['item_name'].value()
)
context = {
"form": form,
"header": header,
"queryset": queryset,
}
return render(request, "list_items.html", context)
My models are as follows.
models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return self.name
class Stock(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
#category = models.CharField(max_length=50, blank=True, null=True)
item_name = models.CharField(max_length=50, blank=True, null=True)
quantity = models.IntegerField(default='0', blank=True, null=True)
receive_quantity = models.IntegerField(default='0', blank=True, null=True)
receive_by = models.CharField(max_length=50, blank=True, null=True)
issue_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_by = models.CharField(max_length=50, blank=True, null=True)
issue_to = models.CharField(max_length=50, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
created_by = models.CharField(max_length=50, blank=True, null=True)
reorder_level = models.IntegerField(default='0', blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True)
last_updated = models.DateTimeField(auto_now_add=True, auto_now=False)
export_to_CSV = models.BooleanField(default=False)
def __str__(self):
return self.item_name + '' + str(self.quantity)
So what happens is, I can search just fine the "item_name" field and results come up as required, but when i attempt to search for category no error pops up but no results show up, i kinda feel it's due to some foreign key fields issues but i can't just figure it out, I will much appreciate some help, this thing has been a nightmare for quite a while.
Try doing the following. I assume the form is not being properly used.
if request.method == 'POST' and form.is_valid():
queryset = Stock.objects.filter(category__name__icontains=form.cleaned_data.get('category'),
item_name__icontains=form.cleaned_data.get('item_name')
)
Try this:
queryset=Stock.objects.filter(category__name__icontains=form['category'].value(),
item_name__icontains=form['item_name'].value())
I'm building an app in which I have a model with several manytomany fields and some foreignkey fields, and I need a view that allows me to create all in one page and let me enter multiply times for the manytomanyfields, but I don't know how to deal with a lot of forms in the same page/view.
main model
class Client(models.Model):
company_name = models.CharField(max_length=255, blank=True, null=True)
payment_method = models.CharField(max_length=64, null=True, blank=True)
owner = models.CharField(max_length=100, blank=True, null=True)
operation = models.CharField(max_length=50, blank=True, null=True)
value = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
currency = models.CharField(max_length=55, null=True, blank=True)
address = models.ManyToManyField(Address, blank=True)
contact = models.ManyToManyField(Contact, blank=True)
relationship = models.ManyToManyField(Relationship, blank=True)
attachment = models.ManyToManyField(Attachment, blank=True)
billing = models.ForeignKey(Billing, null=True, blank=True, on_delete=models.CASCADE)
delivery = models.ForeignKey(Delivery, null=True, blank=True, on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True)
note = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.company_name
others models
class Address(models.Model):
address = models.CharField(max_length=256, null=True, blank=True)
number = models.PositiveIntegerField(null=True, blank=True)
district = models.CharField(max_length=32, null=True, blank=True)
city = models.CharField(max_length=32, null=True, blank=True)
country = models.CharField(choices=COUNTRY_CHOICES, max_length=64, null=True, blank=True)
def __str__(self):
return self.address
class Contact(models.Model):
name = models.CharField(max_length=256, blank=False, null=True)
sector = models.CharField(max_length=64, blank=True, null=True)
email = models.EmailField(max_length=256, blank=True, null=True)
phone = PhoneField(blank=True, null=True)
cellphone = PhoneField(blank=True, null=True)
role = models.CharField(max_length=155, blank=True, null=True)
nfe = models.BooleanField(verbose_name='NFE', default=False)
def __str__(self):
return self.name
class Relationship(models.Model):
company = models.CharField(max_length=256, blank=False, null=True)
agent = models.ForeignKey(Vendedor, on_delete=models.DO_NOTHING, blank=True, null=True)
type = models.CharField(choices=TYPE_CHOICES, max_length=32, blank=True, null=True)
contact = models.CharField(max_length=128, blank=True, null=True)
def __str__(self):
return self.company
class Attachment(models.Model):
file = models.FileField(upload_to='post/img/%Y/%m/%d', blank=True, null=True)
note = models.CharField(verbose_name='Observação', max_length=256, blank=True, null=True)
author = models.ForeignKey(User, on_delete=models.DO_NOTHING)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.note
class BankAccount(models.Model):
bank = models.CharField(max_length=64, blank=False, null=True)
type = models.CharField(max_length=32, blank=False, null=True)
payment_method = models.CharField(max_length=64, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.bank
class Billing(models.Model):
name = models.CharField(max_length=256, blank=True, null=True)
address = models.ForeignKey(Address, null=True, blank=True, on_delete=models.CASCADE)
email = models.EmailField(max_length=256, blank=True, null=True)
phone = PhoneField(blank=True, null=True)
contact = models.CharField(max_length=256, blank=True, null=True)
def __str__(self):
return self.name
class Delivery(models.Model):
name = models.CharField(max_length=256, blank=True, null=True)
address = models.ForeignKey(Address, null=True, blank=True, on_delete=models.CASCADE)
email = models.EmailField(max_length=256, blank=True, null=True)
phone = PhoneField(blank=True, null=True)
contact = models.CharField(max_length=256, blank=True, null=True)
def __str__(self):
return self.name
does anyone know what is the best way to deal with this?
Make a python file forms.py and make model forms for all the models you have. Then in views make a function with all the forms. Then in the html file call the different forms together using jinja2. Here is a simple example:
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
Your_website = models.URLField(blank = True)
profile_pic = models.ImageField(upload_to="profile_pics", blank = True)
def __str__(self):
return self.user.username
This model is connected to the django user model by OneToOneField.
Then in forms.py I have created all the model forms for the models.
from django import forms
from django.contrib.auth.models import User
from basic.models import UserProfileInfo
from django.core import validators
class userform(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
re_enter_password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ("username", "email", "password")
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = UserProfileInfo
fields = ('Your_website', "profile_pic")
Then make the view with both the model forms.
def register(request):
registered = False
if request.method == 'POST':
user_form = forms.userform(data = request.POST)
profile_form = forms.UserProfileInfoForm(data = request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = forms.userform()
profile_form = forms.UserProfileInfoForm()
In the html file call both the forms like this:
<div class="container">
<form method="post" enctype="multipart/form-data" class="all_forms">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" class="btn btn-primary" value="Register Now!">
</form>
</div>
This way you don't have to create multiple forms for the models, the user will be asked only one form where all the models will get their separate response from one form.
I am getting a (RelatedObjectDoesNotExist: UserProfile has no site) error in one of my views yet I am able to perform all CRUD operations in the admin with out any errors.
django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: UserProfile has no site.
Excerpt from models.py
class Sites(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
active = models.NullBooleanField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
logo_file_name = models.CharField(max_length=255, blank=True, null=True)
logo_content_type = models.CharField(max_length=255, blank=True, null=True)
logo_file_size = models.IntegerField(blank=True, null=True)
logo_updated_at = models.DateTimeField(blank=True, null=True)
logo_path = models.CharField(max_length=255, blank=True, null=True)
account_type = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
site_str = 'id = {}, name = {}'.format(self.id, self.name)
return site_str
class Meta:
managed = True
db_table = 'sites'
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
site = models.ForeignKey(Sites)
def __str__(self):
user_profile_str = '{}: {}'.format(self.user.username, str(self.site))
return user_profile_str
Excerpt form views.py
#login_required
def client_list(request):
user_profile = UserProfile(user=request.user)
print(user_profile.user.username)
clients = Clients.objects.filter(site_rec=user_profile.site)
return render(request, 'snapreport/clients/all_clients.html', {'clients': clients})
In this line: user_profile = UserProfile(user=request.user) you're creating a new UserProfile for the user. And since you don't assign it a site, user_profile.site is None (or trying to access it throws RelatedObjectDoesNotExist).
You probably want:
user_profile = UserProfile.objects.get(user=request.user)
if the profile already exists (assuming that will have a site).