so i have django-messages installed on my website: https://github.com/arneb/django-messages
and it states in the docs "Messages can be composed and there is an easy, url-based approach to preloading the compose-form with the recipient-user, which makes it extremly easy to put "send xyz a message" links on a profile-page."
and I've found the url being ,
^messages/ ^compose/(?P<recipient>[\w.#+-]+)/$ [name='messages_compose_to']
however the docs give no information on how to implement this, i would like to be able to add send user a message on the profile page of each user however being so new to django i dont really unserdtand how to implement this.
i also found this in views.py
form = form_class()
if recipient is not None:
recipients = [u for u in User.objects.filter(**{'%s__in' % get_username_field(): [r.strip() for r in recipient.split('+')]})]
form.fields['recipient'].initial = recipients
return render(request, template_name, {
'form': form,
Could someone please guide me in the right direction?
Related
I'm managing to send emails to users that are present in my table and then showing success message on the same page. I'm successfully sending email to users(taking their id and then their email to send). While creating urls, I need to mention id as well which redirects me to another page. But what I want is to be redirected on the same page.
Here's the table which contains the users:
After clicking Send Mail, I'm taking the userid then email with this and then sendig mail.
Taking userid:
</button><span class="badge badge-success">Send Mail</span>
Here's my views.py code on this button:
def sendMails(request, id=None):
query_user = get_object_or_404(NewUser, id=id)
user_email = query_user.user
admin_email = request.user.email
result = send_emails(request, admin_email, user_email)
context = {
'code': result
}
return render(request,'requested_users.html', context)
And urls.py:
path('dashboard/requested_users/<id>', views.sendMails, name='sendMails'),
What I want to be on same page even after sending mail(such that the urls will be):
path('dashboard/requested_users/', views.sendMails, name='sendMails'),
But if I'm not providing the id in the urls, it's giving me the error:
Reverse for 'sendMails' with keyword arguments '{'id': 1}' not found.
I know I've asked a long question, but I'm really stuck into this.
Thank you in advance.
Maybe I am not asking the right question in the search area, but I can't find an answer for this. I am pretty sure that many people have this use case, but as a beginner in Django + Python, I need to ask it.
I have user that fills up a form and the data is stored in the database. Basically this form asks for an access to a Database and after the form is submitted I want my program to send an email to the user's manager and to the DBA to APPROVE or DENY it. Very simple, right?
My idea is that in this e-mail I send two URL's, one for approving and one for denying the request. When the URL the is clicked I send a response to the server with an update in the manager_approval field.
Has anyone implemented this solution, or could point me to something that could help me?
I am doing everything using Django + Python.
Regards,
Marcos Freccia
Basically this technique used in email verification. This is where you should look into.
Let's say you have model, named request, which has field like username to identify the person who requested access, database name, well, everything. But it will also have two "password-like" fields which will be used to determine if request was declined or not.
class Request(models.Model):
user = models.ForeignKey ...
databasename =
date =
...
access_granted = models.BooleanField(default=False)
deny_token = models.CharField()
allow_token = models.CharField()
The point is to generate those tokens on saving request in the View:
if request.method == POST:
form = RequestForm(request.POST)
if form.is_valid():
data['user'] = form.cleaned_data['user'])
data['databasename'] = form.cleaned_data['databasename'])
...
data['access_token'] = GENERATE_USING_HASH_FUNCTION()
data['deny_token'] = GENERATE_USING_HASH_FUNCTION()
form.save(data)
Then you can use module EmailMultiAlternatives to send html email like so:
subject, from_email, to = 'Request', 'admin#example.com', form.cleaned_data['manager_email']
html_content = render_to_string(HTML_TEMPLATE, CONTEXT) # Just as any regular templates
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to], reply_to=["admin#example.com"])
msg.attach_alternative(html_content, "text/html")
msg.send()
And inside that template you construct reverse url:
{% url 'app:grant_access' allow_token=token %} # "token" you get from context
{% url 'app:deny_access' deny_token=token %} # will become example.com/deny_access/7ea3c95, where 7ea3c95 is token
Then add lines to urls.py of your app like that:
url(r'^allow_access/(?P<allow_token>[0-9]+)$', CheckAcessView.as_view(), name="app:grant_access"),
url(r'^deny_access/(?P<deny_token>[0-9]+)$', CheckAcessView.as_view(), name="app:deny_access"),]
Then create CheckAcessView view. Where you access request stored in your database and check if, for example, parameter of url "allow_token" is equal stored allow_token. If so, change request status to allowed.
So i've installed Django allauth to handle my login authentication. However I don't want a seperate URL for login. I want it to be available on my homepage via Javascript onclick (login box appears when you click a button/no page refresh). But the current allauth URL is located at '/accounts/login'. So as I said I need it located at '/'. How would I do this?
Here is my views.py:
def boxes_view(request):
...
search = request.GET.get('search')
posts = Post.objects.all().filter(category=1).order_by('-date')
if search:
posts = posts.filter(
Q(title__icontains=search) |
Q(content__icontains=search)
)
else:
posts = Post.objects.all().filter(category=1).order_by('-date')
context = {
'posts': posts,
}
return render(request, 'polls.html', context)
Can I pass it in as context or? How would it be done?
It sounds like you want a user to be able to log in using a modal from your homepage, or what you currently see when going to '/'
If so, you don't change the allauth login url. Instead change your javascript code for your login box to present the contents given here.
See also this answer.
My scenario:
My app, handles signup at /profile/signup/ using SingupView(FormView).
class SignupView(FormView):
template_name = "profile/signup.html"
template_name_signup_confirmed = "profile/created.html"
template_name_inactive = "profile/inactive.html"
def form_valid(self, form):
# Create and save inactive user
self.created_user = self.create_user(form, commit=False)
self.created_user.is_active = False
self.created_user.save()
# Create and save user's profile
profile = self.create_profile(form)
# Send registration email
self.send_registration_email([self.created_user.email], registration_code=profile.registration_code)
# Response
return render_to_response(self.template_name_signup_confirmed, {'email': self.created_user.email})
def form_invalid(self, form):
if 'email' in form.errors and form.errors['email'].as_text() == \
'* An inactive user is registered with this email address.':
return render_to_response(self.template_name_inactive, {'email': form.data["email"]})
return render_to_response(self.template_name, self.get_context_data(form=form))
In SingupView().form_valid(form) the User and his Profile are created, user is signed up, but inactive.
After that, in my case there is not success url to redirect, but render a new page, at the same address (/profile/signup/) with a new html saying "An email was sent at youremail#email.com, check and activate".
The same case when an inactive, registered user, tries to signup again, he will get a new page, rendered at the same adress /profile/signup/ saying 'Your email youremail#email.com is already in our db but is not active.. .'
My questions:
Can anyone explains if this is a good way to go, or I need to redirect to new urls, controlled by a new views?
Is there any security risk by using render instead of redirect? Especially on user sign in/sign up?
What is the difference when using redirect or render a new template at the same address? What is the best practice in Django?
Is it ok, to display user's email, in the signup confirmation page and also in the alert page that says that user is registered but inactive in db?
The common pattern for this sort of behaviour is to use a redirect.
I would personally prefer that as it avoid the confuson of one view doing two things - one view displays and processes the form, the other displays a success message.
If the user manages to POST the form data a second time, what do you do?
https://en.wikipedia.org/wiki/Post/Redirect/Get
I am not aware of any greater security risk from using render rather than redirect (though someone with more expertise may know more than me about that).
Im checking the examples google gives on how to start using python; especifically the code posted here; http://code.google.com/appengine/docs/python/gettingstarted/usingdatastore.html
The thing that i want to lean is that, here:
class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
They are saving a comment, IF the user is logged in, we save the user; if not its empty and when we get it out of the db we actually check for that here:
if greeting.author:
self.response.out.write('<b>%s</b> wrote:' % greeting.author.nickname())
else:
self.response.out.write('An anonymous person wrote:')
So what i would like is to use the User object to get the information, like this:
class Guestbook(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
if user:
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
else:
self.redirect(users.create_login_url(self.request.uri))
So, what i would like to do with that code is to send the user to the login url(if he is not logged in); and then to come back with whatever he had in post and actually post it. But what happens is that it doesnt even get to that action coz is nothing in the post.
I know i could put something in the session and check for it in the get action of the guestbook, but i wanted to check if someone could come up with a better solution!
Thanks
The problem is, self.redirect cannot "carry along" the payload of a POST HTTP request, so (from a post method) the redirection to the login-url &c is going to misbehave (in fact I believe the login URL will use get to continue when it's done, and that there's no way to ask it to do a post instead).
If you don't want to stash that POST payload around somewhere (session or otherwise), you can make your code work by changing the def post in your snippet above to def get, and of course the action="post" in the HTML written in other parts of the example that you haven't snipped to action="get". There are other minor workarounds (you could accept post for "normal" messages from logged-in users and redirect them to the get that perhaps does something simpler if they weren't logged in yet), but I think this info is sufficient to help you continue from here, right?