mercredi 6 mai 2015

adding dynamically a property to a class in HTML

I've got these css classes:

planning a span.icon {
    background-image:url(../img/icon1.png);
    background-position:left top;
    background-repeat:no-repeat;

.planning a:hover span.icon {
    background-position: left bottom;
}

In my template, I want to loop on an item (blurb) and dynamically update the value for the property background-image.

For now, I've tried to remove background-image from css class and added it in the template without success:

{% for blurb in page.homepage.blurbs.all %}
    <div class="span4">
    <a href={{ blurb.link }}>
    <span class="img_icon icon" style="background-image: {% static blurb.icon %}"></span>
       </a>
     </div>
{% endfor %}

It ends up that the background-image property isn't attributed to the class icon.

Any idea to do the trick?

Replace ArrayField for several fields from other models: ArrayField(ForeignKey) emulation in django-admin

I want to store model fields as array of foreign keys to other atomic-Models. It makes model more flexible: I can add/remove/inherit(if it's tree node) any of predefined properties without programming.

Let's start with atomic-Models. It contain some classified properties.

class Liquid(models.Model):
    volume = models.DecimalField(max_digits=12, decimal_places=6)

class Granular(models.Model):
    weight = models.DecimalField(max_digits=16, decimal_places=9)

class Serial(models.Model):
    lot_number = models.CharField(max_length=16)
    estimated_release_time = models.DateTimeField()
    deadline_time = models.DateTimeField())

I want to emulate the following code. It's not valid because:
1. I want to store foreign keys to several models (GenericForeignKey can help);
2. ArrayField doesn't support array of foreign keys yet;

class Entity(models.Model):
        arr = ArrayField(models.ForeignKey(DifferentAtomicModels))

Emulation is the following. Where even numbers is pk of django.contrib.contenttypes.models.ContentType, odd numbers is pk of atomic-Model (atomic-model obtained from the previous even number).

class Entity(models.Model):
    arr = ArrayField(models.IntegerField(), null=True, blank=True)

Well, in in django-admin changelist_view and changeform_view I want to replace arr field with the fields obtained from it.

What is the way to achieve this? Where it's better to intervene to django-admin behaviour (override formfield, make custom widget, smth. else...)?

P.S. What kind of emulation is better?

class Entity(models.Model):
    em01 = ArrayField(models.IntegerField())  # "ContentType_pk", "Model_pk", ...
    em02 = ArrayField(ArrayField(models.IntegerField(), size=2))  # "ContentType_pk", "Model_pk", ...
    em03 = ArrayField(ArrayField(models.CharField(), size=2))  # "Model_name", "Model_pk", ...
    em11 = HStoreField()  # {"ContentType_pk": "Model_pk"}
    em12 = HStoreField()  # {"Model_name": "Model_pk"}

How is this code supposed to be intended?

I'm learning django and python and I want to know how to indent this code properly. How should it be done?

{% block content %}
    <h2>Nyinkommet</h2>
    {% if request.GET.sorting == 'desc' %}
        <form method="get" action=".">
        <input type="hidden" name="sorting" value="asc">
        <input type="submit" value="Visa äldsta ärende först">
        </form>
    {% else %}
        <form method="get" action=".">
        <input type="hidden" name="sorting" value="desc">
        <input type="submit" value="Visa nyaste ärende först">
        </form>
{% endif %} 

How to get the custom payload from pyapns using phonegap push plugin?

we are using PYAPNS to send push notifications from an Django application to iOS devices running an phonegap application.

The server code looks like this:

def sendNotificationAPNS(title, message, targets, eventid):
    apns = APNs(use_sandbox=False, cert_file='/path/to/push_cert.pem', key_file='/path/to/push_cert.pem')

        # Send a notification
        for token_hex in targets:
            payload = Payload(alert=message, sound="default", badge=1, custom={'eventid':str(eventid)})
            apns.gateway_server.send_notification(token_hex, payload)
            print('Notification to APNS send!')

        return true

On the mobile application the code from Phonegap Push Plugin looks like this:

// handle APNS notifications for iOS
function onNotificationAPN(e) {
    if (e.alert) {
        console.log('APNS Notifiation recieved: ' +  e.alert);
        // showing an alert also requires the org.apache.cordova.dialogs plugin
        navigator.notification.alert(e.alert);
    }

    if (e.sound) {
        // playing a sound also requires the org.apache.cordova.media plugin
        var snd = new Media(e.sound);
        snd.play();
    }

    if (e.badge) {
        pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
    }
    //eventid
    if(e.eventid) {
        console.log('APNS eventid: ' + e.eventid);
    }

    //custom
    if(e.custom) {
        console.log('APNS eventid: ' + e.custom.eventid);
    }
}

The problem is: I don't get anything for e.custom or e.eventid?! What do I have to change to access the custom payload?

Thanks!

Show messages in Django

I am using Django's message framework.

When I have this view:

class ItemUpdateView(UpdateView):
    model = Item
    template_name = 'item_update_form.html'
    fields = ['name',]

    def dispatch(self, request, *args, **kwargs):
        messages.success(request, 'test')
        return super(ItemUpdateView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        messages.success(self.request, "test")
        return super(ItemUpdateView, self).form_valid(form)

it does show a message from the dispatch method but if I'm updating the object, the message from form_valid wont be shown.

What can cause the code not to show the message from form_valid?

Is the back end needed only to produce RESTful API?

I've just started learning Django and from the first tutorials i've followed or test i've done, it seemed to me (note: i'm a beginner at the whole web developing thing) that you can use it to do anything (back end as well as front end). Now thinking about the many frameworks and libraries for the front end I thought that I was missing something, so after a bit of research i came to the conclusion that the back end part is there only to provide a rest service to use with a front end framework. Do anyone for example uses the templates in Django, if so for what purposes? Am I missing something about front end - back end integration?

Thanks.

Create form from related models

I have 2 models, Message and Attachment. I want to use these in one form. The Attachment should have a reference to the message (a message can have more than 1 attachment).

Models:

class Message(models.Model): 
    createdby   = models.ForeignKey(User)
    subject     = models.CharField(max_length=200, null=True)
    body        = models.TextField(default=None,   blank=True)

class Attachment(models.Model):
    docfile     = models.FileField(upload_to='documents/%Y/%m/%d')
    message     = models.ForeignKey(Message,  null=True)

Forms

class MessageForm(forms.ModelForm):
    class Meta:
        model   = Message

AttachmentFormSet = inlineformset_factory(Message, Attachment, extra=1 )

Views

class MessageCreateView(CreateView):
     model       = Message
     fields      = ["subject", "body"]
     form_class  = MessageForm
     success_url = 'success/'

    def get(self, request, *args, **kwargs):
        """
        Handles GET requests and instantiates blank versions of the form
        and its inline formsets.
        """
        self.object = None
        form_class  = self.get_form_class()
        form        = self.get_form(form_class)
        attachment_form = AttachmentFormSet()

        return self.render_to_response(
            self.get_context_data(form  =form,
                                  attachment_form=attachment_form,
                                  ))

    def post(self, request, *args, **kwargs):
        """
        Handles POST requests, instantiating a form instance and its inline
        formsets with the passed POST variables and then checking them for
        validity.
        """
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        attachment_form = AttachmentFormSet(self.request.POST)
        if (form.is_valid() and attachment_form.is_valid()):
            return self.form_valid(form, attachment_form)
        else:
            return self.form_invalid(form, attachment_form)

    def form_valid(self, form, attachment_form):
        """
        Called if all forms are valid. Creates a Message instance along with
        associated Attachment then redirects to a success page.
        """
        self.object   = form.save()

        attachment_form.instance = self.object
        self.object   = attachment_form.save()
        return HttpResponseRedirect(self.get_success_url())

I tried many things, but for some reason the Attachment is never saved. There must be something missing in the form_valid() function, but I can't figure out what.

For completeness, here also the template:

<script type="text/javascript">
        $(function() {
            $(".inline.{{ attachment_form.prefix }}").formset({
                prefix: "{{ attachment_form.prefix }}"
            })
        });
</script>
<form class="" action="/bugtrack/project/{{ project_id }}/tickets/{{ ticket_id }}/replyform/" method="post" id="replyform">
        {% csrf_token %}
        {{ form |crispy }}        

        {{ attachment_form.management_form }}
        {% for formattach in attachment_form  %}
            {{ formattach.id }}
            <div class="inline {{ attachment_form.prefix }}">
                {{ formattach.docfile }}
            </div>
        {% endfor %}

       <button class="btn btn-info pull-right btn-sm" type="submit" name="submit" value="createReply">Submit</button>
</form>

What would be the correct way to save the Message and Attachment correctly using a formset?

Is there any opportunity to add pandas with Django framework?

I want to use pandas in Django frame work .I need pandas for statistical operations and want to produce Report and figures. Please give me some suggestions for this.

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?

'heroku run python manage.py migrate' fails with an error 'Error R13 (Attach error) -> Failed to attach to process'

i have tried 'heroku run python manage.py migrate' and get " Timeout awaiting dyno, see http://ift.tt/1BEyfgE" error.

heroku logs

 2015-05-06T05:42:05.881706+00:00 heroku[api]: Starting process with command `manage.py db:migrate` by navajyothms1989@gmail.com

2015-05-06T05:42:22.537124+00:00 heroku[run.9766]: Awaiting client 2015-05-06T05:42:22.789430+00:00 heroku[run.9766]: State changed from starting to up 2015-05-06T05:42:52.552578+00:00 heroku[run.9766]: Error R13 (Attach error) -> Failed to attach to process 2015-05-06T05:42:53.293185+00:00 heroku[run.9766]: Process exited with status 128 2015-05-06T05:42:53.307222+00:00 heroku[run.9766]: State changed from up to complete

What should I do to solve this problem?

How to programmatically trigger password reset email in django 1.7.6?

I've encountered a problem where I had to load more than 200 new users into my django app and right away send them a password reset email. This had to happen only once, done only by me and run quietly on backend. Surfing the internet brought me only to one more or less right answer: Trigger password reset email in django without browser?. The only problem was is that this post was about 4 years old and of course when I tried the solution, it didn't work...

docker-compose does not start postgres image

I'm creating a docker-compose config for an django app, the Dockerfile builds successfully but when I compose them up, django return an issue -- cannot connect to posgres.

I run docker-compose run web bash, found redis and posgres both cannot be connected.

My docker-compose.yml file:

db:
  image: postgres:9.1
  environment:
    - POSTGRES_PASSWORD=mysecretpassword

redis:
    image: redis:2.8

web:
  links:
    - db
    - redis
  build: .
  volumes:
    - .:/workspace
  ports:
    - "8000:8000"

Error info when I do docker-compose up:

sudo docker-compose up
Recreating breadtrip_db_1...
Recreating breadtrip_redis_1...
Recreating breadtrip_web_1...
Attaching to breadtrip_redis_1, breadtrip_web_1
redis_1 | [1] 06 May 06:07:30.469 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf

... 

redis_1 | [1] 06 May 06:07:30.490 # Server started, Redis version 2.8.19
redis_1 | [1] 06 May 06:07:30.490 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1 | [1] 06 May 06:07:30.490 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
redis_1 | [1] 06 May 06:07:30.491 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1 | [1] 06 May 06:07:30.491 * DB loaded from disk: 0.000 seconds
redis_1 | [1] 06 May 06:07:30.491 * The server is now ready to accept connections on port 6379
web_1   | Traceback (most recent call last):
web_1   |   File "/workspace/BreadTripServer/webapps/manage.py", line 14, in <module>
web_1   |     execute_manager(settings)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
web_1   |     utility.execute()
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 379, in execute
web_1   |     self.fetch_command(subcommand).run_from_argv(self.argv)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 191, in run_from_argv
web_1   |     self.execute(*args, **options.__dict__)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 209, in execute
web_1   |     translation.activate('en-us')
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/__init__.py", line 100, in activate
web_1   |     return _trans.activate(language)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 202, in activate
web_1   |     _active.value = translation(language)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 185, in translation
web_1   |     default_translation = _fetch(settings.LANGUAGE_CODE)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 162, in _fetch
web_1   |     app = import_module(appname)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
web_1   |     __import__(name)
web_1   |   File "/workspace/BreadTripServer/webapps/lib/haystack/__init__.py", line 83, in <module>
web_1   |     backend = load_backend(settings.HAYSTACK_SEARCH_ENGINE)
web_1   |   File "/workspace/BreadTripServer/webapps/lib/haystack/__init__.py", line 57, in load_backend
web_1   |     return importlib.import_module('haystack.backends.%s_backend' % backend_name)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
web_1   |     __import__(name)
web_1   |   File "/workspace/BreadTripServer/webapps/lib/haystack/backends/__init__.py", line 6, in <module>
web_1   |     from django.db.models import Q
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 78, in <module>
web_1   |     connection = connections[DEFAULT_DB_ALIAS]
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __getitem__
web_1   |     conn = backend.DatabaseWrapper(db, alias)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/contrib/gis/db/backends/postgis/base.py", line 11, in __init__
web_1   |     self.ops = PostGISOperations(self)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/contrib/gis/db/backends/postgis/operations.py", line 91, in __init__
web_1   |     vtup = self.postgis_version_tuple()
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/contrib/gis/db/backends/postgis/operations.py", line 445, in postgis_version_tuple
web_1   |     version = self.postgis_lib_version()
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/contrib/gis/db/backends/postgis/operations.py", line 425, in postgis_lib_version
web_1   |     return self._get_postgis_func('postgis_lib_version')
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/contrib/gis/db/backends/postgis/operations.py", line 406, in _get_postgis_func
web_1   |     cursor = self.connection._cursor()
web_1   |   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 140, in _cursor
web_1   |     self.connection = Database.connect(**conn_params)
web_1   |   File "/usr/local/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
web_1   |     connection_factory=connection_factory, async=async)
web_1   | psycopg2.OperationalError: could not connect to server: Connection refused
web_1   |   Is the server running on host "localhost" (::1) and accepting
web_1   |   TCP/IP connections on port 5432?
web_1   | could not connect to server: Connection refused
web_1   |   Is the server running on host "localhost" (127.0.0.1) and accepting
web_1   |   TCP/IP connections on port 5432?
web_1   | 
breadtrip_web_1 exited with code 1

TypeError : int() argument must be a string or a number, not 'list'

I am getting the error when i try to run this code.but it works fine on debug.

unions_choice_list = []
msss_choice_list = []
if request.method == 'POST':
    form = AnnouncementForm(request.POST, request.FILES,)
    type = request.POST.get("type")
    if type == 'individual':
        series = request.POST.get("series")
        print 'in individual'
        if series == 'union':
            print 'in series'
            unions_choice_list = request.POST.getlist('union')
            print unions_choice_list
            if form.is_valid():
                print 'in is_valid'
                for item in unions_choice_list:
                    print 'in for loop'
                    form.instance.pk = None
                    announcement = form.save(commit=False)
                    obj = Union.objects.get(pk=item)
                    announcement.union = obj
                    announcement.tittle = request.POST.get('tittle')
                    announcement.show_to = 'union'
                    announcement.save()
            else:
                messages.error(request, "Correct the displayed errors")

when i tried to print datas in console,I got the following result.

in individual
in series
[u'1', u'3']

I tried to read the matching results in this site.but those does not solve my problem.Can someone help? and can someone tall me why this runs fine on debug??

How to store the messages, when other person is offline, so when he comes online he gets all the messages?

How to store the messages, when Sub(subscriber) is offline, so when he comes online he gets all the messages?

Sub.py

# -*- coding: utf-8 -*-
# collects data from remote publisher and sends it to local subscriber 
from gevent_zeromq import zmq
ctx = zmq.Context()
s = ctx.socket(zmq.SUB)
s.connect("tcp://127.0.0.1:5567")
s.setsockopt(zmq.SUBSCRIBE,'')
while True:
    print 'waiting...'
    msg = s.recv()
    print 'received:', msg
s.close()
ctx.term()

Pub.py

def NOTIFICATION(request):
    if request.method == 'GET':
        return render_to_response('notifications.html',context)
    if request.method == 'POST':
        message_json = json.dumps(request.data)
        message_load = json.loads(message_json)
        message = {message_load['msg']}
        ctx = zmq.Context()
        publisher = ctx.socket(zmq.PUB)
        publisher.bind("tcp://*:5566")
        time.sleep(1)
        while True:
             publisher.send_multipart("message:%s" % str(message))
             time.sleep(1)
             publisher.close()
        ctx.term() 
    return Response('',status=200)

This code is working properly for message sending. But, When publisher sends the messages, if subscriber is offline, subsciber will not receive the messages. He will only receive when he is online. What to write in the code so that when subscriber comes online he receives all messages what he is not receiving in this case.

Django URL is not calling a function instead it returns old information

I don't understand clearly why the URL is not calling a function,instead it returns old information. May be cache problem ? If yes, how to prevent ?

Please note: I am using render_to_response

The cases I have tried is REQUEST METHOD : GET or I am refreshing the browser for the new information

Is anyone facing the same issue before ? please let me know your views. Your help is highly appreciable

For instance:

URLS.PY

url(r'^home/$','home.views.index')

VIEWS.PY

def index(request):
    print "I am in index"
    new_info = "Here getting updated information from django models"
    return render_to_response('index.html',{'new_info':new_info})

Problem is some times it goes inside the function and returns new information, but other times not at all going inside, instead returns old information

How to setup zmq using python django?

How to setup zmq with django using pub sub? I tried PyZmq but not working. It is showing error

 File "socket.pyx", line 481, in zmq.core.socket.Socket.send (zmq/core     /socket.c:4919)
 File "socket.pyx", line 518, in zmq.core.socket.Socket.send (zmq/core/socket.c:4609)
 File "socket.pyx", line 84, in zmq.core.socket._check_closed (zmq/core/socket.c:1106)

ZMQError: Operation not supported

which table structure would be better?

I cant decide which way is better to create a key/value Tag model in Django,

class Tag(models.Model):
    tag = models.CharField(max_length=35, unique=True)
    description = models.CharField(max_length=250, null=True)
    is_key = models.BooleanField(default=False)
    parent = models.ForeignKey("self", blank=True, related_name="key")

or

class TagKey(models.Model):
    key = models.CharField(max_length=35, unique=True)
    description = models.CharField(max_length=250, null=True)    

class TagValue(models.Model):
    value = models.CharField(max_length=35, unique=True)
    description = models.CharField(max_length=250, null=True)
    port = models.PositiveIntegerField(default=0)
    key = models.ForeignKey(TagKey)

All I intent to do is create a key:value based tag model which I can use to tag my applications.

Explanation: What I am doing in Tag class is that I am giving a self relation to itself when I will be adding a value tag, but if I am adding a key type Tag then I wont be populating the parent field.

P.S I have to use my own tag model so please don't suggest third party Django tag app

Relation fields do not support nested lookups

I am trying to look up really nested information in my web app but keep getting Relation fields do not support nested lookups as an error when doing so.

Serializers:

class UserSerializer(ModelSerializer):

    class Meta(UserDetailsSerializer.Meta):
         model = User


class UserProfileSerializer(ModelSerializer):
    user = UserSerializer(required=True, many=False)

    class Meta:
        model = UserProfile
        fields = ('premium', 'user')


class UserGameProfileSerializer(ModelSerializer):
    user = UserProfileSerializer(required=True, many=False)
    game = GameDetailSerializer(required=True, many=False)

    class Meta:
        model = UserGameProfile
        fields = ('user', 'game', 'game_user_name')

View:

class UserGameProfileView(generics.ListAPIView):
    # authentication_classes = (authentication.TokenAuthentication,)
    # permission_classes = (permissions.IsAuthenticated,)
    serializer_class = UserGameProfileSerializer

    def get_queryset(self):
        return UserProfile.objects.filter(user__user__username__exact=self.request.user)

My Logic

In my mind the query set would go from UserGameProfileSerializer -> UserProfileSerializer -> UserSerializer -> Username. Is that not the case? If so, why is it not allowed?

How to filter for a single object based on multiple instances of another object?

I'm trying to create a query to find renters that match at least one of a set of floorplans and need help writing the query.

The Renter model

class RenterProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
    name = models.CharField(max_length=120)
    desired_location = models.CharField(max_length=120)
    move_in_date = models.DateField(null=True, blank=True, help_text='Use mm/dd/yyyy format')
    coordinates =models.CharField(max_length=120, blank=True, null=True)
    lat = models.CharField(max_length=120, blank=True, null=True)
    lng = models.CharField(max_length=120, blank=True, null=True)
    price = models.IntegerField(max_length=120, blank=True, null=True)
    numbers = (('0','0'),('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6+','6+'),)    
    beds = models.CharField(max_length=120, blank=True, null=True, choices=numbers)
    baths = models.CharField(max_length=120, blank=True, null=True, choices=numbers)

The FloorPlan Model

class FloorPlan(models.Model):
    property_name = models.ForeignKey(Property)
    floor_plan_name = models.CharField(max_length=120, blank=True, null=True)
    numbers = (('0','0'),('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6+','6+'),)
    bedrooms = models.CharField(max_length=120, blank=True, null=True, choices=numbers)
    bathrooms = models.CharField(max_length=120, blank=True, null=True, choices=numbers)
    sqft = models.IntegerField(max_length=120, blank=True, null=True)
    min_price = models.IntegerField(max_length=120, blank=True, null=True)
    max_price = models.IntegerField(max_length=120, blank=True, null=True)
    availability = models.DateField(null=True, blank=True, help_text='Use mm/dd/yyyy format')
    image = models.ImageField(upload_to='floor_plans/', null=True, blank=True)    

Django Rest Framwork and Angular

I am very new Django Rest Framework and Angular Js. What I wandering here is the best way to work with these two.

  1. Django Rest and Angular js together (Most of tutorials showed me this)
  2. Django Rest as backend and Angular js in frontend as 2 different projects

I am very confused, though I feel the 2nd approach is better. But still not sure. Can please anyone help me in this with pros and cons of both the approaches

How do I write a Django rest framework writeable nested serializer by overriding onCreate? (with manyToMany relationship)

I am trying to write a serializer within the django rest framework that has a manyToMany relationship. I want the serializer to be writeable so I can send data to the object and am trying to override the create method to achieve this but am running into problems.

I can't find any examples which implement this particular behaviour.

Models:

class Messages(models.Model):
    owner = models.OneToOneField(User, primary_key=True, related_name='user_messages', editable=False) #TODO, change owner to 'To'
    #suggested_songs = models.ForeignKey(Song, null=True, blank=True)
    suggested_songs = models.ManyToManyField(Song, related_name='suggested_songs',null=True, blank=True)

Serializers:

class MessagesSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.IntegerField(source='pk', read_only=True)
    suggested_songs = SongSerializer(many=True)

    class Meta:
        model = Messages
        fields = ('id','owner','url','suggested_songs',)

def create attempts:

def create(self, validated_data):
    song_data = validated_data.pop('suggested_songs')
    messages = Messages.objects.create(**validated_data)
    for song in song_data:
        s = Song.objects.create()
        s.song = song.get("song")
        s.save()
        messages.suggested_songs.add(s)
    #post.save()
    return message

Produces the error:

"" needs to have a value for field "messages" before this many-to-many relationship can be used. So I can't create messages without first making "suggested_songs".

So I attempted the following:

def create(self, validated_data):
    suggested_songs_data = validated_data.pop('suggested_songs')
    suggest_song_list = list()
    for song_data in suggested_songs_data:
        song = Song.objects.create(**song_data)
        suggest_song_list.append(song)          
    message = Messages.objects.create(suggested_songs=suggest_song_list, **validated_data)
    return message

Produces: 'suggested_songs' is an invalid keyword argument for this function. I'm guessing because I've built the object incorrectly?

I am also trying to override "def update" next so an example with that also would be great.

'MultiValueDict' object is not callable

I am trying to have users upload an image in my django web app. I've looked through the forum and everyone is asking for several layers of complexity that I'm not wanting to tackle yet. Keep it simple....

The goal is to avoid forms if it is possible. The error comes specifically from the views line that says: profile.picture = request.FILES('profilepic')

Model:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True, null=True)
    facebook = models.URLField(blank=True, null=True)
    twitter = models.URLField(blank=True, null=True)
    linkedin = models.URLField(blank=True, null=True)
    bio = models.TextField(max_length=500, blank=True, null=True)
    address = models.OneToOneField(Address, blank=True, null=True)
    picture = models.ImageField(upload_to='/media/profile_images', blank=True)

Views:

def registration(request):
    if request.POST:
        email = request.POST['email']
        username = request.POST['email']
        password = request.POST['password']
        user = User.objects.create_user(username=username, password=password, email=email)
        user.save()
        profile = UserProfile()
        u = User.objects.get(username=username)
        profile.picture = request.FILES('profilepic')
        profile.user = u
        profile.save()
        new_member = authenticate(username=username, password=password)

    if new_member:
        login(request, new_member)
        return HttpResponseRedirect('/app/')
    return HttpResponseRedirect('/app/')

return render(request, 'app/registration.html')

Template:

<form method="POST" id="registration">    
<div id="errors" style="color: red;"></div> 
{% csrf_token %}    
    Email: <input type="email" name="email" id="email"><br>    
    Password: <input type="password" name="password" id="password"><br>    
    Profile picture: <input type="file" name="profilepic" id="profilepic"> 
<input type="submit" value="Register"> 
</form>

Render matplotlib graph into html via views in django

I have a django view as follows. I am using matplotlib to generate a bargraph.

def myview(request, pk, sub):
    x=[1,2,3,4,5,6]
    y=[5,2,6,8,2,7]
    plot(x,y, linewidth=2)
    xlabel('x-axis')
    ylabel('yaxis')
    title('sample graph')
    grid(True)

    buffer = StringIO.StringIO()
    canvas = pylab.get_current_fig_manager().canvas
    canvas.draw()
    graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
    graphIMG.save(buffer, "PNG")
    pylab.close()

    assgn = MyModel.objects.filter(data=pk, subject=sub)
    return render_to_response('mypage.html', {'assgn':assgn})

How do i pass the bargraph along with my query in my render_to_response ? Also how will i plot this graph in my html?

How to override Mezzanine comments form?

I am using:

Python 2.7
Django 1.6.11
Mezzanine 3.1.10

Anyone who logs into my blog site can set the "name" field of the comments form for a blog post. I had the idea to hide this field but I can't find the template for the comment form.

Does anyone know where the comment form template is or another way to prevent users from setting the "name" field for comments?

Where to check for 403 in a Django CBV?

I am making a basic app to teach beginners. Each user can write notes, but I want to make it so that a user cannot view or update a different user's notes.

I have the following view, but I had to repeat myself.

from django.core.exceptions import PermissionDenied

...

class NoteUpdate(LoginRequiredMixin, UpdateView):

    ...

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()

        if self.object.owner != self.request.user:
            raise PermissionDenied

        return super(NoteUpdate, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()

        if self.object.owner != self.request.user:
            raise PermissionDenied

        return super(NoteUpdate, self).post(request, *args, **kwargs)

I feel like there is probably a way to do this without repeating myself. Yeah, I could write a method like this and call it from both:

def check_permission(self):
   if self.object.owner != self.request.user:
        raise PermissionDenied 

But what I really mean is am I overriding the wrong methods? Is there a more traditional way to do this? It feels a little weird overriding .get() and .post()

get_object_or_create in a Mixin for differents models

I have a Mixin that allow me update the objects that I have created already, thing is that I have too many models and each one with different fields, this Mixin when not found the object return a 404, I need when the object is not found return the form for create the object associated to predio_id object , I have tried with get_object_or_create, but with this method I have to pass each field. How can achieve that when the object is not found, return his corresponding empty form for create it?

class UpdateModelMixin(object):
    def get_object(self):
        return get_object_or_404(self.model,predio_id=self.kwargs['predio_id'])

and it's called to view like this one:

class ManejoGeneralUpdateView(UpdateModelMixin, UpdateView):
    model = ManejoGeneral
    form_class = FormManejoGeneral
    success_url = '/'
    template_name = 'manejo_finca/edit/manejo_general.html'

Note that the UpdateView that I wrote here is just one of almost 30 o 40 UpdateViews that I have because each UpdateView call a different form and template

Need to store a password, cannot use hash

Application has many users, some have accounts on a third party site.

Needing to programmatically access and scrape a the third party site. It has no API or key based auth.

So I've got to either:

  • Ask the user for their password to the third party every time we need it. Not really an option as user will not always be present.
  • Store the user's password to the third party site.

It pains me to ask, but what's the most safe/practical way to do this? I understand there isn't a completely safe option here.

Should I seperate two users into apps ? Why would anyone do that?

I am creating a job board as a project. I plan to seperate employers and students into seperate apps. This is my first time creating a project with two different users. Im not sure what to do.

Django Rest Framework - how to write multiple nested field serializer (for reading & writing)

I'm trying to write a "def create" method to perform nested serialization for multiple objects.

    def create(self, validated_data):
        suggested_songs_data = validated_data.pop('suggested_songs')
        suggest_song_list = list()
        for song_data in suggested_songs_data:
            song = Song.objects.create(**song_data)
            suggest_song_list.append(song)          
        message = Messages.objects.create(suggested_songs=suggest_song_list, **validated_data)
        return message

Here is my schema:

class MessagesSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.IntegerField(source='pk', read_only=True)
    suggested_songs = SongSerializer(many=True)

    class Meta:
        model = Messages
        fields = ('id','owner','url','suggested_songs',)
        #fields = ('id','url','suggested_songs',)

class SongSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Song
        fields =('id','title','artist','album','albumId','num_votes','cleared')
        read_only_fields = ('song_id')

But I am getting this error

Cannot assign "[<Song: Song object>, <Song: Song object>]":     "Messages.suggested_songs" must be a "Song" instance.

Any advice?

What is the Flask version of Django's render_to_string function?

So, I'm trying to learn TDD for Flask, by translating this code to Flask. I've been trying to find how to render a template to a string for a while now. Here is what I have tried:

render_template(...)
render_template_string(...)
make_response(render_template(...)).data

and none of them seem to work. The error in each case seems to be AttributeError: 'NoneType' object has no attribute 'app' in templating.py's render_template function.

My test code is as follows:

def test_home_page_can_save_POST_request(self):
    rv = c.post('/', data = {'item_text':"A new list item"})
    self.assertIn("A new list item", rv.data)

    # or whatever will work.
    self.assertEqual(rv.data, make_response(render_template('home.html',new_item_text='A new list item')).data)

Best way to approach sports site

I have a sports site (MLB) that has games being scraped from ESPN and stored into DB something like

class mlb_games(models.Model):
    team_a = models.CharField(max_length=255)
    team_h = models.CharField(max_length=255)
    time = models.TimeField()
    date = models.DateField()
    game_id = models.IntegerField(max_length=11)

So basically I would create small little previews for each game. However what happened was teams would play each other on back to back to back days and it would create multiple pages with same content.

So i decided that for each game ever played I would create 1 URL for each game and keep it at that, and update the content to that page after each game is played. However Im having difficulties on the best approach to go about this.

My initial thought was in urls.py capture the 2 teams with regex, and in views serve the content based on filtering for the most recent game, however it then creates the issue of 2 urls being created for each game. /team-a-vs-team-b and /team-b-vs-team-a

Anyways Im just looking for any thoughts or advice on the best way to approach this project. Thanks!

'dict' object has no attribute 'pk' Django Rest API Framework

Im using Django Rest API Framework, I want to upload multiple images for a single project using Angular js.

Here's my model:

class Project(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    owner = models.ForeignKey(User)
    number_of_photos = models.IntegerField()

class Photo(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    images = models.ImageField(upload_to='photos/', max_length=254)
    project = models.ForeignKey(Project)

I have this serializers:

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ('id', 'created', 'number_of_photos', 'owner')

    def create(self, validated_data):
        project = Project.objects.create(**validated_data)
        return project

class UploadSerializer(serializers.ModelSerializer):
    project = ProjectSerializer(many=True, read_only=True)

    class Meta:
        model = Photo
        fields = ('url', 'created', 'images', 'project')

In my view I got this inside my viewsets.ModelViewSet

serializer = UploadSerializer(data=photo_array, many=True, context={'request': request})

if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

The variable photo_array contains:

[{'project': u'1', 'images': {u'name': u'test-image.png', u'lastModifiedDate': u'2015-04-22T08:51:11.000Z', u'webkitRelativePath': u'', u'lastModified': 1429692671000, u'type': u'image/png', u'size': 43152}}, {'project': u'1', 'images': {u'name': u'test.png', u'lastModifiedDate': u'2015-04-08T08:35:17.000Z', u'webkitRelativePath': u'', u'lastModified': 1428482117000, u'type': u'image/png', u'size': 127433}}]

But it gives me an error 'dict' object has no attribute 'pk'

Did my photo_array variable cause this problem?.

mysql-python installation error on Windows

everybody. I am trying to get running with Django, but I'm stuck on the last process of installation - the mysql-python downloading and installation. This is the screenshot of Command Prompt:

Command Prompt screenshot

Can somebody tell me if this will affect the Django learning process at all (I know already that it comes with SQLite) and how to fix it if I have to?

AttributeError in Django admin 'datetime.date' object has no attribute 'date'

Django 1.6, PostgreSQL, time zone support disabled.

After adding new instance of GetData in standard Django admin and save it, when i want to edit this instance i have error:

AttributeError at /admin/app/getdata/2/
'datetime.date' object has no attribute 'date'

I made two models:

class GetData(models.Model):
   cookie = models.CharField(null=True, blank=True, max_length=255)
   mail = models.EmailField(null=True, blank=True, max_length=75)
   first_visit = models.DateTimeField(null=True, blank=True)
   last_visit = models.DateTimeField(null=True, blank=True)

   def __unicode__(self):
      return self.cookie

class GetUrl(models.Model):
    cookie = models.ForeignKey('GetData')
    url = models.CharField(null=True, blank=True, max_length=255)

my admin.py looks like this:

from django.contrib import admin
from app.models import GetData, GetUrl

class GetDataAdmin(admin.ModelAdmin):
    pass
admin.site.register(GetData, GetDataAdmin)

class GetUrlAdmin(admin.ModelAdmin):
    pass
admin.site.register(GetUrl, GetUrlAdmin)

And i adding simple data to Django admin: enter image description here

No CSS and JS files when deploying with Heroku

I'm trying to deploy my project to heroku, but I faced a problem: there is no CSS and JS in deployed site. When I open page source of deployed site, for example here is next script in page source:

<script type="text/javascript"
        src="/static/static/scripts/validation.js">

When I go to src link, it shows internal error. I guess that if my scripts were saved somewhere in Inet and src would be a link to it, then it would work correct. But when deploying my site, all my scripts and CSSare in static folder. When run site locally, it's okay, when through heroku, it can't see CSS and scripts. Is there any solution for it?

Is it possible to process arbitrary content with the Django template processor?

My web app contains a banner serving API.

Abridged banner model:

class Banner(models.Model):
    name = models.CharField(max_length=50)
    ad_tag = models.TextField()
    active = models.BooleanField(default=True)
    priority = models.IntegerField(null=True, blank=False)

    def __unicode__(self):
        return self.name

The banner serving API accepts some GET parameters and, based on these parameters, returns a Django template that spits out the ad_tag TextField above. The ad_tag field is the banner's HTML:

<!-- ... -->
<body>
    {{ ad_tag|safe}}
</body>

My problem: I would like to process the contents of the ad_tag field with the Django template processor, so I can use includes, template logic, etc. Is this possible?

Django Rest Framework - How do I limit results returned with Geolocation?

I have a model which stores a users location:

[
{
    "url": "http://ift.tt/1GNHAVn",
    "id": 1,
    "owner": 1,
    "test_info": "",
    "created_at": "2015-05-02T07:09:16.535689Z",
    "updated_at": "2015-05-02T07:09:16.535746Z",
    "geolocation": null,
    "jukebox_mode_enabled": false
},
{
    "url": "http://ift.tt/1GZuZ78",
    "id": 2,
    "owner": 2,
    "test_info": "",
    "created_at": "2015-05-02T07:09:24.206959Z",
    "updated_at": "2015-05-02T07:09:24.207042Z",
    "geolocation": null,
    "jukebox_mode_enabled": false
},

I am trying to achieve a system that allows users to query and see who else is nearby but for security reasons I would like to limit the results to users with say 1KM.

What is the best way to achieve this?

P.S - The "status" is tied to the normal user model in the django model using a oneToOneField.

Multiple Comment Forms on One Page in One Template - Django

I have researched this and many answers out there touch on it, but none is exactly what I'm after...

I have an application that allows users to post cards to a board and each card can have zero or more comments. I have the database relationships set up so if I manually add board, card, or comment objects I can display them in the template just fine.

The card form is also working, so this is not an issue. But now I want to display a comment textarea with a click event (which I have working with jQuery). The problem is, the form is not displaying the field. Here is the form code:

class AddCommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ['message']

    message = forms.CharField(
        widget=forms.Textarea(
            attrs={
                'class': 'form-control comment-input'
                'name': 'message',
                'placeholder': 'Comment away...'
            }
        ),
        required=False,
    )

Right off the bat, there is a problem in that when Django renders a form, it uses an id. In this case, it ends up being id_message. Of course, in HTML, this is no good.

So I thought of using formsets but it seems not quite right, because as I understand them, they are for several forms inside one form tag. My case is different, in that each card has zero or more comments and the flow of the HTML dictates that there should be several form elements.

Another challenge is that I need to have two views: one to process the cards and one to process each comment. I'm currently using different action values to accomplish this and it seems to work.

It seems like my use case is not so strange, and I can think of several cases where this kind of situation would occur: Twitter replies, comments on blog posts, etc. I just can't get Django to work with this.

I should also note that I can manually make this work with this:

<label>
    <textarea class="form-control comment-input" name="message"></textarea>
    <button type="submit"></button>
</label>

I guess it kinda bugs me that I can't do this with Django so I'm looking for someone who has accomplished this.

Make data from GPS adapter an object to render in Django

I've got a doozy for you Python and Django experts out there.

I am trying to read GPS coordinates from the AdaFruit Ultimate GPS hat that is soldered to a Raspberry Pi. Further I need to make an object that when printed, spits out the current Longitude and Latitude. Lastly, I need to present this data in a Django HttpResponse.

Folder Structure:

manage.py
hud/
  views/
     views.py
     gps_reader.py
  templates/
     hud/
        index.html 

I have a script that will gather the GPS coords among other things and print them to the console which works great. Here is that script in it's entirety:

gps_reader.py :

import os, time, threading
from gps import *
from time import *

gpsd = None #seting the global variable

os.system('clear') #clear the terminal (optional)

class GpsPoller(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
    global gpsd #bring it in scope
    gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
    self.current_value = None
    self.running = True #setting the thread running to true

  def run(self):
    global gpsd
    while gpsp.running:
      gpsd.next() #this will continue to loop and grab EACH set of gpsd info    to clear the buffer

if __name__ == '__main__':
  gpsp = GpsPoller() # create the thread
  try:
    gpsp.start() # start it up
    while True:
      #It may take a second or two to get good data
      os.system('clear')
      print 'latitude    ' , gpsd.fix.latitude
      print 'longitude   ' , gpsd.fix.longitude
      time.sleep(5) #set to whatever

  except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
    print "\nKilling Thread..."
    gpsp.running = False
    gpsp.join() # wait for the thread to finish what it's doing
  print "Done.\nExiting."

Here is my Django view.py:

from django.shortcuts import render
from django.http import Http404
import gps_reader.GpsPoller as GpsPoller

session = GpsPoller()
session.start()

def sensors(request):
    gps_lat = "{}".format(session.fix.latitude)
    return render(request, 'hud/index.html', {"gps_lat": gps_lat})

Finally, here is my simplified index.html:

<p>
Latitude: {{ gps_lat }} 
</p>

When I run the development server with the above settings, I get the following:

ImportError at /hud/
No module named GpsPoller
Request Method: GET
Request URL:    http://ift.tt/1Kf2EqR
Django Version: 1.8
Exception Type: ImportError
Exception Value:    
No module named GpsPoller
Exception Location: /home/pi/lab/django/pi/hud/views/views.py in <module>,       line 3
Python Executable:  /usr/bin/python
Python Version: 2.7.3

Rest_framework datas from list

django rest_framework works very well if the datas You would like to expose are coming from the database, but what' s the situation if the datas are coming from simply a list (of dictionaries)? Is there any support in rest_framework to represent datas like this?:

[
    {'id': 1, 'name': 'apple'},
    {'id': 2, 'name', 'banana'},
    {'id': 3, 'name': 'orange'},
]

.

What would be the best way to achieve my goal if it' s sure the datas will never change (so no need to put them into the db as we' re talking about only less than 10 elements)?

I guess to convert the list to a fake QuerySet in django 1.6+ is not possible anymore... .

Rest_framework version: 3.1.1 Django version: 1.7.x

.

Django Rest Framework Form

What I want to do:

Django Rest Framework comes with a renderer for returning a HTML form from a serializer[1]. After poring through the docs and then through the code, I still cannot figure out how to get it to render a blank form.

What I think the problem might be:

I can't figure out how to instantiate a blank serializer. In the docs for DRF they say the serializer has a very similar API to django's forms. When you want a blank form in a template, you instantiate one with MyForm() and pass it to the template context. However when I try that with a serializer, the .data attribute is just {'detail': 'Not Found.'}

Please help

I feel like I must be missing something blindingly obvious because rendering a blank form seems like a pretty major use case for an HTMLFormRenderer.

Some Source Code

class CustomViewSet(ModelViewSet):
    lookup_field = 'id'
    pagination_class = MyCustomPagination
    serializer_class = MyModelSerializer
    renderer_classes = (JSONRenderer, BrowsableAPIRenderer, HTMLFormRenderer)

    def create(self, request, *args, **kwargs):
        # return an html form for GET requests to /api/my_model/create/.form

I'm pretty sure I have the urlconf wired up right that the request ends up in the right place, because when I GET /api/my_model/<pk>/.form I get a form in response, with the model attributes pre-entered. I just want a way to get a blank form...

Django Ical with user's content

I'm trying to use Django_ical to export some custom user content to ical. I'm pretty inexperienced with class based views in django so forgive me if this is a simple question.

from django_ical.views import ICalFeed

class ical_export(ICalFeed):
    filename = "offers.ics"
    def items(self):
       user_offers = Offer.objects.filter(user_id=request.user)
       return user_offers

def item_link(item):
    reverse("show",args=[item().id])

My question is: how can I access the request object in this case?

How do you create a singleton celery task that runs indefinitely upon starting a Django application?

Right now I have a @sharedtask that follows the following code exactly: http://ift.tt/1ILfijb

And the following scheduler settings:

CELERYBEAT_SCHEDULE = {
    'indefinite-task': {
        'task': 'app.tasks.indefinite_task',
        'schedule': timedelta(seconds=1),
    },
}

But my two of my workers seem to be running the task more than once, presumably because of a worker having concurrent threads? How can I ensure that the task is only run once by a single thread on a single worker?

Example of what I am seeing in the shell:

11:00:43 worker.1 | [2015-05-05 15:00:43,444: DEBUG/Worker-1] app.tasks.indefinite_task[b8b0445c-91e6-4652-bd75-4c609149161f]: Acquiring lock
11:00:43 worker.1 | [2015-05-05 15:00:43,444: DEBUG/Worker-2] app.tasks.indefinite_task[b8b0445c-91e6-4652-bd75-4c609149161f]: Acquiring lock

Edit: I'm using a Procfile with heroku.

How to display/view/fill in/submit a Django dynamic form

First time using Django. Got a project set up with Django dynamic forms. Was able to access the form builder in the admin panel, but I don't know how to view the forms that I've built. How do I view, fill in, and submit a dynamic form?