how to change model fields value in CreateView - python

I currently have the following in my CreateView:
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ["title", "content", "quiet_tag", "camera_tag"]
def form_valid(self, form):
form.instance.author = self.request.user
user = self.request.user.profile
print("hello")
# print(form.instance.title) <--- what I want to pass into user.participating_in
# user.participating_in = Post(form.instance.title) <--- where I'm stuck
print(user.participating_in) <--- returns nothing even though form.instance.title gives me the correct title
return super().form_valid(form)
In my models I have the following
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
participating_in = models.ForeignKey(Post, on_delete=models.CASCADE, default=None)
image = models.ImageField(default="default.jpg", upload_to="profile_pics")
def __str__(self):
return f"{ self.user }'s Profile"
When the user is created they automatically get a profile and their participating_in field is set to null. When the user makes a post I want participating_in to be set to the title of the post they're making but I can't seem to figure out how to change the value for participating_in inside of PostCreateView.

Related

Django auto save the current user in the model on save

I am trying to save the user automatically when saving new data. I mean I want to save the user id for the user who is posting a new thing (submitting a form) without asking that user to choose his account from the droplist (the droplist from the User ForeignKey)
Try 1 :
models.py
class Feedback(models.Model):
.
.
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
editable=False,
)
def save(self, *args, **kwargs):
self.author = get_user_model().objects.get(id=2) #############
return super().save(*args, **kwargs)
It's working if I hard-coded the user-id get(id=2). How can I make the id dynamic?
Edit:
Try 2 :
I tried also doing it with the view:
models.py
class Feedback(models.Model):
.
.
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
editable=False,
null=True
blank=True
)
# without save()
views.py
class FeedbackForm(ModelForm):
class Meta:
model = Feedback
fields = "__all__"
class FeedbackListView(generics.ListCreateAPIView):
queryset = Feedback.objects.all()
serializer_class = FeedbackSerializer
from_class = FeedbackForm
permission_classes = [FeedbackPermission,] # I also tried AllowAny
def form_valid(self, form, FeedbackForm):
obj = form.save(commit=False) # I also tried self.obj = ...
obj.author = self.request.user # I also tried self.obj.author = ...
obj.save() # I also tried self.obj.save()
return super().form_valid(form)
But on the second try (with forms), the author field remains null.
ListCreateAPIView don't have method form_valid, look at this
In your class FeedbackListView you need to do something like this:
class FeedbackListView(generics.ListCreateAPIView):
queryset = Feedback.objects.all()
serializer_class = FeedbackSerializer
def perform_create(self, serializer):
# The request user is set as author automatically.
serializer.save(author=self.request.user)

ValueError at /post/new/ Cannot assign "<SimpleLazyObject:<User: chetan>>": "Post.author" must be a "User" instance

I keep getting this error "ValueError at /post/new/
Cannot assign ">": "Post.author" must be a "User" instance."
class User(models.Model):
user = models.OneToOneField(User,on_delete = models.CASCADE)
def __str__(self):
return self.user.username
class Post(models.Model):
author = models.ForeignKey('User.User',related_name="posts",on_delete = models.CASCADE)
text = models.TextField()
created_at = models.DateTimeField(default = timezone.now)
updated_at = models.DateTimeField(blank = True,null =True)
def update(self):
updated_at = timezone.now()
self.save()
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
views.py
class CreatePostView(LoginRequiredMixin, CreateView):
# form_class = forms.PostForm
fields = ['text',]
model = Post
def form_valid(self, form):
self.object = form.save(commit=False)
form.instance.author = self.request.user
self.object.save()
return super().form_valid(form)
Please help!
You here made two User objects, the User object from django.contrib.auth and one from the User app. In order to retrieve the related User object from the User app, you can use self.request.user.user (given you of course constructed that related object):
class CreatePostView(LoginRequiredMixin, CreateView):
# form_class = forms.PostForm
fields = ['text',]
model = Post
def form_valid(self, form):
self.object = form.save(commit=False)
form.instance.author = self.request.user.user
self.object.save()
return super().form_valid(form)
It is however very confusing to name two models the same. It might be better to just use Profile for example. In that case it would be form.instance.author = self.request.user.profile which is also more readable.

Django Inline form validation ignored partly filled form

I have got the code from https://github.com/adandan01/mybook, the code is working fine, even when I have updated it to Django 2. It's very simple project for adding a person in a form, and his/her relatives in the inline form. Everything works but when I add a relative name and forget to add his relationship, and submitted the form, unfortunately, that record will not pass the validation but will give no error messages as well. Django will ignore the entire record. For example, the record for Hawra in the image, will not be saved and Django will remove it. For this simple App there are only two fields to be filled (name and relationship), but I'm working on app with 8 fields, and it will be difficult to lose the data. is there any way to make django do the validation in the formset/subform as long as any fields have data and will ask the user to fill all required fields?
models.py:
class Profile(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
created_date = models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('profile-update', kwargs={'pk': self.pk})
def __unicode__(self):
return "%s %s" % (self.first_name, self.last_name)
class FamilyMember(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.PROTECT)
name = models.CharField(max_length=100)
relationship = models.CharField(max_length=100)
form.py
class ProfileForm(ModelForm):
class Meta:
model = Profile
exclude = ()
class FamilyMemberForm(ModelForm):
class Meta:
model = FamilyMember
exclude = ()
FamilyMemberFormSet = inlineformset_factory(Profile, FamilyMember,
form=FamilyMemberForm, extra=1)
views.py
class ProfileCreate(CreateView):
model = Profile
fields = ['first_name', 'last_name']
class ProfileFamilyMemberCreate(CreateView):
model = Profile
fields = ['first_name', 'last_name']
success_url = reverse_lazy('profile-list')
def get_context_data(self, **kwargs):
data = super(ProfileFamilyMemberCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['familymembers'] = FamilyMemberFormSet(self.request.POST)
else:
data['familymembers'] = FamilyMemberFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
familymembers = context['familymembers']
with transaction.atomic():
self.object = form.save()
if familymembers.is_valid():
familymembers.instance = self.object
familymembers.save()
return super(ProfileFamilyMemberCreate, self).form_valid(form)
I found the solution here django inline_formset - form.empty_permitted = False doesn't work
I had to add the following code before if (familymembers.is_valid():...) in the create and update class, so, now Django will show the error if I entered data in the Name field only and will tell me the Relationship field is required.
if familymembers.is_valid() == False:
return self.render_to_response(self.get_context_data(form=form,familymembers=familymembers ))

Edit another model after creating an instance

I am finding it difficult to achieve the following scenario:
In my app, a user creates a project, now to that project he can link a previous team that he created or create a new team.
A team can be part of many projects but a project is linked to only ONE team.
models.py:
class Team(models.Model):
team_name = models.CharField(max_length=100, default = '')
team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
def __str__(self):
return self.team_name
class TeamMember(models.Model):
user = models.ForeignKey(MyUser)
team = models.ForeignKey(Team)
def __str__(self):
return self.user.first_name
class Project(models.Model):
name = models.CharField(max_length=250)
team_id = models.ForeignKey(Team, blank=True, null=True)
project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
def get_absolute_url(self):
return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk})
def __str__(self):
return self.name
views.py:
class ProjectCreate(CreateView):
model = Project
fields = ['name']
template_name = 'project_form.html'
def form_valid(self, form):
form.instance.project_hr_admin = self.request.user
return super(ProjectCreate, self).form_valid(form)
class ProjectDetailView(generic.DetailView):
model = Project
template_name = 'project_details.html'
class TeamCreate(CreateView):
model = Team
fields = ['team_name']
template_name = 'team_form.html'
def form_valid(self, form):
obj = form.save(commit=False)
obj2 = Project.team_id
obj2 = obj.team_id
obj2.save()
print("sucess")
I would like that when a user creates a team, and if the team is created it successfully. Add automatically to the Project models with the corresponding team_id.
Any help would be appreciated. Thanks in advance!
Well, you can get the project with your user id which has a team_id null.
In the form_valid method of your TeamCreate() view:
def form_valid(self, form):
valid = super(TeamCreate, self).form_valid(form)
obj = form.save()
obj2 = Project.objects.get(project_hr_admin=self.request.user, team_id=None)
obj2.team_id = obj
obj2.save()
return valid
Here you just get the Project which has your user as admin and a null team_id.
Warning though, if an admin create two projects with no team, the request Project.objects.get(...) will raise an error as it will return more than one object.
So you must be sure it will always be one project and then one team created.
Hope it helps.

django class based view many to many field display selected values

I have a form created with Update View class based view. It displays every value in input type fields from database, except values of many to many field.
What should i insert into view or maybe model so user will see what options they have slected (like in built-in admin module).
This is my view:
class StudentUpdateView(LoginRequiredMixin, UpdateView):
form_class = StudentForm
model = Student
template_name = 'forms/modify.html'
def get_context_data(self, **kwargs):
context = super(StudentUpdateView, self).get_context_data(**kwargs)
context['year'] = Setting.objects.get(id=2)
return context
def form_valid(self, form):
if self.request.is_ajax():
self.object = form.save()
return HttpResponse(json.dumps("success"),
mimetype="application/json")
return super(StudentUpdateView, self).form_valid(form)
def form_invalid(self, form):
if self.request.is_ajax():
return HttpResponseBadRequest(json.dumps(form.errors),
mimetype="application/json")
return super(StudentUpdateView, self).form_invalid(form)
EDIT:
This is my model used, as Model Form
And StudentForm does not exist
class Student (models.Model):
name = models.CharField(u'ImiÄ™', max_length=40)
surname = models.CharField(max_length=80)
email = models.EmailField(blank=True)
subjects = models.ManyToManyField(Subjects, blank=True)
programs = models.ManyToManyField(Programs, editable=False)
history = models.CharField(max_length=50, editable=False)
added = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'%s %s'(self.name, self.surname)
class StudentForm(ModelForm):
class Meta:
model = Student

Categories

Resources