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
Related
I have a problem with select_related. I don't know what I'm doing wrong but it doesn't work..
models.py
class OrganizerUser(models.Model):
"""This user manage Agents"""
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Agent(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
organizer = models.ForeignKey(OrganizerUser, blank=True, null=True,
on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Lead(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
age = models.IntegerField(default=0)
organizer = models.ForeignKey(OrganizerUser, on_delete=models.CASCADE)
agent = models.ForeignKey(Agent, null=True, blank=True, on_delete=models.SET_NULL)
category = models.ForeignKey(
Category, related_name="categories", null=True, blank=True, on_delete=models.SET_NULL
)
description = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
phone_number = models.CharField(max_length=20)
email = models.EmailField()
converted_date = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
views.py
class LeadsApiView(generics.ListCreateAPIView):
serializer_class = LeadSerializer
permission_classes = [IsAuthenticated, IsAdminOrOrganizer]
def get_queryset(self):
user = self.request.user
#if user.is_staff:
#return Lead.objects.select_related('organizer', 'agent').all()
if user.is_organizer:
return Lead.objects.select_related('organizer').filter(
organizer=user.organizeruser)
else:
return Lead.objects.select_related('agent').filter(agent=user.agent)
serializers.py
class LeadSerializer(serializers.ModelSerializer):
class Meta:
model = Lead
fields = ['id', 'first_name', 'last_name', 'age',
'organizer', 'agent', 'category', 'description', 'date_added',
'phone_number', 'email', 'converted_date'
]
for agents everything is fine. Django makes 3 queries but for other users, it makes extra queries for each existing user.
This solution solved the problem
How to always prefetch_related for a specific django model
class UsersManager(models.Manager):
def get_queryset(self):
return super().get_queryset().select_related('user')
class OrganizerUser(models.Model):
"""This user manage Agents"""
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
objects = UsersManager()
def __str__(self):
return self.user.username
class Agent(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
organizer = models.ForeignKey(OrganizerUser, blank=True, null=True,
on_delete=models.CASCADE)
objects = UsersManager()
def __str__(self):
return self.user.username
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',)
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})
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
As this questions says, I am having trouble displaying a ManyToManyField in the django admin page.
The m2m field that I'm having trouble displaying is comics in the Gig model.
Here is the code for my project:
#models.py file
class Host(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='host')
name = models.CharField("Venue Name", max_length=200)
slug = models.SlugField(allow_unicode=True, blank=True, null=True)
description = models.TextField("Brief Venue Description - [50 Characters Max]", max_length=50, blank=True)
profile_pic = models.ImageField("Profile Picture", upload_to='host/profile_pics',blank=True)
class Gig(models.Model):
host = models.ForeignKey(Host, on_delete=models.CASCADE, blank=True, related_name='host_gigs')
title = models.CharField("Gig Title",max_length=50, null=True)
date_time = models.DateTimeField("Date/Time of Gig", null=True, blank=True)
description = models.TextField("Describe this gig", max_length=150, blank=True)
instructions = models.CharField('Instructions for accepted comics', max_length=200, blank=True, null=True)
comics = models.ManyToManyField("comic.Comic", through='comic.ComicGig',related_name='gig_comics', default=" ")
#in separate app
#models.py
class Comic(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='comic')
dob = models.DateField("Date of Birth", null=True, blank=True)
mobile = PhoneNumberField(null=True, blank=True)
slug = models.SlugField(allow_unicode=True, blank=True, null=True)
class ComicGig(models.Model):
thegig = models.ForeignKey('host.Gig', on_delete=models.CASCADE, default="", related_name='comic_gig')
comic = models.ForeignKey(Comic, on_delete=models.CASCADE, default="")
approved_comic = models.BooleanField(default=False, null=True)
def approve(self):
self.approved_comic = True
self.save()
Here is my Host admin.py file:
class AuthorAdmin(admin.ModelAdmin):
list_display = ('host', 'title',)
filter_horizontal = ('comics',)
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "comics":
kwargs["queryset"] = Gig.objects.filter(comic_gig__approved_comic=True)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Host)
admin.site.register(Gig, AuthorAdmin)
Here is a picture of my Host model in the admin
Here is a picture of my ComicGig model in the admin