Django Signals and form is_valid - django

This question is related to this. I would like to save my form data in relation to the created signal:
Model :
class PatientInfo(models.Model):
lastname = models.CharField('Last Name', max_length=200)
...
class MedicalHistory(models.Model):
patient = models.OneToOneField(PatientInfo, on_delete=models.CASCADE, primary_key=True)
physician_name = models.CharField('Physician', max_length=200, null=True, blank=True)
...
#receiver(post_save, sender=PatientInfo)
def create_medical_history(sender, **kwargs):
if kwargs.get('created', False):
MedicalHistory.objects.create(patient=kwargs.get('instance'))
View
class MedicalCreateView(CreateView):
template_name = 'patient/medical_create.html'
model = MedicalHistory
form_class = MedicalForm
success_url = '/'
def post(self, request, pk):
form = self.form_class(request.POST)
if form.is_valid():
patiente = form.save(commit=False)
physician_name = form.cleaned_data['physician_name'] # do not delete
patiente.save()
messages.success(request, "%s is added to patient list" % physician_name )
return redirect('index')
else:
print(form.errors)
My code above saves two entry in my MedicalHistory table, patient field is linked to Patient_info.id while the other is empty yet populated with form data.
Any help is greatly appreciated.

Since my MedicalHistory model is has generated its its own automatically, based in my PatientInfo . My way of populating data to existing MedicalHistoryid is by changing:
class MedicalCreateView(CreateView)
to
class MedicalCreateView(UpdateView):
I removed this
def post(self, request, pk):
form = self.form_class(request.POST)
if form.is_valid():
patiente = form.save(commit=False)
physician_name = form.cleaned_data['physician_name'] # do not delete
patiente.save()
messages.success(request, "%s is added to patient list" % physician_name )
return redirect('index')
else:
print(form.errors)

Related

Handling form fields in django for logged in user

Im trying to handle the existing name of a Category, so that users wont be allowed to create 2 categories with the same name, but at the moment its taking all categories from the database, not only for the logged-in user. I dont know how and where to implement request.user.
I`m building an inventory app where everyone creates their own categories and adds items.
Thank you.
This is my model:
class Category(models.Model):
user = models.ForeignKey(User, default=1, on_delete=models.CASCADE,
related_name='category', null=True)
name = models.CharField(max_length=100, null=False, blank=False)
slug = models.SlugField(max_length=100)
created_on = models.DateTimeField(auto_now_add=True)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-timestamp']
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('category_detail', kwargs={'slug': self.slug})
This is my form:
class CategoryForm(forms.ModelForm):
add_category = forms.BooleanField(widget=forms.HiddenInput, initial=True)
class Meta:
model = Category
fields = ['name']
def clean_name(self):
name = self.cleaned_data.get('name')
if (name == ""):
raise forms.ValidationError('This field cannot be left blank')
for instance in Category.objects.all():
if instance.name == name:
raise forms.ValidationError('There is a category with the name ' + name)
return name
This is my view:
#login_required
def index(request):
categories = Category.objects.filter(user=request.user)
items = Item.objects.all()
add_item = ItemForm()
add_category = CategoryForm()
query = None
if request.method == 'POST':
if 'add_item' in request.POST:
add_item = ItemForm(request.POST)
if add_item.is_valid():
form = add_item.save(commit=False)
form.category = get_object_or_404(
Category, name=request.POST.get('category'),
user=request.user)
add_item.save()
return redirect('home')
else:
add_category = CategoryForm(request.POST)
if add_category.is_valid():
category_form = add_category.save(commit=False)
category_form.save()
messages.success(request, f'{name} has been added')
return redirect('home')
Edit Category View
#login_required
def category_edit(request, pk):
category = Category.objects.get(id=pk)
if request.method == 'POST':
form = CategoryForm(request.POST, instance=category)
if form.is_valid():
form.save()
messages.info(request, f'{category.name} has been updated!')
return redirect('home')
else:
form = CategoryForm(instance=category, user=request.user)
context = {
'form': form,
}
return render(request, 'category_edit.html', context)
Ive tried adding user = request.user in the form class, but that resulted in an error Ive tried adding category_form.user = request.user before saving the form but that was still taking names from every other user
Pass the request's user to the form:
class CategoryForm(forms.ModelForm):
add_category = forms.BooleanField(widget=forms.HiddenInput, initial=True)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
class Meta:
model = Category
fields = ['name']
def clean_name(self):
name = self.cleaned_data.get('name')
if (name == ""):
raise forms.ValidationError('This field cannot be left blank')
qs = Category.objects.filter(user=self.user, name=name)
if self.instance.pk:
# EXCLUDE CURRENT INSTANCE TO ENABLE EDIT
qs = qs.exclude(pk=self.instance.pk)
if qs.exists():
raise forms.ValidationError('There is a category with the name ' + name)
return name
then in the view you need to pass the user:
#login_required
def index(request):
categories = Category.objects.filter(user=request.user)
items = Item.objects.all()
add_item = ItemForm()
add_category = CategoryForm(user=request.user)
query = None
if request.method == 'POST':
if 'add_item' in request.POST:
add_item = ItemForm(request.POST)
if add_item.is_valid():
form = add_item.save(commit=False)
form.category = get_object_or_404(
Category, name=request.POST.get('category'),
user=request.user)
add_item.save()
return redirect('home')
else:
add_category = CategoryForm(user=request.user, data=request.POST)
if add_category.is_valid():
category_form = add_category.save(commit=False)
category_form.save()
messages.success(request, f'{name} has been added')
return redirect('home')

update a Model field in DetailView

As a newbie in Django, I'm sure there is something obvious I'm not seeing. I have a user model with a one to one relationship to a userprofile model, where I'm storing the profile photo. I mixed DetailView and Formview because I want the user to go to his details page and update just the photo, but somehow its not working for me. I know I could do the job with UpdateView, but for didactic purposes, can anyone tell me why this is not working? I'm trying to updated the model fields in the form_valid method but this is not working, they just remain with the old values. I thought at the beginning it was the photo that could not be updated because of some errors on my side, but I've tried also updating other string fields and it doesnt work. Here the code: (the commented out fields are the places where I tried updating several model fields using get_object_or_404 and other functions)
class UserDetail(FormMixin, DetailView):
template_name = "users/user_detail.html"
model = User
form_class = forms.UserPhotoForm
def get_success_url(self):
return reverse('users:user_detail', args=[str(self.get_object().pk)])
def get_context_data(self, **kwargs):
user = self.get_object()
form = forms.UserPhotoForm(instance=user)
context = super().get_context_data(**kwargs)
context['user_rating'] = CotizacionReview.objects.filter(cotizacion__user=self.get_object()).aggregate(Avg('nota'))
context['form'] = form
return context
def form_valid(self, form):
form.save()
return super(UserDetail, self).form_valid(form)
def post(self, request, *args, **kwargs):
a = get_object_or_404(User, pk=self.get_object().id).userprofile
form = forms.UserPhotoForm(request.FILES['avatar'], instance=a)
# get_object_or_404(User, pk=self.get_object().id).apellido = '1234'
if form.is_valid():
# print(get_object_or_404(User, pk=self.get_object().id).userprofile.avatar)
# I tried updating several model fields here, but didnt work
# print(request.FILES['avatar'])
return self.form_valid(form)
else:
return self.form_invalid(form)
Here the model:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='profile_pics', default='profile_pics/default-user-icon-4.jpg', blank=True)
telefono = models.CharField(max_length=12, blank=True)
nombre = models.CharField(max_length=64, blank=True)
apellido = models.CharField(max_length=64, blank=True)
link = models.CharField(max_length=256, blank=True)
educacion = models.CharField(max_length=256, blank=True)
experiencia = models.TextField(max_length=512, blank=True)
birthdate = models.DateField(blank=True, null=True)
#receiver(post_save, sender=User)
def update_profile_signal(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
So I achieved it by using commit=False in my form_valid method:
class UserDetail(FormMixin, DetailView):
template_name = "users/user_detail.html"
model = User
form_class = forms.UserPhotoForm
def get_success_url(self):
return reverse('users:user_detail', args=[str(self.get_object().pk)])
def get_context_data(self, **kwargs):
user = self.get_object()
form = forms.UserPhotoForm(instance=user)
context = super().get_context_data(**kwargs)
context['user_rating'] = CotizacionReview.objects.filter(cotizacion__user=self.get_object()).aggregate(Avg('nota'))
context['form'] = form
return context
def form_valid(self, form):
user_instance = form.save(commit=False)
user_instance.avatar = form.cleaned_data['avatar']
user_instance.id = self.get_object().userprofile.id
user_instance.save(update_fields=['avatar'])
return super(UserDetail, self).form_valid(form)
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
But now I have another problem. Every time I update the photo, a new photo is saved to the database. Is there a way of doing this and deleting the old photo? or replacing it?

UNIQUE constraint failed: auth_user.username while updating user info

I am trying to give a user the option to change his/her first/last name through a ModelForm. When I press submit, I get hit with the UNIQUE constraint failed: auth_user.username error. Here are my codes:
students/forms.py:
class EditProfileForm(UserChangeForm):
def clean_password(self):
# Overriding the default method because I dont want user to change
# password
pass
class Meta:
model = User
fields = (
'first_name',
'last_name',
)
students/views.py:
User = get_user_model()
def student_profile_view(request, slug):
if request.method == 'GET':
# forms
edit_name_form = EditProfileForm(instance=request.user)
context = {
'edit_name_form': edit_name_form,
}
return render(request, "students/profile.html", context)
class ChangeNameView(SuccessMessageMixin, UpdateView):
template_name = 'students/edit_profile.html'
model = User
form_class = EditProfileForm
success_message = "Your name has been updated"
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
form.instance.student_profile = StudentProfile.objects.get(slug=request.user.student_profile.slug)
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
"""If the form is valid, save the associated model."""
form.instance.username = self.request.user
self.object = form.save(commit=False)
return super().form_valid(form)
def get_success_url(self):
return reverse('students:student_profile_view', kwargs={'slug': self.object.student_profile.slug})
also fyi, User model is foreign key with StudentProfile.
students/models.py:
class StudentProfile(models.Model):
user = models.OneToOneField(User, related_name='student_profile', on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True)
description = models.CharField(max_length=120, null=True, blank=True)
objects = models.Manager()
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse("students:student_profile_view", kwargs={"slug": self.slug})
I am pretty new to class based view so maybe I'm doing something wrong there?
I assume you do not have the user within the form so you need the form
def get_context_data (self, *args, **kwargs)
ctx = super().get_context_data(*args, **kwargs)
if self.request.method == 'POST':
ctx['form'] = EditProfileForm(instance=self.request.user)
and remove def form_valid()

Django: Can't update database properly

models.py
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=500, verbose_name='Title')
post = models.TextField(verbose_name='Post')
post_time = models.DateTimeField()
update_time = models.DateTimeField()
exists = models.BooleanField(default=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.id:
self.post_time = timezone.now()
# self.exists = True
self.update_time = timezone.now()
return super(Post, self).save(*args, **kwargs)
class PostEditHistory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
title = models.CharField(max_length=500)
body = models.TextField()
edit_time = models.DateTimeField()
views.py
#login_required
def edit_post(request, username, post_id):
other_user = User.objects.get(username=username)
post = Post.objects.get(user=other_user.pk, pk=post_id)
prev_post = post
form = EditPostForm(data=request.POST or None, instance=post)
if form.is_valid():
PostEditHistory.objects.create(
user=request.user,
post=prev_post,
title=prev_post.title,
body=prev_post.post,
edit_time=prev_post.update_time
)
return redirect('single_post', username=username, post_id=post_id)
form.save()
context = {
'form': form
}
return render(request, 'blog_post/edit_post.html', context)
Before saving edited post, I'm trying to save the original post to PostEditHistory model. Every time a post is edited, it performs the same operations. But the code save the edited post to both Post and PostEditHistory model, and the original one gets lost. Help me to solve the problem.
Thanks in advance.
You are leaving of your function before use form.save()
return redirect('single_post', username=username, post_id=post_id)
form.save()
Change the position
form.save()
return redirect('single_post', username=username, post_id=post_id)
Suggestion: You should remove logic from views and handle it only in your models using functions...
Obs.: Dont use straight .objects.get() because if this do not exist will break your page and throw error, use filter to get the values without breaking and check it
class PostHistory(models.Model):
...
#staticmethod
def add_history(user, prev_post):
PostEditHistory.objects.create(
user=user,
post=prev_post,
title=prev_post.title,
body=prev_post.post,
edit_time=prev_post.update_time
)
#login_required
def edit_post(request, username, post_id):
...
post = Post.objects.filter(user=other_user.pk, pk=post_id).first()
prev_post = post if post else None
if form.is_valid():
PostEditHistory.add_history(request.user, prev_post)
form.save()
return redirect('single_post', username=username, post_id=post_id)

Form not saved in database by POST request in django view

My form was working fine but suddenly it stops working and I'm stuck here, help me please!
When I prints form.errors in case of form not valid then it prints
user is a required field.
models.py
class TarWithDocker(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(User, related_name='deployments')
slug = AutoSlugField(populate_from='name', unique=True, name='slug')
archive = models.FileField(upload_to='archives', name='archive')
created_at = models.DateTimeField(default=timezone.now, editable=False)
class Meta:
ordering = ['-created_at']
views.py
class AwdDeployment(LoginRequiredMixin, CreateView):
template_name = 'deployments/awdDeployment.html'
def get(self, request, *args, **kwargs):
return render(request, 'deployments/awdDeployment.html', {})
def post(self, request, *args, **kwargs):
if request.method == 'POST':
form = AwdDeploymentForm(request.POST, request.FILES)
if form.is_valid():
deployment = TarWithDocker()
deployment.name = form.cleaned_data['name']
deployment.user = self.request.user
deployment.archive = form.cleaned_data['archive']
deployment.save()
return HttpResponse("Submitted")
else:
print("not saved")
else:
print("something happnes wrong")
form = AwdDeploymentForm()
return HttpResponseRedirect(reverse('users:deployments:awd'))
You have user in request, but may be not in post data
May be it help you:
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = AwdDeploymentForm(post_data, request.FILES)