Auto populate hidden form fields in modelform - django

So my model, form, and view are working mostly. View works and sending the email works. The "message" is saved but I cannot get the message_to and message_from to save. It is supposed to save the usernames. I can get everything to save, but cannot get the message saved to the database WITH the to and from usernames. I am trying to only have 1 field in the message. "Content". The to and from should be hidden and auto-populated. I appreciate any other set of eyes on this. Thank you.
'models.py'
class Message(models.Model):
message_content = models.TextField()
message_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='message_to')
message_from = models.ForeignKey(User, on_delete=models.CASCADE, related_name='message_from')
date_created = models.DateTimeField(default=timezone.now)
unread = models.BooleanField(default=True)
'forms.py'
class MessageSellerForm(forms.ModelForm):
class Meta:
model = Message
'views.py'
def ad_detail(request, *args, **kwargs):
template_name = 'x_ads/ad_detail.html'
ad = get_object_or_404(Ad, pk=kwargs['pk'])
ad.increment_view_count()
if request.method == 'POST':
message_form = MessageSellerForm(data=request.POST)
message_form.message_from = request.user.username
message_form.message_to = ad.creator.username
if message_form.is_valid():
subject = 'Message about your ad. ' + ad.title
from_email = request.user.email
to_email = ad.creator.email
message = 'You have a message about one of your ads waiting for you!'
send_mail(subject=subject, message=message, from_email=from_email,
recipient_list=[to_email], fail_silently=False)
messages.success(request, your message has been sent.')
message_form.save()
return HttpResponseRedirect(request.path_info)
else:
message_form = MessageSellerForm()
return render(request, template_name, {'ad': ad, 'message_form': message_form})

I think I see what you're trying to do there, but there are other ways that I think will be a bit easier.
https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method
You could instead:
# create the django object in memory, but don't save to the database
message = message_form.save(commit=False)
message.message_from = request.user.username
message.message_to = ad.creator.username
# now save it to the database
message.save()
If you do that you won't need the assignments to the message form further up:
message_form.message_from = request.user.username
message_form.message_to = ad.creator.username
EDIT
You might also need to modify your MessageSellerForm to not include the message_from and message_to fields so that validation will work. That's OK because you know that you'll be assigning the right values to those fields after form validation but before saving to the database.

Related

Django: Foreign Key to User -> Form is not validating because field is required

I'm currently creating a Registration-Page with two parts
One part is about the Username and a Passwort.
The second part is about choosing the own PC-Configuration
After defining everything, the User can register to get to the Main-Page.
Therefore I got a Model called "PC_Configuration" with a bunch of Foreign-Keys to the different Database-Models of the Processors/Graphicscards etc.:
class PC_Configuration(models.Model):
user = models.ForeignKey(User, related_name='user_id', on_delete=models.DO_NOTHING)
processor = models.ForeignKey(Processors, related_name='processor_id', on_delete=models.DO_NOTHING)
graphicscard = models.ForeignKey(Graphicscard, related_name='graphicscard_id', on_delete=models.DO_NOTHING)
os = models.ForeignKey(OS, related_name='os_id', on_delete=models.DO_NOTHING)
ram = models.ForeignKey(RAM, related_name='ram_id', on_delete=models.DO_NOTHING)
harddrive = models.ForeignKey(Harddrive, related_name='harddrive_id', on_delete=models.DO_NOTHING)
Also, there is one ForeignKey to the User to connect the Configuration to the respective User-ID.
Inside views.py, I've been creating a DropdownForm for all the Dropdown-Fields which the User shall choose on his own:
class DropdownForm(forms.ModelForm):
class Meta:
model = models.PC_Configuration
exclude = []
def __init__(self, *args, **kwargs):
super(DropdownForm, self).__init__(*args, **kwargs)
self.fields['processors'].queryset = DropdownForm.objects.all()
self.fields['processors'].label_from_instance = lambda obj: "%s" % obj.name
self.fields['graphicscard'].queryset = DropdownForm.objects.all()
self.fields['graphicscard'].label_from_instance = lambda obj: "%s" % obj.name
self.fields['os'].queryset = DropdownForm.objects.all()
self.fields['os'].label_from_instance = lambda obj: "%s" % obj.name
self.fields['ram'].queryset = DropdownForm.objects.all()
self.fields['ram'].label_from_instance = lambda obj: "%s" % obj.name
self.fields['harddrive'].queryset = DropdownForm.objects.all()
self.fields['harddrive'].label_from_instance = lambda obj: "%s" % obj.name
But regarding the fact, that the User-ID shall be assigned to the Configuration automatically, there's no field for that in here.
It is defined in the register_view(request) - Method:
def register_view(request):
form = DropdownForm()
if request.method == "POST":
form = DropdownForm(request.POST)
username = request.POST.get('username')
password = request.POST.get('password')
myuser = User.objects.create_user(username, None, password)
myuser.save()
auth.login(request, myuser)
#form.user = request.user
print(form.errors)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
messages.success(request, "Account has been created successfully")
return redirect(reverse('gamesearch_view'))
else:
print('Failed')
form = DropdownForm()
render(request, 'register.html', dict(form=form))
return render(request, 'register.html', dict(form=form))
And in here, we got the problem, I guess.
While Testing the Registration, the Testaccounts keep creating and login successfully. But the problem is, that there's no PC-Configuration created because the form is not validating.
With
print(form.errors)
I've been trying to figure out why exactly and it said
<ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
So it seems like it's necessary to define the "user"-field before checking, if the form is validating and defining the user inside an instance afterwards.
That's why I was trying to do this:
form.user = request.user
But it's still not working and I can't figure out, what's exactly the problem since "user" shouldn't be part of the form-validation.
Can you help me out here?
Thank you in Advance!
You'll have a simpler time with something like this...
Your related_names were somewhat bogus; they're supposed to be the reverse name from the "viewpoint" of the other model. (Also, you never need to add _id to your fields by hand in Django.) If you elide the related_names, they'll implicitly be pc_configuration_set.
on_delete=DO_NOTHING is likely not a good idea. PROTECT is a good default.
It's easier to just handle the username and password as fields in the form.
You were missing exclude = ["user"], so if your template didn't render a field for user, of course it'd be missing. However, you also don't want the POSTer of the form to submit any old user id.
Using a FormView removes most of the boilerplate required to manage forms.
We're using transaction.atomic() to make sure the user doesn't get finally saved to the database if saving the PC Configuration fails.
We assign the created user to form.instance, which is the new but as-of-yet unsaved PC Configuration.
(Of course, imagine these are in separate files.)
from django import forms
from django.db import models, transaction
from django.views.generic import FormView
class PC_Configuration(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
processor = models.ForeignKey(Processors, on_delete=models.PROTECT)
graphicscard = models.ForeignKey(Graphicscard, on_delete=models.PROTECT)
os = models.ForeignKey(OS, on_delete=models.PROTECT)
ram = models.ForeignKey(RAM, on_delete=models.PROTECT)
harddrive = models.ForeignKey(Harddrive, on_delete=models.PROTECT)
class RegisterAndConfigurePCForm(forms.ModelForm):
username = forms.CharField(required=True)
password = forms.CharField(required=True, widget=forms.PasswordInput())
class Meta:
model = PC_Configuration
exclude = ["user"] # we'll assign this by hand
class RegisterAndConfigureView(FormView):
form_class = RegisterAndConfigurePCForm
template_name = "register.html"
def form_valid(self, form):
with transaction.atomic():
user = User.objects.create_user(form.cleaned_data["username"], None, form.cleaned_data["password"])
form.instance.user = user # assign user to the to-be-created PC configuration
form.save()
return redirect(reverse("gamesearch_view"))

Message notification in django

i have simple message model in my study project.
class Message(models.Model):
sender = models.ForeignKey(CustomUser, related_name='sender')
reciever = models.ForeignKey(CustomUser, related_name='reciever')
text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
How can I send notification to request.user about new message.
i.e. I need send notification to request.user if I have new Message object with request.user in reciever field
UPD my view:
def dialog(request, user_pk):
sent = Message.objects.filter(reciever_id=user_pk, sender_id=request.user.pk)
recieved = Message.objects.filter(reciever_id=request.user.pk, sender_id=user_pk)
mate = CustomUser.objects.get(pk=user_pk)
dialog_list = sorted(chain(sent, recieved), key=lambda a:a.created_at)
if request.POST:
form = MessageForm(request.POST)
if form.is_valid():
f = form.save(commit=False)
f.sender = CustomUser.objects.get(pk=request.user.pk)
f.reciever = CustomUser.objects.get(pk=user_pk)
form.save()
else:
form=MessageForm()
return render(request, 'dialog.html', {'sent':sent,
'recieved':recieved, 'form':form, 'mate':mate, 'dialog_list':dialog_list})
look's like this:
I solved this problem by making some ugly logic
Update my model with boolean field:
class Message(models.Model):
sender = models.ForeignKey(CustomUser, related_name='sender')
reciever = models.ForeignKey(CustomUser, related_name='reciever')
text = models.TextField(verbose_name='')
created_at = models.DateTimeField(auto_now_add=True)
is_readed = models.BooleanField(default=False)
In view I create set for my message and add users here, who have messages with is_readed == False
It become True when we load dialog page with this user
I never working in real project, but I think this solution unacceptable here.
Anyway in my first study project it's worked, maybe it helped some newbies, like meemphasized text
def dialog(request, user_pk):
sent = Message.objects.filter(reciever_id=user_pk, sender_id=request.user.pk)
recieved = Message.objects.filter(reciever_id=request.user.pk, sender_id=user_pk)
not_readed = set()
for message in recieved:
message.is_readed = True
message.save()
for message in Message.objects.filter(reciever_id=request.user.pk):
if message.is_readed ==False:
not_readed.add(CustomUser.objects.get(pk=message.sender_id))
dialog_list = sorted(chain(sent, recieved), key=lambda a:a.created_at)
if request.POST:
form = MessageForm(request.POST)
if form.is_valid():
f = form.save(commit=False)
f.sender = CustomUser.objects.get(pk=request.user.pk)
f.reciever = CustomUser.objects.get(pk=user_pk)
form.save()
else:
form=MessageForm()
return render(request, 'dialog.html', {'sent':sent,
'recieved':recieved, 'form':form, 'mate':mate,
'dialog_list':dialog_list, 'not_readed':not_readed})

Show modelform with the data the user filled in

Im trying to make a simple voting app.
The user should be presented with a blank form at first, but when the user has filled in the form, the user should be presented with the same form, but with the data they filled in.
How can I present the data they put in, on the same form?
My model:
class Vote(models.Model):
user = models.ForeignKey(User)
vote_1 = models.ForeignKey(Song, null=True, blank=True, related_name="voted_1")
vote_2 = models.ForeignKey(Song, null=True, blank=True, related_name="voted_2")
vote_3 = models.ForeignKey(Song, null=True, blank=True, related_name="voted_3")
creation_date = models.DateTimeField(auto_now_add=True)
edited = models.DateTimeField(auto_now=True)
My view:
def show_voteform(request):
if request.method == 'POST':
form = VoteForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, "Vote saved", extra_tags='alert-success')
#Return the user to same page
return HttpResponseRedirect('/vote/')
else:
form = VoteForm(initial={'user':request.user, 'vote_1':???, 'vote_2':???, 'vote_3':???,})
return render(request, 'vote/form.html', {
'form': form,
})
Is this something I could provide in initial, or do I have to do this another way?
Edit:
Changed it to this:
else:
try:
vote = Vote.objects.filter(user=request.user).latest('creation_date')
form = VoteForm(instance=vote)
except Vote.DoesNotExist:
form = VoteForm(initial={'user':request.user})
If your VoteForm is a ModelForm, then you can show the form with data from a model instance filled in using:
# get the most recent Vote by this user
vote = Vote.objects.filter(user=request.user).latest('creation_date')
# fill in the form with data from the instance
form = VoteForm(instance=vote)

Django Form not raising error

I'm trying to create a custom send email application using the User-model.
I am able to get the application functioning by sending email but it does not raise an error on the template , If the user doesn't exist.
So I tried to test whether it will raise any error at all if the number of characters is breach and no error raise . Can someone help me
class Thread(models.Model):
subject = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(User)
class Message(models.Model):
user = models.ForeignKey(User, related_name='sender')
recipient = models.ForeignKey(User, related_name='recipient')
created = models.DateTimeField(auto_now_add=True)
body = models.CharField(max_length=1000)
read = models.BooleanField(default=False)
trash = models.BooleanField(default=False)
sentmessage = models.BooleanField(default=False)
thread = models.ForeignKey(Thread)
def __unicode__(self):
return self.body
views.py
#login_required
def Create(request):
form = NewMessageForm()
if request.method =='POST':
form = NewMessageForm(request.POST)
if form.is_valid():
recipient = form.cleaned_data['recipient']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
thread = Thread.objects.create(subject=subject,user=request.user)
recipient = User.objects.get(username=recipient)
message = Message.objects.create(user=request.user,recipient=recipient,body=message,thread=thread)
return HttpResponseRedirect(reverse('world:message'))
else:
return HttpResponseRedirect(reverse('world:Create'))
return render(request,'create.html',{'messages':messages,'form':form})
forms
class NewMessageForm(forms.Form):
recipient = forms.CharField(required=True,max_length=1)
subject = forms.CharField(required=True,max_length=1)
message = forms.CharField(widget=forms.Textarea,required=True,max_length=1)
def clean_recipient(self):
recipient = self.cleaned_data['recipient']
try:
recipient = User.objects.get(username=recipient)
except User.DoesNotExist:
raise forms.ValidationError("This username does not exist")
return recipient
template
<form method="POST" >{% csrf_token %}
{{form.recipient}}
{{form.subject}}
{{form.message}}
<input type = "submit" value= "send" class="save" id="send"/>
</form>
{{form.recipient.errors}}
{{form.subject.errors}}
{{form.message.errors}}
Your pattern is slightly wrong:
if request.method =='POST':
form = NewMessageForm(request.POST)
if form.is_valid():
recipient = form.cleaned_data['recipient']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
thread = Thread.objects.create(subject=subject,user=request.user)
recipient = User.objects.get(username=recipient)
message = Message.objects.create(user=request.user,recipient=recipient,body=message,thread=thread)
return HttpResponseRedirect(reverse('world:message'))
else:
form = NewMessageForm()
Idea is that you first check if it's a POST, ok - is it working? Great- return correct flow - otherwise fall-through and pass form with errors attached by is_valid() to context. In case it's a new one - create it as a last resort since it doesn't hold any information yet.
Also don't forget form.non_field_errors since it will contain errors that are not specific to any field.

Django Initial for a ManyToMany Field

I have a form that edits an instance of my model. I would like to use the form to pass all the values as hidden with an inital values of username defaulting to the logged in user so that it becomes a subscribe form. The problem is that the normal initial={'field':value} doesn't seem to work for manytomany fields. how do i go about it?
my views.py
#login_required
def event_view(request,eventID):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
event = events.objects.get(eventID = eventID)
if request.method == 'POST':
form = eventsSusbcribeForm( request.POST,instance=event)
if form.is_valid():
form.save()
return HttpResponseRedirect('/events/')
else:
form = eventsSusbcribeForm(instance=event)
return render_to_response('event_view.html', {'user':user,'event':event, 'form':form},context_instance = RequestContext( request ))
my forms.py
class eventsSusbcribeForm(forms.ModelForm):
eventposter = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput())
details = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Event Description here')
date = forms.DateField(widget=SelectDateWidget())
class Meta:
model = events
exclude = ('deleted')
def __init__(self, *args, **kwargs):
super(eventsSusbcribeForm, self).__init__(*args, **kwargs)
self.fields['username'].initial = (user.id for user in UserProfile.objects.filter())
my models.py
class events(models.Model):
eventName = models.CharField(max_length=100)
eventID = models.AutoField(primary_key=True)
details = models.TextField()
attendanceFee = models.FloatField(max_length=99)
date = models.DateField()
username = models.ManyToManyField(UserProfile, related_name='user', blank=True)
eventposter = models.ForeignKey(UserProfile, related_name='event_poster')
deleted = models.BooleanField()
def __unicode__(self):
return u'%s' % (self.eventName)
Can you post your Event model? It's too hard to guess what you are trying to do without that. I have to assume a few things without it, so I'm sorry if I'm wrong.
First off, I'm guessing that you should not be using an Event ModelForm for the EventSubscriptionForm. That doesn't really make sense. Hopefully, you created a through class for Event and User, so in your Event model, you have something like
subscriber_users = models.ManyToManyField(User, through="Subscription")
and
class Subscription(models.Model):
user = models.ForeignKey(User, related_name="events",)
event = models.ForeignKey(Event, related_name="subscribers")
Then you can use a Subscription ModelForm.
Is there any reason you're using eventID instead of the django idiom, event_id? You should also import your Event and EventSubcribeForm classes with Pythonic casing. One very important thing is that you should be linking everything to User and not UserProfile.
Technically, it makes more sense to set initial in the view rather than the form init, because you would have to pass request.user to init anyway.
I think you should try this for your view...
#login_required
def event_view(request, event_id=None):
user = request.user.get_profile()
event = Event.objects.get(id=event_id)
initial = {'user': request.user}
form = EventSubcriptionForm(request.POST or None, instance=event, initial=initial)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('event_list'))
return render_to_response('event_view.html', {
'event': event,
'form': form
}, context_instance = RequestContext(request))
A few notes
use request.user.get_profile() for the current user's profile object
you can use request.POST or None to avoid the request.method cases
always use named urls so you can reverse on names instead of hard-coding urls into views
if you want user in your template context, just setup a context processor (see pinax for example on how to do this) instead of passing it in every single view. You can always use request.user also.
Keep in mind that this code will only work if you have that through class setup like I said and you use a form like
class EventSubcriptionForm(forms.ModelForm):
class Meta:
model = Subscription
exclude = ('event')
EDIT
Thanks a bunch for the ups. I'm not new to django, but somehow very new to SO.
Okay, you should really read some of the PEPs about Python conventions http://www.python.org/dev/peps/pep-0008/ or some SO posts about it What is the naming convention in Python for variable and function names?.
Here's what I recommend for your event app models.py:
class Event(models.Model):
name = models.CharField(max_length=100)
details = models.TextField()
attendance_fee = models.FloatField(max_length=99)
date = models.DateField()
poster = models.ForeignKey(User, related_name='events_posted')
deleted = models.BooleanField()
attendee_users = models.ManyToManyField(User, through="Attendance")
def __unicode__(self):
return self.name
class Attendance(models.Model):
user = models.ForeignKey(User, related_name="events",)
event = models.ForeignKey(Event, related_name="attendees")
Notes
The name of a class is capitalized and singular. You are not describing events, you are the blueprint for an Event.
you never need the name of the class in its attributes, i.e. event_name can just be name.
all variables are lowercase_and_underscored
always link to User, not your profile model. A lot of django code expects this.
So now you can access the users attending the event with event.attendees.
I found this while trying to set defaults for the manytomany. I didn't want to add a through table.
based on the view Casey posted, but adding the user in the manytomany relation.
for the initial post:
#login_required
def event_view(request, event_id=None):
user = request.user.get_profile()
event = Event.objects.get(id=event_id)
initial = {'user': request.user, 'username': [ request.user.id, ] } # makes the poster also an attendee
form = EventSubcriptionForm(request.POST or None, instance=event, initial=initial)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('event_list'))
return render_to_response('event_view.html', {
'event': event,
'form': form
}, context_instance = RequestContext(request))
updated version:
#login_required
def event_view(request, event_id=None):
user = request.user.get_profile()
event = Event.objects.get(id=event_id)
initial = {'user': request.user, 'subscriber_users': [ request.user.id, ] } # makes the poster also an subscriber
form = EventSubcriptionForm(request.POST or None, instance=event, initial=initial)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('event_list'))
return render_to_response('event_view.html', {
'event': event,
'form': form
}, context_instance = RequestContext(request))