CustomUserModel has no user_doctors - django

I have a detail page of clinical operation. And i want to make it accessible for only staff's and doctor's related with this operation with ManyToManyField
For do this i did
class OperationPanelView(LoginRequiredMixin,View):
login_url = reverse_lazy("doctor:login")
def get(self,request,id):
operation = OperationModel.objects.get(id=id)
if request.user.user_doctors not in operation.doctor.all():
if DoctorModel.objects.filter(user = request.user).exists():
return redirect("doctor:panel",request.user.id)
elif request.user.is_staff == True:
return redirect("disease:panel",operation.id)
context = {
"operation":operation,
}
return render(request,"operation_detail.html",context)
this has worked for if request.user.user_doctors is not related with this operation's doctors then it will redirects the user to their own panel.
And also has worked for if request.user.user_doctors is related with operation's doctors then page will open.
But didn't worked for if user is staff and gave this error:
RelatedObjectDoesNotExist at /disease/panel/1
CustomUserModel has no user_doctors.
in line 35: if request.user.user_doctors not in operation.doctor.all():
Then i add this condition:
if request.user.user_doctors:
but this gave the same error too
DoctorModel:
class DoctorModel(models.Model):
BLOOD_TYPE_CHOICES = [
("A+","A+"),
("A-","A-"),
("B+","B+"),
("B-","B-"),
("O+","O+"),
("O-","O-"),
("AB+","AB+"),
("AB-","AB-"),
]
GENDER_CHOICES = [
("Male","Male"),
("Female","Female"),
]
user = models.OneToOneField("account.CustomUserModel",on_delete=models.CASCADE,null=False,blank=False,related_name="user_doctors")
first_name = models.CharField(verbose_name="Ad:",max_length=40,null=False,blank=False)
last_name = models.CharField(verbose_name="Soyad:",max_length=60,null=False,blank=False)
gender = models.CharField(choices=GENDER_CHOICES,max_length=6)
working_field = models.ForeignKey(DoctorField,on_delete=models.SET_NULL,null=True,blank=False,related_name="field_doctors")
phonenumber = PhoneNumberField(null=False,blank=True)
about = models.TextField(verbose_name="Haqqinda:",null=True,blank=True)
is_active = models.BooleanField(default=True)
blood_type=models.CharField(choices=BLOOD_TYPE_CHOICES,max_length=10, null=True,blank=False)
born_date = models.DateField(null=True,blank=False)
OperationModel:
class OperationModel(models.Model):
name = models.CharField(null=True,blank=True,max_length=45)
description = models.TextField(null=True,blank=True)
disease = models.ManyToManyField(DiseaseModel,related_name="disease_operations")
doctor = models.ManyToManyField("doctors.DoctorModel",blank=False,related_name="doctor_operations")
starting_date = models.DateTimeField(auto_now_add=True)
finished_date = models.DateTimeField(auto_now=True)
patient = models.ForeignKey("patients.PatientModel",on_delete=models.DO_NOTHING,related_name="patient_operations")
is_active = models.BooleanField(default=True)
CustomUserModel:
class CustomUserModel(AbstractUser):
username = None
is_accepted = models.BooleanField(default=False)
email = models.EmailField(_("email address"),unique=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
objects = CustomUserManager()
class Meta:
db_table = "user"

Related

Sending data through postman problem in django

I am trying to send data through postman and it takes one field null. So anyone can help me with that. And also I am a beginner to Django.
this is the error
django.db.utils.IntegrityError: null value in column "user_id"
violates not-null constraint DETAIL: Failing row contains (6, MBBS,
Orenburg University, 2019, null).
My models are:
class MyUser(AbstractBaseUser):
gender_type = (('Male','Male'),('Female','Female'))
user_name = (('Doctor','Doctor'),('Patient','Patient'))
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
user_type = models.CharField(choices=user_name, max_length=7)
full_name = models.CharField(max_length=13,null=False)
mobile_number = models.CharField(max_length=13,null=True)
date_of_birth = models.DateField(auto_now_add=True)
gender = models.CharField(choices=gender_type, max_length=10)
blood_group = models.CharField(max_length=25,null=True)
address = models.CharField(max_length=255, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
class Educations(models.Model):
user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='edu_user')
doctor_degree = models.CharField(max_length=25)
university = models.CharField(max_length=25)
passing_year = models.IntegerField()
def __str__(self):
return self.doctor_degree
here the user is for doctor and i'm taking it's foreign key in education model
And its viewset is:
class EducationViewSet(viewsets.ViewSet):
def list(self,request):
eduss=Educations.objects.all()
edu_data_list=[]
for edu in eduss:
edu_data_list.append({
"doctor_degree" : edu.doctor_degree,
"university" : edu.university,
"passing_year" : edu.passing.year,
"doctor_name" : edu.user.full_name,
"doctor_mobile_number": edu.user.mobile_number,
"doctor_date_of_birth": edu.user.date_of_birth,
"doctor_blood_group": edu.user.blood_group,
"doctor_email": edu.user.email
})
return Response({"eduss":edu_data_list})
def create(self,request):
doctor_degree = request.data.get('doctor_degree')
university = request.data.get('university')
passing_year = request.data.get('passing_year')
user = request.user
education = Educations()
education.doctor = user
education.doctor_degree = doctor_degree
education.university = university
education.passing_year = passing_year
education.save()
return Response("successfully saved")

Django - Update a record using a modelform (Table contains Unique_constraint)

The idea would be that the user should be able to go in and update the record using the same form I have provided. I included a unique constraint because the idea was that a Requisition can contain multiple Requisition_lines. For the initial phase I have hard coded sequence=1. It saved the record initially but I am now getting an Integrity error when i try to update the record using update_or_create. Any help would be appreciated! Let me know if any more information is needed.
Models.py
class Requisition(models.Model):
username = models.ForeignKey(
'users.CustomUser', on_delete=models.CASCADE, related_name='req_user')
signature = models.CharField(max_length=10, blank=True, null=True)
status = models.ForeignKey('RequisitionStatus', related_name='req_status', on_delete=models.CASCADE)
class RequisitionLine(models.Model):
parent_req = models.ForeignKey('Requisition', on_delete=models.CASCADE, related_name='par_req_line' )
sequence = models.PositiveIntegerField()
item_code = models.ForeignKey(
'items.ItemMaster', on_delete=models.CASCADE, related_name='req_item', blank=True, null=True)
description = models.CharField(max_length=50, blank=True)
extra_information = models.TextField(blank=True)
quantity = models.PositiveIntegerField(blank=True, default=0,null=True)
price = models.DecimalField(max_digits=19, decimal_places=2, blank=True, default=0.00,null=True)
purchase_order = models.CharField(max_length=9, blank=True,null=True)
po_line = models.PositiveSmallIntegerField(blank=True,null=True)
req_delivery_date = models.DateField(blank=True,null=True)
act_delivar_date = models.DateField(blank=True, null=True)
class Meta:
unique_together = ('parent_req','sequence')
Views.py
def update_requisition(request, id):
current_req = Requisition.objects.get(id=id)
if current_req.username == request.user:
data = { 'parent_req': id }
if request.method == "POST":
req_form = ReqForm(request.POST, instance = current_req)
if req_form.is_valid():
req_form_line, created = RequisitionLine.objects.update_or_create(
parent_req = current_req,
sequence = 1,
description = req_form.cleaned_data['description'],
extra_information = req_form.cleaned_data['extra_information'],
quantity = req_form.cleaned_data['quantity'],
price = req_form.cleaned_data['price'],
defaults = {'parent_req':current_req,
'sequence': 1 })
return(redirect(reverse('requisition:req_history')))
else:
try:
req_form_line = RequisitionLine.objects.get(parent_req=current_req, sequence=1)
req_form = ReqForm(initial=data, instance = req_form_line)
except RequisitionLine.DoesNotExist:
req_form = ReqForm(initial=data, instance = current_req)
return render(request, 'req/update_req.html' , {'current_req': current_req, 'req_form': req_form})
else:
return HttpResponseRedirect(reverse('requisition:req_history'))
Your usage of the update_or_create function is wrong. You misunderstand the keyword defaults (see docs). You need to put all your fields to update into this dictionary:
req_form_line, created = RequisitionLine.objects.update_or_create(
parent_req = current_req,
sequence = 1,
defaults = {
description : form.cleaned_data['description'],
extra_information : req_form.cleaned_data['extra_information'],
quantity : req_form.cleaned_data['quantity'],
price : req_form.cleaned_data['price'],
})

How can I deal with filter object in HTML

I tried with above to see how I can use with objects in showing in homepage.
few people recommend me to use this code below
infos = Info.objects.select_related('user','group', 'user_number').filter(id = newc.id)
and my model code is like this.
class Group(models.Model):
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Type(models.Model) :
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Info(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(null=True, blank=True, unique=True)
memo = models.CharField(max_length=200, null=True)
birthday = models.CharField(max_length=12,null=True, blank=True)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
class Number(models.Model):
number = models.CharField(max_length=11)
info = models.ForeignKey(Info, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
type = models.ForeignKey(Type, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
and in my views.py.
def addcontract(request) :
if request.user.is_authenticated :
pk = request.user.id
name = request.POST['name']
email = request.POST['email']
memo = request.POST['memo']
birthday = request.POST['birthday']
group_id = request.POST['group_id']
type_id = request.POST['type_id']
number = request.POST['number']
user_id = pk
newc = Info(
name = name, email = email, memo = memo, birthday = birthday,
group_id = group_id, user_id = pk)
newc.save()
number = Number(number = number, type_id= type_id, user_id = pk, info = newc)
number.save()
infos = Info.objects.select_related('user','group', 'user_number').filter(id = newc.id)
grouplist = Group.objects.filter(user_id = request.user.id)
typelist = Type.objects.filter(user_id = request.user.id)
return render(request, 'detail.html',
{'infos':infos, 'grouplist':grouplist, 'typelist':typelist})
My previous question was
How to connect all related DB with FK in Django?
it doesn't work in homepage at all to show from object that's why I tried to check in homepage then problem occured.
user_id is only for account. I need to use Info_id as a fk all in query
please help this.

DRF PUT request on unique model field

I have the following model:
class Movie(models.Model):
name = models.CharField(max_length=800, unique=True)
imdb_rating = models.IntegerField(null=True)
movie_choice = (
('Act', 'Action'),
...........
)
movie_type = models.CharField(max_length=3, choices=movie_choice)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Hiren(models.Model):
movie = models.ForeignKey(Movie)
watched_full = models.BooleanField(default=True)
rating = models.IntegerField()
source = models.CharField(max_length=500, null=True)
watched_at = models.DateField()
quality_choice = (
..................
)
video_quality = models.CharField(max_length=3, choices=quality_choice)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
and serializer:
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = '__all__'
class HirenSerializer(serializers.ModelSerializer):
movie = MovieSerializer()
class Meta:
model = Hiren
fields = ('movie', 'id', 'watched_full', 'rating', 'source', 'video_quality', 'watched_at')
def update(self, instance, validated_data):
instance.movie.name = validated_data.get('movie', {}).get('name')
instance.movie.imdb_rating = validated_data.get('movie', {}).get('imdb_rating')
instance.movie.movie_type = validated_data.get('movie', {}).get('movie_type')
instance.watched_full = validated_data.get('watched_full', instance.watched_full)
instance.rating = validated_data.get('rating', instance.rating)
instance.source = validated_data.get('source', instance.source)
instance.video_quality = validated_data.get('video_quality', instance.video_quality)
instance.watched_at = validated_data.get('watched_at', instance.watched_at)
instance.movie.save()
instance.save()
return instance
When I try to send a put request without changing name field from Movie model it throws an error
{
"movie": {
"name": [
"movie with this name already exists."
]
}
}
However, I can perfectly update any other field if I change the name field's value each time.
The problem is in Movie model defined by you.
When you set the name field of Movie model as unique = True,then any new entry with same movie name will always throw an error.
In your model,
class Movie(models.Model):
name = models.CharField(max_length=800, unique=True)
imdb_rating = models.IntegerField(null=True)
movie_choice = (
('Act', 'Action'),
...........
)
movie_type = models.CharField(max_length=3, choices=movie_choice)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
If you want to add two entries with the same name,remove the line unique = True or make sure to save every entry with a different name.
Or,if you want to update the record/entry then you don't need to assign a value for name field,just remove that line from your code,alternatively check if the name of the movie is already same with an improvement in the code like this :
class HirenSerializer(serializers.ModelSerializer):
movie = MovieSerializer()
class Meta:
model = Hiren
fields = ('movie', 'id', 'watched_full', 'rating', 'source', 'video_quality', 'watched_at')
def update(self, instance, validated_data):
movie_name = validated_data.get('movie', {}).get('name')
if movie_name != instance.movie.name :
instance.movie.name = movie_name
instance.movie.imdb_rating = validated_data.get('movie', {}).get('imdb_rating')
instance.movie.movie_type = validated_data.get('movie', {}).get('movie_type')
instance.watched_full = validated_data.get('watched_full', instance.watched_full)
instance.rating = validated_data.get('rating', instance.rating)
instance.source = validated_data.get('source', instance.source)
instance.video_quality = validated_data.get('video_quality', instance.video_quality)
instance.watched_at = validated_data.get('watched_at', instance.watched_at)
instance.save()
return instance
Hope this helps,Thanks.

How to set a Django Boolean value to True when by default, it is false?

I have a django view where users can sign up. For any user who signs up from this point forward, I would like to set the boolean value to True.
class Person(models.Model):
user = models.OneToOneField(User, primary_key=True)
facebook_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
twitter_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
suggested_person = models.BooleanField(default=False)
userPic = models.CharField(max_length=128, blank=True)
phoneNum = models.CharField(max_length=128, blank=True)
Sign-Up Django view:
#csrf_exempt
def signup(request):
if request.method == 'POST':
# Parse the JSON
data = json.loads(request.raw_post_data)
# Check if the user already exists
if User.objects.filter(username = data['username']).exists():
return HttpResponse("Username already exists")
# If not then create new user with the supplied info
else:
newUser = User()
newUser.username = data['username']
newUser.email = data['email']
newUser.set_password(data['password'])
newUser.first_name = data['firstName']
newUser.last_name = data['lastName']
newUser.save()
newPerson = Person(user = newUser, phoneNum = data['phoneNum'], userPic = data['userPic'], userCover = data['userCover'])
if 'token' in data:
if Person.objects.filter(token=data['token']).exists():
oldToken = Person.objects.get(token=data['token'])
oldToken.token = None
oldToken.save()
newPerson.token = data['token']
newPerson.save()
else:
newPerson.token = data['token']
newPerson.save()
#perhaps like this? newPerson.suggested_person =True
newPerson.save()
newUser.relationships.add(newUser)
return HttpResponse(str(newUser.id))
# If not POST
else:
return HttpResponse("Signup here People")
How can I go about making any user who signs up from this point forward a 'suggested_person'?
If you can't or don't want to change the default definition on your model, you can either pass in your desired value when creating your Person instance:
newPerson = Person(user = newUser, phoneNum = data['phoneNum'], userPic = data['userPic'], userCover = data['userCover'], suggested_person=True)
Or you can set the attribute prior to saving:
newPerson.suggested_person = True