Is the model definition correct in django - django

I have defined below models in my models.py file.
I am trying to populate Allocation table only for the rows where member is null.
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Member(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
DESIGNATION = [
('Developer', 'Developer'),
('Tester', 'Tester'),
('Support', 'Support'),
]
name = models.CharField(max_length=200, null=True)
role = models.CharField(max_length=100, null=True, choices=DESIGNATION)
email = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Task(models.Model):
CATEGORY = [
( 'Low', 'Low'),
('Medium', 'Medium'),
('Urgent', 'Urgent'),
]
STATUS = [
('Not Started', 'Not Started'),
('In Progress', 'In Progress'),
('Completed', 'Completed'),
]
name = models.CharField(max_length=200, null=True)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
description = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
member = models.ForeignKey('Member', null=True, on_delete=models.CASCADE)
task_status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return self.name
class Allocation(models.Model):
member = models.ForeignKey('Member', null=True, on_delete=models.CASCADE)
task = models.OneToOneField('Task', null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.task.name
And here is my view for task allocation
def allocate_task(request, pk):
task_details = Task.objects.get(id=pk)
form = TaskAllocateForm(instance=task_details)
if request.method == 'POST':
form = TaskAllocateForm(request.POST, instance=task_details)
if form.is_valid():
form.save()
return redirect('/')
forms.py:
class TaskAllocateForm(ModelForm):
class Meta:
model = Task
fields = ['name', 'member', 'task_status']
I am creating new tasks with create method which is working fine.
And I am trying to assign that task to a member from Member table.
But, the form.save() method in the allocate_task view is not reflecting changes in Allocation table

Related

Cannot query "sabbir": Must be "User" instance

I mean when a doctor uploads a file, the patients that are under that doctor can see that file. In the same way when a patient uploads his prescription only that doctor can see.
views.py
def practitioner_tab(request, practitioner_id):
client = Appointment.objects.get(id=practitioner_id)
practitioner = Profile.objects.get(user=client.practitioner)
notes = AddNote.objects.filter(user=client.practitioner)
appointments=Appointment.objects.filter(user=client.practitioner)
context = {
'client': client,
'practitioner': practitioner,
'notes': notes,
'appointments': appointments,
}
return render(request, 'client/practitioner_tab.html', context)
models.py
class Profile(models.Model):
phone = models.CharField(max_length=50, blank=True, null=True)
avatar = models.ImageField(max_length=50, blank=True, null=True,
upload_to='practitioner/avatar')
start_date = models.DateTimeField(auto_now_add=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Appointment(models.Model):
Appointments = [
('audio', 'audio'),
('video', 'video'),
]
practitioner = models.ForeignKey(Profile,
on_delete=models.CASCADE, related_name='practitioner')
time = models.DateTimeField()
appointment = models.CharField(max_length=100,
choices=Appointments)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username

Django Import Export, Filter ForeignKey objects connected to users

I'm building an import excel files system for every leads whit an import-export library. On the Website, each user must be able to import his leads and make sure that they are viewed only by him. In all other cases, I filtered the "organisation" field linked to a UserProfile model through the views.py. But now I don't know how to filter the field organisation for a specific user. At the moment I can import the excel files from the template but leave the organisation field blank. Help me please I'm desperate
Models.py
class Lead(models.Model):
nome = models.CharField(max_length=20)
cognome = models.CharField(max_length=20)
luogo=models.CharField(max_length=50, blank=True, null=True, choices=region_list)
città=models.CharField(max_length=20)
email = models.EmailField()
phone_number = models.CharField(max_length=20)
description = models.TextField()
agent = models.ForeignKey("Agent", null=True, blank=True, on_delete=models.SET_NULL)
category = models.ForeignKey("Category", related_name="leads", null=True, blank=True, on_delete=models.SET_NULL)
chance=models.ForeignKey("Chance",related_name="chance", null=True, blank=True, on_delete=models.CASCADE)
profile_picture = models.ImageField(null=True, blank=True, upload_to="profile_pictures/")
converted_date = models.DateTimeField(null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE,null=True, blank=True)
objects = LeadManager()
age = models.IntegerField(default=0)
def __str__(self):
return f"{self.nome} {self.cognome}"
class User(AbstractUser):
is_organisor = models.BooleanField(default=True)
is_agent = models.BooleanField(default=False)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
Views.py
def simple_upload(request):
if request.method == 'POST':
Lead_resource = LeadResource()
dataset = Dataset()
newdoc = request.FILES['myfile']
imported_data = dataset.load(newdoc.read(),format='xlsx')
#print(imported_data)
for data in imported_data:
value = Lead(
data[0],
data[2],#nome
data[3],#cognome
data[5],#luogo
data[7],#città
data[8],#email
data[9],#numero telefono
data[11],#desc
)
value.save()
result = Lead_resource.import_data(dataset, dry_run=True) # Test the data import
if not result.has_errors():
Lead_resource.import_data(dataset,dry_run=False) # Actually import now
return render(request, 'input.html')
Resources.py
class LeadResource(resources.ModelResource):
nome = fields.Field(attribute='nome', column_name='nome')
luogo = fields.Field(attribute='luogo', column_name='regione')
class Meta:
model = Lead
report_skipped=True
admin.py
#admin.register(Lead)
class PersonAdmin(ImportExportModelAdmin):
readonly_fields = ('date_added',)

Django class based view, save in another model after CreateView

I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. How can I do that?
My models.py:
class Asset(models.Model):
# Relationships
room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True)
model_hardware = models.ForeignKey("asset_app.Model_hardware", on_delete=models.SET_NULL, blank=True, null=True)
# Fields
name = models.CharField(max_length=30)
serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None)
mac_address = models.CharField(max_length=30, null=True, blank=True)
purchased_date = models.DateField(null=True, blank=True)
may_be_loaned = models.BooleanField(default=False, blank=True, null=True)
is_loaned = models.BooleanField(default=False, blank=True, null=True)
missing = models.BooleanField(default=False, blank=True, null=True)
notes = HTMLField(default="")
ip = models.CharField(max_length=90, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Loan_asset(models.Model):
# Relationships
asset = models.ForeignKey("asset_app.Asset", on_delete=models.SET_NULL, blank=True, null=True)
loaner_type = models.ForeignKey("asset_app.Loaner_type", on_delete=models.SET_NULL, blank=True, null=True)
location = models.ForeignKey("asset_app.Locations", on_delete=models.SET_NULL, blank=True, null=True)
# Fields
loaner_name = models.CharField(max_length=60)
loaner_address = models.TextField(max_length=100, null=True, blank=True)
loaner_telephone_number = models.CharField(max_length=30)
loaner_email = models.EmailField()
loaner_quicklink = models.URLField(null=True, blank=True)
loan_date = models.DateField()
return_date = models.DateField()
notes = HTMLField(default="")
returned = models.BooleanField(default=False, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Meta:
pass
def __str__(self):
return str(self.loaner_name)
def get_absolute_url(self):
return reverse("asset_app_loan_asset_detail", args=(self.pk,))
def get_update_url(self):
return reverse("asset_app_loan_asset_update", args=(self.pk,))
my urls.py
`path("asset_app/loan_asset/create/", views.Loan_assetCreateView.as_view(), name="asset_app_loan_asset_create")`,
my views.py
class Loan_assetCreateView(generic.CreateView):
model = models.Loan_asset
form_class = forms.Loan_assetForm
Here are some options:
override form_valid method that's being called in post method implementation, so that after form will be validated (model instance saved), you'll be able to set the flag through foreign key/by creating Asset instance:
...
def form_valid(self, form):
self.object = form.save()
if self.object.asset:
self.object.asset.is_loaned = True
else:
self.object.asset = Asset.objects.create(is_loaned=True)
return HttpResponseRedirect(self.get_success_url())
use Django signals:
#receiver(post_save, sender=Loan_asset)
def create_transaction(sender, instance, created, **kwargs):
if created:
Asset.objects.create(is_loaned=True)
You can override the post method in your Loan_assetCreateView.
class Loan_assetCreateView(generic.CreateView):
model = models.Loan_asset
form_class = forms.Loan_assetForm
def post(request, *args, **kwargs):
response = super().post(request, *args. **kwargs)
# Do your thing
return response

django form is not picking data which is already in database

How do I update my form as the
form.instance.users = request.user
is not working however if I print request.user on terminal it prints the username of the user currently logged in.
Also in this form I want to pick existing data from that user to display in the form to update it.
The save form button return HttpResponse saved successfully but the data is not stored in the database.
models.py
class BasicDetails(models.Model):
GENDERS = (
('M', 'Male'),
('F', 'Female'),
('O', 'Others'),
)
users = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
father_name = models.CharField(max_length=50, blank=True, null=True)
mother_name = models.CharField(max_length=50, blank=True, null=True)
date_of_birth = models.DateField(blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDERS)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.first_name+" "+ self.last_name
class Education(BasicDetails):
current_year = datetime.date.today().year
YEAR_CHOICES = [(r, r) for r in range(2000, datetime.date.today().year+2)]
course_name = models.CharField(max_length=100, blank=True, null=True)
university_board_name = models.CharField(
max_length=200, blank=True, null=True)
passing_year = models.IntegerField(
choices=YEAR_CHOICES, default=current_year, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(default=timezone.now)
forms.py
class BasicDetailsForm(forms.ModelForm):
class Meta:
model = BasicDetails
fields = '__all__'
exclude = ['users']
class EducationForm(forms.ModelForm):
class Meta:
model = Education
fields = '__all__'
exclude = ['users']
views.py
#login_required
def View(request):
education = EducationForm()
education.instance.users = request.user
if request.method =="POST":
print(request.user.id)
education = EducationForm(request.POST,instance=request.user)
if education.is_valid():
education.save(commit=True)
return HttpResponse("Saved Successfully")
else:
education = EducationForm()
return render(request, 'app/view.html',{'education':education})

replacing dropdown lookup with related user field

In a form I have a drop down of usernames, this is referenced in the 'taken_by' field. I would like to display first_name and last_name, this is achieved through the __str__ but I can't seem to get it to function, the list of usernames are presented but not the firstname. Suggestions welcome.
from django.contrib.auth.models import User
from django.conf import settings
class Sample(models.Model):
sample_id = models.AutoField(primary_key=True)
area_easting = models.IntegerField(choices = EASTING_CHOICES)
area_northing = models.IntegerField(choices = NORTHING_CHOICES)
context_number = models.IntegerField()
sample_number = models.IntegerField()
material_type = models.CharField(max_length=200, default='', blank=True, null=True, choices = MATERIALS)
weight = models.DecimalField(max_digits=6, decimal_places=2)
description = models.CharField(max_length=500, default='', blank=True, null=True)
recovery_method = models.CharField(max_length=200, default='', blank=True, null=True, choices = RECOVERY_METHODS)
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='taken_by', on_delete = models.PROTECT)
comments = models.CharField(max_length=1000, default='', blank=True, null=True)
def __str__(self):
return self.taken_by.first_name
# return str(self.sample_id)
# return str(self.firstname)+ '-' +str(self.lastname)
# return u'%s %s' % (self.first_name, self.last_name)
Form setup as requested
class BotanySampleFilterForm(forms.ModelForm):
class Meta:
model = Sample
fields = (
# 'botany_id',
'sample_id',
'area_easting',
'area_northing',
'context_number',
'sample_number',
'material_type',
'weight',
'description',
'recovery_method',
'taken_by',
'comments'
)