Django cross site ajax(get) not getting response - django

I need to get the userid of user logged in to my django site. I am using Django 1.3.1.
Template
$.get(http://www.tomjoyapp.com/pinTag/, { URL: document.URL},
function(data){
alert("Data Loaded: " + data.responseText);
});
view
import os
from django.template.loader import get_template
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Context, RequestContext
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def pinTag(request):
user=request.user.id
return HttpResponse(str(user))
I need to get the userid as response if he is logged in to my django app.
I am getting the status as 200 OK. But No response.

Related

Forbidden (CSRF cookie not set.): /auth for obtaining_auth_token

I am trying to get an auth token for the client (OrderClient.py). This keeps failing with
Forbidden (CSRF cookie not set.): /auth.
Here is my views
from rest_framework.decorators import api_view,permission_classes,authentication_classes
from rest_framework.response import Response
from .serializers import OrderSerial
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
#api_view(['POST'])
#authentication_classes([SessionAuthentication, TokenAuthentication])
#permission_classes([IsAuthenticated])
def make_order(request,*args,**kwargs):
user1=request.user
serializer = OrderSerial(user=user1)
print(serializer.is_valid())
data={'abc':'cde'}
return Response(data=data)
Here is my urls.py
from django.urls import path
from Products.views import home_view,Phone_input_view,Phone_list_view,Phone_edit_view
from Products.api.views import make_order
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('',home_view),
path('auth/', obtain_auth_token),
path('createPhone/',Phone_input_view),
path('viewPhoneList/',Phone_list_view),
path('edit/<int:id>',Phone_edit_view),
path('order/', make_order)
]
I have added the 'rest_framework.authtoken' to installed apps in settings.
I was expecting to retrieve the token and successfully sign in
Here is the link to my github repository: https://github.com/henselwilson/TrialProject

Does django server support url callbacks (webhooks)?

I am trying to implement url callbacks. And trying to test it. But seems like it is not working. I have been following this article for callbacks implementation.
I have defined two urls in urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^agent205', 'agent205.views.test'),
url(r'^agent206', 'agent205.views.test2'),
)
and their views in views.py
__author__ = 'rai'
from django.shortcuts import HttpResponse, render_to_response, render
from django.http.request import HttpRequest
import urllib, urllib2, json
from django.contrib.auth.decorators import login_required
import json
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def test(request):
data = {'foo': 'bar', 'hello': 'world'}
print request.body
return HttpResponse(json.dumps(data), content_type='application/json')
#csrf_exempt
def test2(request):
return HttpResponse(json.dumps(request.body), content_type='application/json')
Then I test from postman like
I am getting HTTP 200 OK response instead of getting 202 Accepted. What should I do for callback to work? Or am I missing something
If your issue is to return a 202 HTTP status code instead of the default 200, you could try to use the status parameter as follows:
#csrf_exempt
def test(request):
data = {'foo': 'bar', 'hello': 'world'}
print request.body
return HttpResponse(json.dumps(data), content_type='application/json', status=202)

Custom template in django form wizard - NameError

I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.

'module' object is not callable Django

views.py
for user in users:
#for profile in RegistrationProfile.objects.filter(user=user):
#if profile.activation_key_expired():
salt = sha_constructor(str(random())).hexdigest()[:5]
profile.activation_key = sha_constructor(salt+user.username).hexdigest()
user.date_joined = datetime.now()
user.save()
profile.save()
#if Site._meta.installed:
site = Site.objects.get_current()
# else:
site = RequestSite(request)
profile.send_activation_email(site)
context.update({"form" : form})
return render_to_response("registration/registration_complete.html", context)
imports of my views:
import django.contrib.sessions
from django.core.mail import send_mail
from django.core.mail import EmailMessage
from mail_templated import EmailMessage
from django.db.models import Sum
from tinymce.widgets import TinyMCE
from django.utils.encoding import smart_unicode
import datetime
from django.db.models import Q
from django.utils.hashcompat import sha_constructor
from registration.models import RegistrationProfile
import random
from django.contrib.sites.models import Site, RequestSite
this is giving me error ' module' object is not callable..can anyone tell me why? plz tell me what i am missing
I think you should check your imports. random is both a module name and a function inside a module. If you have
import random
Then you need to call random.random instead of just random.

Can't accessing Django profile with query from db while it get profile of logged in user

I am developing a site in Django and having two types of profiles. One of them named Person. So I am trying to access a Person object, using following code:
from django.contrib.auth.forms import UserCreationForm
from django.template import RequestContext
from django.shortcuts import render_to_response,get_object_or_404
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from accounts.forms import UserRegistrationForm, UserProfileForm
from pprint import pprint
from django.http import HttpResponse
from models import User
from models import UserProfile
def profile(request, url,template_name='person/profile.html'):
user=User(username=url).get_profile().person;
return HttpResponse(user)
And it gives error:
DoesNotExist at /p/Haafiz/
UserProfile matching query does not exist.
At another place, I am trying to do so with following code:
from django.contrib.auth.forms import UserCreationForm
from django.template import RequestContext
from django.shortcuts import render_to_response,get_object_or_404
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from accounts.forms import UserRegistrationForm, UserProfileForm
from pprint import pprint
from django.http import HttpResponse
from accounts.forms import UserProfile
#login_required
def dashboard(request,template_name="account/dashboard.html"):
return HttpResponse(request.user.get_profile().person)
And in this case, it is working fine. What can be problem at first place where I am trying to access profile from object getting from db? Both these cases seems same to me but it is having problem in the above one.
User(name=url) just generate an instance of User,not query the database for certain user.
Change
user=User(username=url).get_profile().person
to
user = User.objects.get(username=url).get_profile().person