Django createView passing current user_id to Modelform - python

I am trying to make a calendar app and currently trying to stop people from being about to save an event when they are already busy during that time period. I believe my issue is that the modelForm doesn't have the user_id as part of the form object. how can I pass the user_id so I can use it to filter with the clean().
I tried using get_form_kwargs() but this doesn't seem to be the correct route to take.
Please can you point me in the right direction of how to do this.
view.py
class CalendarEventAdd(LoginRequiredMixin, CreateView):
model = Event
form_class = EventForm
template_name = 'calendar_create_event_form.html'
success_url = reverse_lazy('calendar_list')
def form_valid(self, form):
form.instance.manage = self.request.user
return super(CalendarEventAdd, self).form_valid(form)
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(CalendarEventAdd, self).get_form_kwargs()
kwargs['user_id'] = self.request.user
return kwargs
form.py
class EventForm(forms.ModelForm):
class Meta:
model = Event
widgets = {
'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
}
fields = ['avilibility','start_time','end_time']
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
# input_formats parses HTML5 datetime-local input to datetime field
self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',)
self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',)
def clean(self, *args, **kwargs):
form_start_time = self.cleaned_data.get('start_time')
form_end_time = self.cleaned_data.get('end_time')
form_manage_id = self.cleaned_data.get('manage_id')
between = Event.objects.filter(manage_id=1, end_time__gte=form_start_time, start_time__lte=form_end_time)
if between:
raise forms.ValidationError('Already Calendar entry for this time')
super().clean()
model.py
class Event(models.Model):
avilibility_choices = [
('Avilible', 'Avilible'),
('Busy', 'Busy'),
]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
manage = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
avilibility = models.CharField(max_length=10, choices=avilibility_choices, editable=True)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
def __str__(self):
return self.avilibility + " - " + str(self.start_time) + " - " + str(self.end_time) + " - " +str(self.id)
def get_absolute_url(self):
return reverse('calendar_event_detail', args=[str(self.id)])
def get_absolute_url_edit(self):
return reverse('calendar_event_detail_update', args=[str(self.id)])
def get_html_url(self):
url = reverse('event_edit', args=(self.id,))
return f' {self.avilibility} '

In your view, you should pass the primary key of the user, so:
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(CalendarEventAdd, self).get_form_kwargs()
kwargs['user_id'] = self.request.user.pk
return kwargs
You can save it in the EventForm object:
class EventForm(forms.ModelForm):
def __init__(self, *args, user_id=None, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
self.user_id = user_id
# input_formats parses HTML5 datetime-local input to datetime field
self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',)
self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',)
def clean(self, *args, **kwargs):
form_start_time = self.cleaned_data.get('start_time')
form_end_time = self.cleaned_data.get('end_time')
form_manage_id = self.cleaned_data.get('manage_id')
between = Event.objects.exclude(pk=self.instance.pk).filter(
manage_id=self.user_id,
end_time__gte=form_start_time,
start_time__lte=form_end_time
)
if between.exists():
raise forms.ValidationError('Already Calendar entry for this time')
return super().clean()
The .exclude(pk=self.instance.pk) will exclude the object you are editing, if you later decide to use the EventForm not only to create but also update an Event object.
Note: The documentation advises to
use the AUTH_USER_MODEL setting [Django-doc] over
get_user_model() [Django-doc].
This is safer, since if the authentication app is not yet loaded, the settings
can still specify the name of the model. Therefore it is better to write:
from django.conf import settings
class Event(models.Model):
# …
manage = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)

Related

Django - Multiple custom models on the same form

I'm using Django 2.1 and PostgreSQL.
My problem is that I'm trying to create a form to edit two different models at the same time. This models are related with a FK, and every example that I see is with the user and profile models, but with that I can't replicate what I really need.
My models simplified to show the related information about them are:
# base model for Campaigns.
class CampaignBase(models.Model):
....
project = models.ForeignKey(Project, on_delete=models.CASCADE)
creation_date = models.DateTimeField(auto_now_add=True)
start_date = models.DateTimeField(null=True, blank=True)
end_date = models.DateTimeField(null=True, blank=True)
....
# define investment campaign made on a project.
class InvestmentCampaign(models.Model):
....
campaign = models.ForeignKey(CampaignBase, on_delete=models.CASCADE, null=True, blank=True)
description = models.CharField(
blank=True,
max_length=25000,
)
....
And the form that I want to create is one that includes the end_date of the FK CampaignBase, and the Description from the InvestmentCampaign.
Now I have this UpdateView to edit the InvestmentCampaign, and I need to adapt to my actual needs, that are also update the CampaignBase model:
class ProjectEditInvestmentCampaignView(LoginRequiredMixin, SuccessMessageMixin, generic.UpdateView):
template_name = 'webplatform/project_edit_investment_campaign.html'
model = InvestmentCampaign
form_class = CreateInvestmentCampaignForm
success_message = 'Investment campaign updated!'
def get_success_url(self):
return reverse_lazy('project-update-investment-campaign', args=(self.kwargs['project'], self.kwargs['pk']))
# Make the view only available for the users with current fields
def dispatch(self, request, *args, **kwargs):
self.object = self.get_object()
# here you can make your custom validation for any particular user
if request.user != self.object.campaign.project.user:
raise PermissionDenied()
return super().dispatch(request, *args, **kwargs)
# Set field as current user
def form_valid(self, form):
campaign = InvestmentCampaign.objects.get(pk=self.kwargs['campaign'])
form.instance.campaign = campaign
form.instance.history_change_reason = 'Investment campaign updated'
return super(ProjectEditInvestmentCampaignView, self).form_valid(form)
def get_context_data(self, **kwargs):
project = Project.objects.get(pk=self.kwargs['project'])
context = super(ProjectEditInvestmentCampaignView, self).get_context_data(**kwargs)
context['project'] = project
return context
My forms are:
class CreateCampaignBaseForm(forms.ModelForm):
class Meta:
model = CampaignBase
fields = ('end_date',)
widgets = {
'end_date': DateTimePickerInput(),
}
def __init__(self, *args, **kwargs):
# first call parent's constructor
super(CreateCampaignBaseForm, self).__init__(*args, **kwargs)
# evade all labels and help text to appear when using "as_crispy_tag"
self.helper = FormHelper(self)
self.helper.form_show_labels = False
self.helper._help_text_inline = True
class CreateInvestmentCampaignForm(forms.ModelForm):
class Meta:
model = InvestmentCampaign
fields = ('description')
widgets = {
'description': SummernoteWidget(attrs={'summernote': {
'placeholder': 'Add some details of the Investment Campaign here...'}}),
}
def __init__(self, *args, **kwargs):
# first call parent's constructor
super(CreateInvestmentCampaignForm, self).__init__(*args, **kwargs)
# evade all labels and help text to appear when using "as_crispy_tag"
self.helper = FormHelper(self)
self.helper.form_show_labels = False
self.helper._help_text_inline = True
I've read everywhere that the best way of doing this is using function based views, and call each of the forms that I have and then do the validation. the thing is that I don't know how can I populate the fields with the right object in both forms, and also, I don't know how to do the equivalent of the get_context_data nor getting the self arguments to do the equivalent of the get_success_url (because with function based views I only have the request attr so I can't access the kwargs).
I've seen some people using the django-betterforms, but again, the only examples are with the auth and profile models and I don't see the way to replicate that with my own models.
Thank you very much.
If the only thing you want to change is one field end_date on BaseCampaign, then you should use just one form. Just add end_date as an additional field (e.g. forms.DateTimeField()) on your CreateInvestmentCampaignForm and in your form.valid() method, after saving the form, set the value on the associated campaign:
def form_valid(self, form):
inv_campaign = form.save(commit=False)
inv_campaign.campaign.end_date = form.cleaned_data['end_date']
inv_campaign.campaign.save()
inv_campaign.history_change_reason = ...
return super().form_valid(form)
Here's how to add end_date to your form and initialize it correctly:
class CreateInvestmentCampaignForm(ModelForm):
end_date = forms.DateTimeField(blank=True)
class Meta:
model = InvestmentCampaign
fields = ('description')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.campaign:
self.fields['end_date'].initial = self.instance.campaign.end_date
Based on the conversation on the answer of #dirkgroten, I've developed what worked for me and what I'm actually using, but I market his answer as correct because his code is also functional.
So, meanwhile he is initiating the values on the form, I'm using the view to do that by adding a def get_initial(self): and also adding the validation on the def form_valid(self, form)::
On the view:
...
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
initial = super(ProjectEditInvestmentCampaignView, self).get_initial()
initial['end_date'] = self.object.campaign.end_date
return initial
...
# Set field as current user
def form_valid(self, form):
form.instance.history_change_reason = 'Investment campaign updated'
is_valid = super(ProjectEditInvestmentCampaignView, self).form_valid(form)
if is_valid:
# the base campaign fields
campaign = form.instance.campaign
campaign.end_date = form.cleaned_data.get("end_date")
campaign.save()
return is_valid
And on the form I just added the end_date field:
class CreateInvestmentCampaignForm(forms.ModelForm):
end_date = forms.DateTimeField()
class Meta:
model = InvestmentCampaign
fields = ('description',)
widgets = {
'description': SummernoteWidget(attrs={'summernote': {
'placeholder': 'Add some details of the Investment Campaign here...'}}),
'end_date': DateTimePickerInput(), # format='%d/%m/%Y %H:%M')
}
def __init__(self, *args, **kwargs):
# first call parent's constructor
super(CreateInvestmentCampaignForm, self).__init__(*args, **kwargs)
# evade all labels and help text to appear when using "as_crispy_tag"
self.helper = FormHelper(self)
self.helper.form_show_labels = False
self.helper._help_text_inline = True

not working update method in rest API framework

I want to be able to edit registered User profile by using UpdateModelMixin class. The forms to edit is existed but when we want to PUT the new information , the new one is not applied and the pervious info is displayed.
models.py:
class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
entry_year = models.PositiveIntegerField()
student_no = models.PositiveIntegerField()
def get_full_name(self):
return self.user.first_name + self.user.last_name
def __unicode__(self):
return self.get_full_name()
views.py:
class ProfessorDetailAPIView(DestroyModelMixin, UpdateModelMixin, RetrieveAPIView):
queryset = Professor.objects.all()
serializer_class = ProfessorDetailSerializers
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
serializers.py:
class ProfessorDetailSerializers(serializers.ModelSerializer):
user = CustomUserSerializer()
professor_no = SerializerMethodField()
class Meta:
model = Student
fields = (
'user',
'professor_no',
)
def get_professor_no(self, obj):
return str(obj.professor_no)
There is not any changes applied on information

Django: How to populate form data in template

So I am trying to have "two forms" in single class based view.
My view is:
class ListAndCreate(CreateView):
model = xmpp_buddy_groups
form_class = xmpp_buddy_groups_form
second_form_class = sip_extension_form
template_name = "xmpp/index.html"
success_url = reverse_lazy('xmpp:index')
def get_context_data(self, **kwargs):
context = super(ListAndCreate, self).get_context_data(**kwargs)
context['object_list'] = self.model.objects.all()
extension = SipExtension.objects.values_list('sip_extension', flat=True)
obj = SipExtension.objects.filter(sip_extension=1331).first()
for buddy_groups in group_names:
for sip in buddy_groups.sipextension_set.all():
sip_extension = sip.sip_extension
print(sip_extension)
context['extension'] = extension
SipExtension.objects.exclude(sip_extension__in=extension)
print(extension)
context['form'] = self.form_class
context['form2'] = self.second_form_class(instance=obj)
context['extensions'] = SipExtension.objects.exclude(sip_extension__in=extension)
return context
My form classes:
from django import forms
from .models import xmpp_buddy_groups
from extensions.models import SipExtension
class xmpp_buddy_groups_form(forms.ModelForm):
class Meta:
model = xmpp_buddy_groups
fields = ['group_name']
def __init__(self, *args, **kwargs):
super(xmpp_buddy_groups_form, self).__init__(*args, **kwargs)
self.fields['group_name'].required = False
class sip_extension_form(forms.ModelForm):
class Meta:
model = SipExtension
fields = ['real_name','sip_extension']
widgets = {
"sip_extension": forms.Select
}
def __init__(self, *args, **kwargs):
super(sip_extension_form, self).__init__(*args, **kwargs)
self.fields['sip_extension'].queryset = \
SipExtension.objects.filter(sip_extension=1331)
My models:
from django.db import models
from django.urls import reverse
class xmpp_buddy_groups(models.Model):
group_name = models.CharField(max_length=30,unique=True)
def __str__(self):
return '%s' % (self.group_name)
from django.db import models
class SipExtension(models.Model):
real_name = models.CharField(max_length=32)
sip_extension = models.PositiveIntegerField(unique=True)
sip_secret = models.CharField(max_length=32)
commlink_push = models.BooleanField(default=False)
default_did = models.ForeignKey('dids.DidNumber',null=True,blank=True)
xmpp = models.BooleanField(default=False)
xmpp_username = models.CharField(max_length=50,default='username')
xmpp_password = models.CharField(max_length=32,default='password')
xmpp_buddy_groups_names = models.ManyToManyField('xmpp.xmpp_buddy_groups')
def __str__(self):
return '%s : %s' % (self.sip_extension, self.real_name)
I am accessing form in template as {{form2.as_p}}. The dropdown appears empty. I want it to populate with 1331. How can I do that?
EDIT: Added models make the question clearer. Pardon my inexperience with Django

submit form as superuser vs regular user

In my django app I have a Myuser(User) class. It inherits the User class.
When a new user is created the Myuser table is poplulated.
myusers.py
class Myuser(User):
address = models.CharField(max_length=40)
pobox = models.CharField(max_length=40)
models.py
class Someclass(models.Model):
objectid = models.IntegerField()
objecttype = models.CharField(max_length=200)
created = models.DateTimeField(default=timezone.now)
modified = models.DateTimeField(auto_now=True)
class Someotherclass(Someclass):
status = models.IntegerField(default=0,)
name = models.CharField(max_length=200)
created = models.DateTimeField(default=timezone.now)
modified = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User)
forms.py
class SomeotherclassForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
self.user = kwargs.pop('user')
self.app = kwargs.pop('app')
self.table = kwargs.pop('table')
self.mytype = kwargs.pop('mytype')
initial = kwargs.get('initial', {})
super(SomeotherclassForm, self).__init__(*args, **kwargs)
create.py
class DataCreate(CreateView):
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
#some code here not relevant at all
def get_form_kwargs(self):
kwargs = super(DataCreate, self).get_form_kwargs()
objectid = self.request.GET.get('objectid',None)
objecttype = self.request.GET.get('objecttype',None)
kwargs.update({'mytype': objecttype})
kwargs.update({'request': self.request})
kwargs.update({'user': self.request.user})
kwargs.update({'app': self.app})
kwargs.update({'table': self.kwargs['table'].lower()})
return kwargs
def form_valid(self, form):
obj = form.save(commit=False)
group = ''
if not self.request.user.is_superuser:
group = MyUser.objects.get(user_ptr_id=self.request.user.pk)
else:
groups = self.request.user.groups.all()
if self.kwargs['table'] == 'Myprotocol':
obj = form.save(commit=False)
table = eval(self.request.GET.get('objecttype',None).title()).objects.get(pk=int(self.request.GET.get('objectid',None)))
obj.objectid = table.pk
obj.objecttype = table.__class__.__name__.lower()
obj.user_id = self.request.user.pk
obj.save()
else:
obj = form.save()
if self.request.POST.get('is_popup'):
check = int(self.kwargs['is_list'])
if self.kwargs['table'] == 'Someclass':
popup = 1
a = checkPopup2(obj,check,popup,obj.pk)
else:
a = checkPopup(obj,check)
return a
else:
return super(DataCreate, self).form_valid(form)
When I have logged in as a regular user ,everything works fine.
When I log in as a superuser, I get form error that objecttype,objectid and user are not filled.
In my attempts to troubleshoot it , I realized that when I am logged in as a superuser ,it dowsn't reach the form_valid() function.
I can't figure out why that is happening.
Any suggestions or advice on how to troubleshoot it?

django - prevent duplicates for users

Here is the Model class
class Album(models.Model):
name = models.CharField(max_length=256)
public = models.BooleanField(default=False)
user = models.ForeignKey(get_user_model())
class Meta:
unique_together = (("name", "user"),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('photos:index')
Here is the View
class Create(CreateView):
model = Album
fields = ['name', 'public']
form_class = AlbumCreateForm
def form_valid(self, form):
form.instance.user = self.request.user
return super(Create, self).form_valid(form)
And here is the form Class
class AlbumCreateForm(ModelForm):
class Meta:
model = Album
fields = ['name', 'public']
labels = {'name': '', 'public': 'Public'}
def __init__(self,*args, **kwargs):
super(AlbumCreateForm, self).__init__(*args, **kwargs)
self.fields['name'].widget = forms.TextInput(
attrs={'placeholder': 'name'})
I can create album just fine, but what I would like to do is prevent duplicate albums from being created for a particular user. For example if user1 has already created album1, he should not be able to create another album named album1.
The place where I can do it is AlbumCreateForm. But AlbumCreateForm does not have any knowledge of current user. Any idea how it can be accomplished?
Pass user to form - add him to form kwargs by adding this method to view:
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(Create, self).get_form_kwargs(*args, **kwargs)
kwargs['user'] = self.request.user
return kwargs
Get user in form and check:
def __init__(self,*args, **kwargs):
self.user = kwargs.pop('user') # this line added
super(AlbumCreateForm, self).__init__(*args, **kwargs)
self.fields['name'].widget = forms.TextInput(
attrs={'placeholder': 'name'})
def clean(self):
if Album.objects.filter(user=self.user).exists():
raise forms.ValidationError('Error description')

Categories

Resources