Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A simple "for loop" doesnt work - django
When i do a simple code in django, its just shows me the next messege: Could not parse the remainder: '[0,1,2]' from '[0,1,2]' And there is the code: {% for i in [0,1,2] %} <div class="coverw-block-welcome"> </div> {% endfor %} The smae thing if i do "range". For some reason django dont let me using "for loop". Its a problem with django -
Deploy a Chat-Bot on Web Sever to make it online using Python
I have created a WhatsApp bot, built with Python. The bot uses Selenium to automate the various actions of web-based WhatsApp such as opening the web based WhatsApp and various button actions. I am using my WhatsApp account right now. The recent chats of the interacting person is pulled using BeautifulSoup by scraping through the dynamic page source fetched by selenium. The Pulled data is parsed and matched using regex which in-turn is used to decide the appropriate reply. Now, I am planning to make this online by building a server using Django. The main idea is to allow users to register and login to my server. After log-in, they can trigger the bot on their WhatsApp account which includes opening the browser on their machine and various actions on their machine only. I am finally planning to deploy this on Heroku later. How do I go about implementing it? Is this possible ? Any suggestions would help. Thanks ! -
Bootstrap popover only shows one word of string
I have a set of popovers that show supplemental info upon hovering. They display but only the first word of the string. template: <a data-toggle="popover" data-trigger="hover" data-content={{std.Description}} >&nbsp;<i class="fa fa-question"></i></a> ... $("[data-toggle=popover]").popover(); The field in question is a Django TextField: Description = models.TextField(blank=True) Behavior: This description had several words, but all after the first were cut off. -
Django empty datefield in Q object
I have a list of leads based on a Lead model that uses a DateField. I have a form with 2 html date fields and some other fields to search by. I would like to return the leads that fall inside the range of dates submitted. My issue is that for the other fields, a blank value works just fine in not filtering the results, but leaving either or both date fields empty causes issues because an empty string isn't a date. So I am wondering how to have django return the results whether either date field is filled in. I am currently using a Q object to make the query, and have tried setting a value in the html form field to use as a default, but I couldn't find what values to use as the min date and max date -
Django, Python, Terminal
When I try to run the server via os x's terminal, its execution has suspended. It does not answer just suspending during the calculation. I used to create servers on the current system. I don't know why. I am completely lost. Previously I deleted python and django from my mac, but all in all reinstalled them. Maybe that is the issue. -
how to serve local static files in development when hosted in S3
I'm storing my static files in S3 according to this tutorial: https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ I am developing a lot of javascript and want to serve my javascript files locally only when in my development environment. Otherwise I would have to keep uploading my js files every time I want to test. My static files settings look like this currently: STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'my.custom_storage.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) I created a local_settings.py file with setttings that point locally: STATICFILES_LOCATION = '/local/myapp/common/static/' STATICFILES_STORAGE = '' STATIC_URL = '/static/' STATIC_ROOT = "/local/myapp/common/static/" No matter what I change here, my app looks for the js files at the S3 url: http://s3.amazonaws.com... How can I have my app look locally for static files when in development so I can rapidly test my js files? -
Django [Errno 10053] An established connection was aborted by the software in your host machine
My django server returning an error when client refresh the page before loading. Is it important? should i ignore these errors? how can i hide these errors if i have to ignore them? My view here: def home(request): assert isinstance(request, HttpRequest) return render( request, 'app/index.html', { 'title':'Home Page', 'year':datetime.now().year, } ) traceback: [05/Sep/2016 22:13:21] "GET / HTTP/1.1" 200 9388 [05/Sep/2016 22:13:21] "GET / HTTP/1.1" 200 9388 Traceback (most recent call last): File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 453, in _write self.stdout.write(data) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\socket.py", line 593, in write return self._sock.send(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [05/Sep/2016 22:13:21] "GET / HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52890) Traceback (most recent call last): File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File … -
djangorest limit_choises_to attribute ignored?
I'm using the DjangoRest Framework with 2 models DeviceType and Channel. Now channel has a ForeignKeyField pointing to a DeviceType. No problem so far. But now I don't want all DeviceTypes to be selectable when adding or editing a Channel but only the DeviceTypes that have their usesChannels field set to True. So I used the limit_Choices_to attribute but somehow that doesn't seem to work. No matter what I do, I alway get a list with all DeviceTypes including the ones with usesChannels set to False This is my code: models.py class DeviceType(models.Model): name = models.CharField(max_length=30) usesChannels = models.BooleanField() def __str__(self): return '%s' % (self.name) class Channel(models.Model): type = models.ForeignKey(DeviceType, limit_choices_to={'usesChannels': True}) name = models.CharField(max_length=30) channelNr = models.IntegerField() serializers.py class DeviceTypeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DeviceType fields = ('url', 'name', 'usesChannels') class ChannelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Channel flieds = ('url', 'type', 'name', 'channelNr') I used the ForeignKey.limit_choices_to example from This link -
How to print even or odd in html using django
I want to find a number whether that is even or odd in django. For that I am taking input from the user in html form and then run the python code to find the number even or odd. And then print even or odd in html page. Do I have to use rest services or can we do that without using it. Thanks -
Django Rest Framework - best way to an endpoint?
I'm learning Django + DRF + React and I reached the phase where it's time to protect some endpoints. Some are easier to protect, just a permission so only the user which created a particular object (and the admins) are able to see it. There is one endpoint which is tricky for me. It's a GET call and returns something like: {book: "Who am I and how come", id: "whatever31", reading: ["user1", "user2"]} I want to protect this endpoint based on the user making the request (Session auth) so only calls coming from user1 and user2 can access this object (also, not exposing reading field, but that's probably a different discussion). Should I use a custom permission on DRF view? Should I use a filter instead in queryset method? Maybe both? -
Applying several filters to prefetch_related
For the purpose of my project, I need to apply several filters to prefetch_related based on if-condition as follows: if (condition1): qs = qs.prefetch_related(\ models.Prefetch('my_model', queryset=MyModel.objects.all().filter(a = 111), to_attr = 'my_list1')) if (condition2) qs = qs.prefetch_related(\ models.Prefetch('my_model', queryset=MyModel.objects.all().filter(a = 222), to_attr = 'my_list2')) The problem is that Django does not allow to use the same list variable for to_attr in both cases which means that I can't apply both if's to the same resultset. What is the right way to rewrite this code ? If the answer is put vaguely, please ask for clarifications. I tried to make it as clear as possible. -
Async IO in Python vs Django / Tornado etc [on hold]
I am not a python expert in general and certainly not one of python 3. Recently I watched a presentation of a guy (from Skoobe.de in ruropython conference) who was advocating the greatness of Async IO new stuff in python (mostly python3). Why is this new? If django would be used by a tornado server to push requests to applications serving them and collect the answers back to send them to users, would that not be simpler and better then Asynch IO? -
Combine Django with AngularJS
I made a form in django to calculate the sum of 3 numbers. Now I would like to combine Angular JS with Django so I can add numbers at real time. Do I need to add the js just in the html code? How do I build the view? Does someone have good examples for easy angular/django projects? Here is the form code: from django import forms class PricerForm(forms.Form): one = forms.DecimalField(initial=100.0) two = forms.FloatField() three = forms.FloatField() Building the view: def calc(request): solution = 0 if request.method == 'POST': form = PricerForm(request.POST) if form.is_valid(): solution = pv(float(request.POST['one']), float(request.POST['two']), float(request.POST['three'])) else: form = PricerForm() form.fields['three'].inital = 3.0 form.fields['two'].initial = 2.0 form.fields['one'].initial = 1.00 context = {'form': form, 'solution': solution} return render(request, 'pricing/output.html', context) the view: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>sum</title> </head> <body> <form action="{% url 'calc'%}" method="post" > {% csrf_token %} <p><label>one (%) </label> {{form.one}}</p> <p><label>two</label> {{form.two}}</p> <p><label>three (years)</label> {{form.three}}</p> <input type="submit" value=">>" /> </form> <b> Solution </b> : {{ solution }} <script src="angular/angular.js"></script> </body> </html> -
Why is this Django URL resolution now working
I have the following Django url configuration in /urls.py file from django.conf.urls import url from django.conf.urls import include, url from django.contrib import admin import core import core.views as coreviews urlpatterns = [ #url(r'^admin/', admin.site.urls), #url(r'^create/$', coreviews.handleFile), #Uncommenting this works url(r'^create/$', include('core.urls')), #This doesn't work url(r'^$', include('core.urls')),#Make msg app the the default one #url(r'^upload/', include('core.urls')), ] My core/urls.py file is defined as follows from django.conf.urls import include, url from django.contrib import admin import core.views as coreviews from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'my$', coreviews.handleFile), url(r'^$', coreviews.index), ] Finally, core/views.py file is defined as follows def index(request): return render_to_response('AudioRecorder/index.html', context_instance=RequestContext(request)) def handleFile(request): return render_to_response('AudioRecorder/index.html', context_instance=RequestContext(request)) show_urls output is as follows / core.views.index /create/ core.views.index /create/my core.views.handleFile /my core.views.handleFile Question: I am running on localhost. When I send get request to url http://localhost:8000/, I get proper response with 200 code. But when I send get request to url http://localhost:8000/create/my, I get 404 not found error. Why is it happening like this? Shouldn't second URL also return 200 code? -
DRF: Seperate fields for each CRUD operation on the same Serializer
I have a serializer that looks like this class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('A', 'B') # 'C' is mandatory to create the object but dont include it on GET def create(self, validated_data): # validated_data contains C ... instance = MyModel(**validated_data) print instance.__dict__ # C is None !?!?! instance.save() return instance When I return the resources, following a GET request, I want only 'A' and 'B' for each row (object) When I create the resource, following a POST request, I have to include a mandatory third attribute 'C' The view does it's job correctly and passes C inside validated_data, but when I create the MyModel it ends up without C value as shown above. If I add 'C' in fields tuple then everything works correctly ... Is there a sensible way to distinguish between the two cases? Writing mutliple serializers (so that each one defines different fields) seems too ugly to me. -
About caching advertisements
Let's say I'm trying to cache somehow content rendered with django which includes ads (adsense, amazon afiliates, paypal, donations, ...) What do I need to consider upfront to grant ads will run correctly? Any advice about caching ads is well received. -
Django permission to set attribute but not edit available options
so I have a Django model that contains a foreign key, kinda like that: class Person(TimeStampedModel): [...] roles = models.ManyToManyField('Role',through='PersonRole',related_name='persons') [...] Where PersonRole is used to assign a role to a person. I want to allow a group of users to set a role on a person, but not add new roles, change existing roles or delete roles. Therefore I removed these three permissions from the group the users are in. Since I did this, the users can not see the the Inline in the Admin Site to set that specific relation on a user. The group still has the "change person" permission. I have two questions that I was unable to answer from the documentation: 1) Is that intended behaviour? I'm working on an old and heavily modified version of django. 2) If not, how can I grant this right without allowing people to change around the available options? I'm on a Django 1.3 and can't change that yet. So a Model-Choice-Field in the admin depending on the user permissions is out of the question sadly. I would appreciate any help. :) -
Making queries ManyToMany relationships
I have a model named AffectedSegment which is used for store a corporal segments selection. class AffectedSegment(models.Model): SEGMENTO_ESCAPULA = 'Escápula' SEGMENTO_HOMBRO = 'Hombro' SEGMENTO_CODO = 'Codo' SEGMENTO_ANTEBRAZO = 'Antebrazo' SEGMENTO_CARPO_MUNECA = 'Carpo/Muñeca' SEGMENTO_MANO = 'Mano' SEGMENT_CHOICES = ( (SEGMENTO_ESCAPULA, u'Escápula'), (SEGMENTO_HOMBRO, u'Hombro'), (SEGMENTO_CODO, u'Codo'), (SEGMENTO_ANTEBRAZO, u'Antebrazo'), (SEGMENTO_CARPO_MUNECA, u'Carpo/Muñeca'), (SEGMENTO_MANO, u'Mano'), ) affected_segment = models.CharField( max_length=12, choices=SEGMENT_CHOICES, verbose_name='Affected Segment' ) def __str__(self): return "%s" % self.affected_segment I have another model named Movement, which is used for store a movement asociated or related with the previous corporal segment entered. The idea is that one segment (AffectedSegment object) can have many movements, and one movement (Movement object) can be associated with one or many segments. class Movement(models.Model): type = models.CharField( max_length=255, verbose_name='Movement type' ) corporal_segment_associated = models.ManyToManyField( AffectedSegment, blank=True, verbose_name='Affected segment associated') def __str__(self): return "%s" % self.type This two models, I am referencing in this model class RehabilitationSession(models.Model): affected_segment = models.ManyToManyField( AffectedSegment, verbose_name='Segmento afectado', #related_name='affectedsegment' ) movement = models.ManyToManyField( Movement, # Chained Model verbose_name='Movement', #related_name = 'movement' ) My main doubt is How to can I lookup the content of affected_segment and movement fields from RehabilitationSession model in my html templates. I am trying pass these data of this way: My views.py … -
django.core.exceptions.FieldDoesNotExist but the field exists
i've a problem sincying the db. i run the command: django-admin migrate System check identified some issues: Operations to perform: Synchronize unmigrated apps: oauth2_provider, <and many more> Apply all migrations: admin, <and many more> Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: No migrations to apply. Traceback (most recent call last): File "/Users/stefano/.virtualenvs/prjrest/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/stefano/.virtualenvs/prjrest/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Users/stefano/.virtualenvs/prjrest/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/stefano/.virtualenvs/prjrest/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/Users/stefano/.virtualenvs/prjrest/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/Users/stefano/.virtualenvs/prjrest/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 208, in handle changes = autodetector.changes(graph=executor.loader.graph) File "/Users/stefano/.virtualenvs/prjrest/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "/Users/stefano/.virtualenvs/prjrest/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 165, in _detect_changes old_field = self.old_apps.get_model(app_label, old_model_name)._meta.get_field(field_name) File "/Users/stefano/.virtualenvs/prjrest/lib/python2.7/site-packages/django/db/models/options.py", line 554, in get_field raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: CustomerKey has no field named u'customer_key_cipher_text' so, it seems that there are not migration, but still django complains for a missing field. however in the last model the field is there class CustomerKey(models.Model): ... customer_key_cipher_text = Base64Field(default='') and also in the DB: any idea on what's the problem? -
Django: Handling empty querysets in generic view
I am having a generic view which sometimes returns nothing. How can I effectively handle it and raise a 404 in that case? My approach is successfull, but hits the database. class MyListView(ListView): template_name = 'template/quest.html' def get_queryset(self, *args, **kwargs): query = MyModel.objects.filter( ... ).filter( ... ) if query.exists(): return query else: raise Http404 -
Django Update/Delete view. Handling user permissions
models.py class Punch(models.Model): ro_number = models.IntegerField() flag = models.FloatField(max_length=10) actual = models.FloatField(max_length=10) description = models.CharField(max_length=100, blank=True) user = models.ForeignKey(User) created_on = models.DateTimeField(auto_now_add=True) def efficiency(self): return '%.2f' % (float(self.flag)/float(self.actual)*100) def __str__(self): return str(self.ro_number) urls.py url(r'^flags/update/(?P<pk>[0-9]+)/$', views.PunchEdit.as_view(), name='update_flags'), view.py class PunchEdit(views.LoginRequiredMixin, UpdateView,): model = Punch fields = ['ro_number', 'flag', 'actual', 'description'] template_name = 'free/home.html' def get_success_url(self): pass I am trying to figure out how to allow users to only edit the punch objects they created. Any time a Punch object is created it saves which user created the punch with a foreign key relation. (Accomplished in views not shown) Right now if you were to type in something like mywebsite.com/punch/update/(pk)/ a user could write in the pk of any punch object and update its info. So my question is.. How, when using class based generic update/delete views, can you prevent a user from touching a punch object they did not create themselves. -
duplicate media folder in django
I have the next error: http://159.203.181.222/media//media/media/salones_JQGuwT5.jpg 404 (Not Found) I don't understnd why do i have two folders on my dir and also three media on my path. settings.py STATIC_URL = '/static/' STATIC_ROOT = '/home/django/django_project/django_project/static' MEDIA_ROOT = '/home/django/django_project/django_project/media/' MEDIA_URL = '/media/' urls.py urlpatterns = patterns('', url(r'^unamforumadmin/', admin.site.urls), url(r'^', include('unamForumApp.urls')), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Category(models.Model): name_category = models.CharField(max_length=10, unique=True) detail_category = models.TextField() photo_category = models.ImageField(upload_to="media", null=True, blank=True) -
Django deployment on heroku not working
I created a personal portfolio website for myself using django and it also includes a blog. You can see the exact directory listing and source code in my github repository by clicking here I have the procfile and the requirements.txt file as said in the heroku website and did the following in command prompt as directed by heroku : $ heroku login $ heroku git:clone -a appname $ cd appname $ git add . $ git commit -am "make it better" Then collectstatic --noinput error occurred so I did this: heroku config:set DISABLE_COLLECTSTATIC=1 Then I again repeated the deployment process and this time the deployment was successfull. And then I opened the app but the website did not appear. Instead this appeared. Please help me deploy this website. -
How to access(ask) token for user login
I have used Django Rest Framework for Rest API and django-oauth-toolkit for token based authentication. I have designed and api for user registration. When user is registered, a token is generated and saved to the database. I want user login from that token. I mean a token based authentication because i want to develop a mobile application. I can get access_token using curl when sending request for logging in but how do i implement in view so that app sends a post request to 127.0.0.1:8000/o/token asking for the token so that the request contains username, password, client_id and client_secret. views.py class UserLoginAPI(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): access_token = AccessToken.objects.get(token=request.POST.get('access_token'), expires__gt=timezone.now()) # error is shown here. I get None data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserCreateSerializer(ModelSerializer): class Meta: model = User extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() if user_obj: expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS'] scopes … -
Invalid form when uploading a file
I am trying a basic example in uploading a file with django. I tried the code from the django documentaion but I keep getting invalid form. And when I don't test the validation of the form and try to handle the file directly, I get: MultiValueDictKeyError at /neurons/nblast " 'file'" P.S: Previously, I had used a model with a FileField and set the (upload_to), but in my current case I don't need to use the model, I only need to let the user uploads his files. This is my code: Template <body> <form action="" method="post"> {{ form }} <br> <button class="btn btn-success" name="btn_upload"> <span class="glyphicon glyphicon-upload"></span> <b>Upload</b> </button> {% csrf_token %} </form> </body> Views def test(request): if request.method == GET: form = UploadFileForm() if request.method == POST: if 'btn_upload' in request.POST: form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) else: print 'Not Valid' form = UploadFileForm() return render_to_response('test.html', {'form': form}, context_instance=RequestContext(request)) Forms: class UploadFileForm(forms.Form): file = forms.FileField() Thank you very much