mercredi 6 mai 2015

Pylint complains about the member of an instance that is set in another file

For my tests I created a method in the init.py file that I include in a lot of tests. Besides the fact that it seems to work pylint shows that the instance of the test class has no member floor.

init.py

def create_floor(self):
    self.floor = Floor.objects.create(level=0)
    ...

test_something.py

def setUp(self):
    create_floor(self)
    self.building = Building.objects.create(floor=self.floor)
    ...

Django : Check object existance in ManytoManyField

I have ChatRoom model as,

class ChatRoom(models.Model):
    name = models.CharField(max_length=300)
    owner = models.ForeignKey(UserProfile)
    description = models.CharField(max_length=300)
    members = models.ManyToManyField(UserProfile,related_name='members')
    members_requested = models.ManyToManyField(UserProfile,related_name='member_requested')
    members_blocked = models.ManyToManyField(UserProfile,related_name='member_blocked')
    def __unicode__(self):
        return self.name

For example I have added a UserProfile instances to members field.

chr_obj.members.add(up_obj1,up_obj2)

How can i check whether a UserProfile object is there or not. I tried with, if chr_obj.name ='new room'

up_obj.chatroom_set.filter(name='new room').exists()

but it returns false. How to verify that ?? Thanks.

mardi 5 mai 2015

Get variables in datables passed by django

I am using jquery datatables in my django app. every row in my table have a named url to another page together with the object. {% url 'obj_details' obj.id %}. When I click on the url I am getting no reverse match found error. I have inspected the issue in detail. The url obj_details is a named url that exists in the urls.py

url(r'^obj/(?P<pk>[\w-]+)/details$', objDetailsView.as_view(), name='obj_details')

datatables uses another view to get the required data it is as pasted below

def objdtable(request):

obj_json_tuple = list(Obj.objects.all().values_list("objnum", "ob_field", "date", "price", "field2", "seller", "id"))

return HttpResponse(json.dumps(obj_json_tuple))

I am displaying all fields except id in datatables without issues.

"columns": [
                   { "": "fields.objnum"},
                   { "": "fields.ob_field" },
                   { "": "fields.date" },
                   { "": "fields.price" },
                   { "": "fields.field2" },
                   { "": "fields.seller" },
           ]

How can I pass id returned by objdtable view as an argument to url obj_details? I have tried {% url 'obj_details' fields.id %} and {% url 'obj_details' id %} but bothe are giving no reverse match found errors. Then I tried in datatables

"data":
         {
         'bid':fields.id
         }

and changed the named url to the link obj/data/details I have also tried changing data to fields.id but nothing worked. How can I access a variable passed by django in datatables? I can use that variable in url so that the issue could be solved.

Django gunicorn nginx unidentified post request to some site

This is the part from gunicorn log file

[2015-05-06 11:48:17 +0000] [6197] [DEBUG] POST /composants/personnes/ajout_exterieur.cfc
[2015-05-06 08:18:18 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:19 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 11:48:20 +0000] [6188] [DEBUG] POST /composants/personnes/ajout_exterieur.cfc
[2015-05-06 08:18:20 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:21 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:22 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 11:48:22 +0000] [6197] [DEBUG] POST /composants/personnes/ajout_exterieur.cfc
[2015-05-06 08:18:23 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:24 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 11:48:25 +0000] [6197] [DEBUG] POST /composants/personnes/ajout_exterieur.cfc
[2015-05-06 08:18:25 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:26 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:27 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 11:48:28 +0000] [6194] [DEBUG] POST /composants/personnes/ajout_exterieur.cfc
[2015-05-06 08:18:28 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:29 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 11:48:30 +0000] [6182] [DEBUG] POST /composants/personnes/ajout_exterieur.cfc
[2015-05-06 08:18:30 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:31 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:32 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 11:48:33 +0000] [6182] [DEBUG] POST /composants/personnes/ajout_exterieur.cfc
[2015-05-06 08:18:33 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:34 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:35 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 11:48:35 +0000] [6188] [DEBUG] POST /composants/personnes/ajout_exterieur.cfc
[2015-05-06 08:18:36 +0000] [6173] [DEBUG] 9 workers
[2015-05-06 08:18:37 +0000] [6173] [DEBUG] 9 workers

it sends post to /composants/personnes/ajout_exterieur.cfc which i have no idea a little bit googling yielded this site http://ift.tt/1GOhMsr but it is down , i suspect some sort of DDOS attack is involved and my server would be used too .. there is no suspicious code in my project and it is inside a virtualenv I have installed the following python modules

Django==1.8
Pillow==2.8.1
amqp==1.4.6
anyjson==0.3.3
argparse==1.2.1
billiard==3.3.0.19
celery==3.1.17
django-celery==3.1.16
django-crispy-forms==1.4.0
gunicorn==19.3.0
jsonfield==1.0.3
kombu==3.0.24
psycopg2==2.6
pycrypto==2.6.1
pytz==2015.2
redis==2.10.3
requests==2.6.2
wsgiref==0.1.2

i don't know where to look .Is this a security threat?? Thanks!

How to set root url in django urls.py ? Django 1.8

I have just started with django now and was configuring urls. I am able to map different urls like /posts, /posts/create etc. Somehow I am not able to configure root url, I am not sure what wrong I am doing. Here is my configuration :

urls.py

url(r'^$',homeViews.posts),
# url(r'^blog/', include('blog.urls')),
url(r'^posts/',homeViews.posts),
url(r'^createPost/',homeViews.createPost),

Here is the View Code

def posts(request):
  t = get_template('index.html')
  postList = Post.objects()
  html = t.render(Context({'posts':postList}))
  return HttpResponse(html)

Strange thing is, when I set DEBUG=True in settings, root url '^$' works but not with DEBUG=False (400 Bad Request). Not sure what is wrong. Please help me out .

Edit :

Here is the complete urls.py

from django.conf.urls import url
from rrdquest import views as homeViews
from manage.user import views as userViews


urlpatterns = [
# Examples:
url(r'',homeViews.posts),
# url(r'^blog/', include('blog.urls')),
url(r'^posts/',homeViews.posts),
url(r'^createPost/',homeViews.createPost),
url(r'^createUser/',userViews.createUser),
url(r'^post/(?P<title>[a-z,A-Z]+)/$',homeViews.post),
]

Cheers!

Update user balance by taking the sum between value and input value

I have a model, that extends User. In that model I have an integer field, called user_balance. When I put the form with it to a template, I can update balance with user_profile.user_balance field. But I don't want to just update balance. I need the sum between value, that already exist in balance, and value, that user can input... How can I do that? Am I need an additional fields in models? Or I just need something in my view?

My userprofile model:

class UserProfile(models.Model):  
    user = models.OneToOneField(User)
    user_picture = models.ImageField(upload_to='users', blank=False, null=False, default='users/big-avatar.jpg')
    user_balance = models.IntegerField(default=0)

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u) [0])

My forms.py

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        first_name = forms.CharField(label='')
        fields = ('first_name', 'last_name', 'email', )
        widgets = {
            'first_name': forms.TextInput(attrs={'placeholder': 'First Name', 'required': True}),
            'last_name': forms.TextInput(attrs={'placeholder': 'Last Name', 'required': True}),
            'email': forms.TextInput(attrs={'placeholder': 'E-Mail', 'required': True}),
        }

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('user_picture', 'user_balance')
        widgets = {
            'user_picture': forms.FileInput(attrs={'class': 'upload_img'}),
        }

And my views.py

def userprofile(request, username):
    u = User.objects.get(username=username)
    if request.POST:
        user_form = UserForm(request.POST, instance=request.user)
        user_profile = UserProfileForm(request.POST, request.FILES, instance=request.user.profile)
        if user_form.is_valid():
            user_form.save()
        if user_profile.is_valid():
            user_profile.save()
    else:
        user_form = UserForm(instance=request.user,
            initial={
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email,
            })
        user = request.user
        profile = user.profile
        user_profile = UserProfileForm(instance=profile)

    return render_to_response('profile.html', {'user_form': user_form, 'user_profile': user_profile}, context_instance=RequestContext(request))

Django how to use login_required with TokenAuthentication

Hi I am trying to use TokenAuthentication from Django rest-framework.

I am able to use this with my views with rest api.

#view_rest.py
class CartList(generics.ListCreateAPIView):
    serializer_class = CartSerializer
    filter_class = CartFilter
    permission_classes = (permissions.IsAuthenticated,)
    def create(self, request, *args, **kwargs):
        request.data['user_id'] = request.user.id
        return generics.ListCreateAPIView.create(self, request, *args, **kwargs)

    def get_queryset(self):
        user = self.request.user.id
        return Cart.objects.filter(user_id_id=user)

But In my custom views it is not authenticating,

#custom_django_views.py
@login_required(login_url='/login/')
def order(request):
    '''Returns page to place order
    '''
    return render(request,"order.html",{})

#this will redirect me to login page.



#settings.py
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'myapp',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'site_aggrigator.middleware.SubdomainMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
#rest framework
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.DjangoFilterBackend',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.DjangoObjectPermissions',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

I am not able to understand why for custom_django_views, request is not authenticated? When does authentication happens?