Headers not visible in ModelAdmin get_form() - python

My model is such that each website has an associated email address. An administrator would select a set of websites on the website list view and use an admin action to pass the email addresses of the selected websites to recipient field of a new email_message object. From here, the administrator should be able to customize an email that is sent to each of those email addresses.
The problem is that I can't pass headers to the get_form() method in the new email_message view. When I run the code, the print function that you see included here prints <QueryDict: {}>.
How can I pass header data from an admin action to another model's get_form method?
admin.py:
def email_selected(modeladmin, request, queryset):
response = HttpResponseRedirect('/admin/websites/email_message/add/')
response['queryset'] = queryset
return response
class WebsiteAdmin(admin.ModelAdmin):
actions = [email_selected]
class Email_messageAdmin(admin.ModelAdmin):
def get_form(self, request, obj, **kwargs):
print(request.GET)
form = super(Email_messageAdmin, self).get_form(request, obj, **kwargs)
return form
Thank you in advance for your time.

Related

How to retrieve URL fragment parameters in drf APIView?

I have created a callback view for instagram account connection in django by inheriting the APIView class.
After successful connection of instagram account facebook redirects me to the InstagramConnectCallbackView and includes the response data as a URL fragment.
url:
http://localhost:8000/v1/instagram-connect/callback/?#access_token=EAAN....&data_access_expiration_time=1650543346&expires_in=6254&state=eyd...
But I don't know how to read the URL fragments from the request into the get method.
callback view:
class InstagramConnectCallbackView(APIView):
permission_classes = (permissions.AllowAny,)
version = settings.FACEBOOK_GRAPH_API_VERSION
def get(self, request, format=None):
....
I tried the following:
request.get_full_path() # returns `/v1/instagram-connect/callback/`
request.query_params() # returns `{}`
Any help will be appreciated.
You can use query_params as
request.query_params.get('your_key_name')
If you want default then yot can use
self.request.query_params.get('your_key_name', None)
In your case you can get values like
access_token = self.request.query_params.get('access_token', None)
data_access_expiration_time = self.request.query_params.get('data_access_expiration_time', None)
expires_in = self.request.query_params.get('expires_in', None)
and so on ...

How can I get kwargs values in redirected view

I'm trying to send user to "payment view" after user register. here is what i try:
def dispatch():
......
#user registration code ...
#then i want to send email to redirected page
new_user_email =form.cleaned_data.get('email')
print("user registration complete")
else:
message = form.errors
messages.error(request, message)
print('form not verified '+ str(form.errors))
return redirect(reverse('account:payment'),kwargs = {'email': new_user_email})
url:
path('payment/', views.PaymentView.as_view(), name = 'payment'),
and after go to payment view i want to get email in this view.
class PaymentView(TemplateView):
'''
For Payment related information and proceed to get new subscription.
'''
template_name = 'home/payment.html'
def get_context_data(self,*args, **kwarg):
context = super().get_context_data(*args, **kwarg)
....
# here i need email
# context['email'] =
return context
how can i do it?
You can send the email in query parameter which can be used in the context of the redirected view.
In your registration view:
return redirect(reverse('account:payment') + '?email=' + new_user_email)
This will create the url: /payment/?email=<<email>>
In the context of the next view, you can access the query parameter like so:
def get_context_data(self,*args, **kwarg):
context = super().get_context_data(*args, **kwarg)
....
# here i need email
context['email'] = self.request.GET.get("email")
return context
You can also login the user first. After signup, you can redirect the user to the view and simply use request.user.email to access the email. This way, it will be easier to manage payment from the user.

get user with token django rest framework

sorry for my english. It is not good.
I work with rest framework django. I want to recover a user with his token. This Token must be sent via a post request
class GetUser(generics.ListCreateAPIView):
serializer_class = serializers.UserBasicSerializer
def get_queryset(self):
return models.Member.objects.filter()
def post(self, request, *args, **kwargs):
user = Token.objects.get(*args, **kwargs).user
i receive this error message
rest_framework.authtoken.models.MultipleObjectsReturned: get() returned more than one Token -- it returned 2!
thanks
Use:
user = Token.objects.filter(*args, **kwargs)
if user.exists():
user = user.last().user
The answer to your question is in the docs. Take a look here: http://www.django-rest-framework.org/api-guide/requests/#user
Basically, you just need to get from request the method user. For example:
def api_name_of_api(request):
user_data = request.user # Get username
user_data = request.user.id # Get user id
...

Django - session key of actuall logged user, not possible to get from request

How to get the session_key in form Class? It is not possible to get the request parameter to do something like this : request.user
I've got this situation, and I need to pass to function get_user session_key which is also
not possible to retrieve from request.
class CustomEntryAdminForm(EntryAdminForm):
def get_user(session_key):
session = Session.objects.get(session_key=session_key)
uid = session.get_decoded().get('_auth_user_id')
user = User.objects.get(pk=uid)
return user
categories = MPTTModelMultipleChoiceField(
label=_('Categories'), required=False,
queryset=Category.objects.filter(groups__in=get_user('uwry5olhemchxnmwa36v10zt2bg9zeci').groups.all()),
widget=MPTTFilteredSelectMultiple(_('categories'), False,
attrs={'rows': '10'}))
Use pass user as keyword argument to your form. You do not need to jump through hoops and load active session key from request and then load user from decoded session. All you need to do is:
in view:
myform = MyFormClass(user= request.user)
in form:
class MyFormClass(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(MyFormClass, self).__init__(*args, **kwargs)
self.fields['categories'].queryset = Category.objects.filter(groups__in = self.user.groups.all())
NB! not complete working code. I just wanted to show you how you can use the self.user in queryset.

Pass Variable to Django Admin Form

I have an add form for CalibrationCertificates in my django admin site. If I link to it from a non-admin template, Instrument_Detail.html, is it possible to pass context information as a default value to the add form.
That is, the only choice in the add form is which Instrument the certificate is for. As the link is already associated with an instrument, is there a way to pass that value, such that the add certificate form will default to the instrument the user came from?
My ModelAdmin is as follows:
class CertificateAdmin(admin.ModelAdmin):
exclude = ('issued_by', 'expires',)
def save_model(self, request, obj, form, change):
obj.issued_by = request.user
obj.expires= datetime.date.today() + datetime.timedelta(days=obj.instrument.kind.duration)
obj.save()
Not sure if I understand your question correctly but I think this is what you want:
def add_view(self, request, form_url='', extra_context=None):
extra_context = extra_context or {}
extra_context['my_extra_content'] = self.something
return super(MyModelAdmin, self).add_view(request, form_url,
extra_context=extra_context)

Categories

Resources