I want to ask for guidance on how to do this Django email notification
https://docs.djangoproject.com/en/1.8/topics/email/#send-mail
I have a basic task form and option to assign it to someone, when the form is saved I want to send an email notification to the assigned user.
Job/task models.py
class Job(models.Model):
completed = models.BooleanField(default=False)
task_name = models.CharField(max_length=80, blank=False)
description = models.CharField(max_length=80, blank=False)
is_important = models.BooleanField(default=False)
completion_date = models.DateField(blank=True, null=True)
assign_to = models.ForeignKey(User, blank=True, null=True)
comments = models.TextField(blank=True)
def __unicode__(self):
return self.task_name
Job/task view.py
#login_required
def job(request):
if request.method == 'POST':
form = JobForm(request.POST)
if form.is_valid():
job_record = form.save(commit=False)
job_record = form.save(commit=False)
job_record.user = request.user
job_record.save()
return redirect('jobs:list')
else:
form = JobForm()
return render(request, 'jobs/form.html', {'form': form})
You are nearly there:
#login_required
def job(request):
form = JobForm(request.POST or None)
if form.is_valid():
job_record = form.save(commit=False)
job_record.assign_to = request.user
job_record.save()
send_mail(
subject="subject",
message="message",
from_email="from#myserver.com",
recipient_list=[job_record.assign_to.email]
)
return redirect('jobs:list')
return render(request, 'jobs/form.html', {'form': form})
Related
I am writing a logic where when a users creates and account, i want to automatically assign the free membership to them and i know this should be done in the register view but i don't know why it's not working as expected. I still have to manually go to my admin page and manually assign a value to newly created user and that's not what i really wanted.
Models.py
class Membership(models.Model):
MEMBERSHIP_CHOICES = (
('Enterprise', 'Enterprise'), # Note that they are all capitalize//
('Team', 'Team'),
('Student', 'Student'),
('Free', 'Free')
)
PERIOD_DURATION = (
('Days', 'Days'),
('Week', 'Week'),
('Months', 'Months'),
)
slug = models.SlugField(null=True, blank=True)
membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30)
duration = models.PositiveIntegerField(default=7)
duration_period = models.CharField(max_length=100, default='Day', choices=PERIOD_DURATION)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
def __str__(self):
return self.membership_type
#### User Membership
class UserMembership(models.Model):
user = models.OneToOneField(User, related_name='user_membership', on_delete=models.CASCADE)
membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True)
reference_code = models.CharField(max_length=100, default='', blank=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=UserMembership)
def create_subscription(sender, instance, *args, **kwargs):
if instance:
Subscription.objects.create(user_membership=instance, expires_in=dt.now().date() + timedelta(days=instance.membership.duration))
views.py
def register(request):
reviews = Review.objects.filter(status='published')
info = Announcements.objects.all()
categories = Category.objects.all()
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
obj = request.user
get_membership = Membership.objects.get(membership_type='Free')
instance = UserMembership.objects.create(user=obj, membership=get_membership)
messages.success(request, f'Account Successfully created for {username}! You can Login In Now')
return redirect('userauths:login')
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
context = {
'reviews': reviews,
'form': form,
'info': info,
'categories': categories
}
return render(request, 'userauths/register.html', context)
in models you need to special a default="..." attribute
How I can add data to form that user submitted ? I want the user to fill in the "name" and "done" in the form and automatically add "user" (creator) and "board"
code:
#views.py
#login_required(login_url='loginPage')
def taskAdd(request, pk):
board = Board.objects.filter(user=request.user).get(pk=pk)
form = AddTaskForm()
if request.method == "POST":
form = AddTaskForm(request.POST)
if form.is_valid():
form.initial['user'] = request.user
form.initial['board'] = board
# that doesn't seem to work....
form.save()
return redirect('insideBoard', pk)
context = {'form': form}
return render(request, 'tasks/taskAdd.html', context)
#forms.py
class AddTaskForm(ModelForm):
class Meta:
model = Task
fields = "__all__"
exclude = ('user', 'board',)
#models.py
class Board(models.Model):
title = models.CharField(max_length=50, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Task(models.Model):
title = models.CharField(max_length=200, null=True)
done = models.BooleanField(default=False, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
You can edit the instance wrapped in the form:
from django.shortcuts import get_object_or_404
#login_required(login_url='loginPage')
def taskAdd(request, pk):
board = get_object_or_404(Board, user=request.user, pk=pk)
form = AddTaskForm()
if request.method == 'POST':
form = AddTaskForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.instance.board_id = pk
form.save()
return redirect('insideBoard', pk)
context = {'form': form}
return render(request, 'tasks/taskAdd.html', context)
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.
hi am working on a project where user-added the post onto the site and driver check his post and give him offer ( price) to ship their load .when the driver submits the post(price) ....at the admin level the selected post and which driver adds the price is working properly, however when the same user logged in (which added the post earlier)and want to see the price of his post-offer by a particular driver. so how can I show to the front end with filtration of the particular user?
this is my user post model
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse("Loader:my_job", kwargs={"pk": self.pk})
here is the price added to the post
class price(models.Model):
my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE,
null=True, default='')
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, default='')
driver_price = models.CharField(max_length=150, null=True)
driver_name = models.CharField(max_length=150, null=True)
approved_price = models.BooleanField(default=False)
status = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse("Driver:Driverview")
def __str__(self):
return self.driver_price
this is the view of the user post(views.py)
class Loader_post_view(CreateView, LoginRequiredMixin):
form_class = forms.Loader_post_form
model = Loader_post
template_name = "post_detail.html"
success_url = reverse_lazy("Loader:my_job")
def form_valid(self, form):
print(form.cleaned_data)
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
and this is the view of added price o particular post
#login_required
def add_price_to_post(request, pk):
post = get_object_or_404(Loader_post, pk=pk)
user = request.user
if request.method == "POST":
form = price_form(request.POST)
if form.is_valid():
ps = form.save(commit=False)
ps.user = request.user
ps.status = True
ps.save()
ps.my_post.add(post)
return redirect('Driver:Driverview')
else:
form = price_form()
return render(request, 'price_form.html', {'form': form})
now how can I show at the front-end of particular logged in user-added price to the post
models.py
class Post(models.Model):
message = models.CharField(max_length=2000)
topic = models.ForeignKey(Topic, related_name="posts", null=True,
blank=True, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, null=True, blank=True,
on_delete=models.CASCADE)
like = models.IntegerField(default=0)
views = models.IntegerField(default=0)
class ReplyPost(models.Model):
reply = models.CharField(max_length=2000)
post = models.ForeignKey(Post, related_name="reply", null=True,
blank=True, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, null=True, blank=True,
on_delete=models.CASCADE)
views.py
def reply_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = ReplyPostForm(request.POST)
if form.is_valid():
replypost = form.save(commit = False)
replypost.reply = form.cleaned_data.get("reply")
replypost.post = post
replypost.created_by = request.user
replypost.save()
return redirect("post", post.id)
else:
form = ReplyPostForm()
args = {
'form': form,
'post':post
}
return render(request, 'home/replypost.html', args)
urls.py
urlpatterns = [
#.....
url(r'^home/questions/(?P<pk>\d+)/reply/$', views.reply_post,
name="replypost"),
url(r'^home/questions/(?P<pk>\d+)/$', views.post, name="post"),
]
forms.py
class ReplyPostForm(ModelForm):
reply = forms.CharField(widget = forms.Textarea)
class Meta:
model = ReplyPost
fields = ('reply',)
The error:
ValueError. The view 'WebBoard.views.reply_post' didn't return an
'HttpResponse' object. It returned 'None' instead.
I can't not understand what is wrong with the code..Please update me if the code above is not sufficient to understand.
Your code needs to return an HttpResponse instance for the case when a request is POST but the form is not valid.
Looking at your code, try to move the last lines back one indentation level; that way everything that isn't a POST with a valid form will fall into that last return statement.
def reply_post(request, pk):
post = ...
if request.method == "POST":
form = ReplyPostForm(request.POST)
if form.is_valid():
...
return redirect("post", post.id)
else:
form = ReplyPostForm()
args = {
'form': form,
'post': post,
}
return render(request, 'home/replypost.html', args)
I have been struggling with this for a couple of weeks now and It seems, I can't get it to work.
As you sign up on my website, you are able to create a userprofile and a company. Then, you are able to add members to your company, however the signal just fires everytime and creates empty companies. How do I stop django from doing this?
model.py
class Companyname(models.Model):
company_name = models.CharField(max_length=100, default = '', null=True, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(max_length=10000, default = '', null=True, blank=True)
def __str__(self):
return self.company_name
#receiver(post_save, sender=User)
def update_user_company(sender, instance, created, **kwargs):
if created:
Companyname.objects.create(user=instance)
if instance.companyname.company_name is '':
print("just print this")
else:
instance.companyname.save()
the company gets stored on the userprofile
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default = '', null=True, blank=True)
company = models.ForeignKey(Companyname, null=True, on_delete=models.CASCADE)
role = models.ForeignKey(Role, null=True, on_delete=models.CASCADE)
team = models.ForeignKey(Team, null=True, on_delete=models.CASCADE)
company_admin = models.BooleanField(default=False)
add_user view.py
def add_user(request):
if request.method == 'POST':
form = AddUserForm(request.POST)
if form.is_valid():
company = request.user.userprofile.company_id
form.save()
user = form.save()
user.refresh_from_db()
user.userprofile.company_id = company
user.userprofile.role = form.cleaned_data.get('role')
user.is_active = False
user.save()
register view.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db() # load the profile instance created by the signal
user.userprofile.description = form.cleaned_data.get('description')
user.companyname.company_name = form.cleaned_data.get('company_name')
user.userprofile.company_id = user.companyname.id
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('/account/my_product')
else:
form = RegistrationForm()
return render(request, 'accounts/reg_form.html', {'form': form})
Hope someone can help :)