Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djangobyexample book - jquery bookmarklet not working at all
Im working through Django By Example and in one chapter a Jquery bookmarklet is built within a Django app so that a user can easily save jpg images from a website into their user profile area within the Django app. Im not an experienced JS or Jquery programmer but I did some JS some years back and can read the code however the tutorial does give exact instructions on what to do which I have followed and although I have managed to get the bookmarklet button to appear in my bookmarks bar in Chrome, nothing happens when I click it when browsing a webpage with jpg images. This is my local Django dashboard where the bookmarklet button is added to the bookmarks bar and this part works fine dashboard image and this is what IT MUST LOOK LIKE when clicked on the bookmarklet, THIS IS THE PART WHERE NOTHING HAPPENS FOR ME when i clicked on bookmarklet (how to solve this?) expected image these are the relevant js files github.com/davejonesbkk/bookmarks/blob/master/images/templates/bookmarklet_launcher.js github.com/davejonesbkk/bookmarks/blob/master/images/static/js/bookmarklet.js I believe the javascript launcher is unable to load the javascript files or the js launcher itself is not getting loaded. The javascript launcher is getting called through a … -
get version issues python code
I want to ask about this code, I don't understand it. What is a PEP 386-compliant? Please any help? VERSION = (1, 1, 0, 'final', 0) def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases parts = 2 if VERSION[2] == 0 else 3 main = '.'.join(str(x) for x in VERSION[:parts]) sub = '' if VERSION[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[VERSION[3]] + str(VERSION[4]) return str(main + sub) -
Problems with own filters or why list doesn't have method "apend" (Python)
I try to write my own filter. But it doesn't work and I don't understand why. Table regimeCalendar contains rows with same columns value "dates" and I want that my filter return only distinct values, maybe I go in wrong way? It is an error that points in the template in the string which uses my filter: 'datetime.date' object has no attribute 'append' My filter file: ... @register.filter(is_safe=False) def get_distinct_dates(value): """Adds the arg to the value.""" try: results = [] for item in value: add = True for result in results: if result == item.regimeCalendar.date: add = False break if add: results.append(item.regimeCalendar.date) while len(results) < 21: result.append("") return results except (ValueError, TypeError): return '' models.py file: class RegimeCalendar(models.Model): patient = models.ForeignKey(Patient) date = models.DateField(default=datetime.now, unique=True) class Meta: ordering = ['date'] unique_together = ('patient', 'date') class AppointmentCalendar(models.Model): added_at = models.DateTimeField(default=datetime.now, blank=True) appointment = models.ForeignKey(Appointments) regimeCalendar = models.ForeignKey(RegimeCalendar) patient = models.ForeignKey(Patient) doctor_mark = models.BooleanField(default=False) nurse_mark = models.BooleanField(default=False) views.py file: ... context['AppointmentCalendar'] = AppointmentCalendar.objects.filter(patient=patient) ... my template html file: {% for item in AppointmentCalendar|get_distinct_dates %} ... {% endfor %} -
Two buttons save on one page
I have problem with buttons on one page. Buttons on bottom of the page are not working, and all buttons on top are working good. On bottom only save button dosen't work. Bellow is my code in template. Here is my buttons on top: {% block top_menu %} {% get_obj_perms user for current_calendar as "perm_list" %} <form action="{% if post.pk %}{% url 'event_edit' post.pk %}{% else %}{% url 'event_create' %}{% endif %}" method="POST"> {% csrf_token %} <fieldset {% if 'can_edit_posts' not in perm_list %}disabled="disabled"{% endif %}> <input type="hidden" name="delete" value="" /> <ul class="btn-group"> <li><a href="{{ back_url|default:"/" }}"><span class="button"><i class="icon-left"></i>Back</span></a></li> {% if 'can_edit_posts' in perm_list %} <li><input class="button" id="save" type="submit" value="Save Changes" name="bottom_button"></li> <li><a class="button" href="{{ back_url|default:"/" }}"><i class="icon-cancel-circled"></i>Discard Changes</a></li> {% endif %} {% if 'can_delete_posts' in perm_list and post.pk %} <li><a class="button" href="{% url 'event_delete' post.pk %}"><i class="icon-trash"></i>Delete</a></li> {% endif %} </ul> </fieldset> </form> {% endblock top_menu %} Here is my buttons on bottom: {% block bottom_menu %} {% get_obj_perms user for current_calendar as "perm_list" %} <form action="{% if post.pk %}{% url 'event_edit' post.pk %}{% else %}{% url 'event_create' %}{% endif %}" method="POST"> {% csrf_token %} <fieldset {% if 'can_edit_posts' not in perm_list %}disabled="disabled"{% endif %}> <input type="hidden" name="delete" value="" … -
Django: how to effectively use select_related() with Paginator?
I have 2 related models with 10 Million rows each and want to perform an efficient paginated request of 50 000 items of one of them and access related data on the other one: class RnaPrecomputed(models.Model): id = models.CharField(max_length=22, primary_key=True) rna = models.ForeignKey('Rna', db_column='upi', to_field='upi', related_name='precomputed') description = models.CharField(max_length=250) class Rna(models.Model): id = models.IntegerField(db_column='id') upi = models.CharField(max_length=13, db_index=True, primary_key=True) timestamp = models.DateField() userstamp = models.CharField(max_length=30) As you can see, RnaPrecomputed is related to RNA via a foreign key. Now, I want to fetch a specific page of 50 000 items of RnaPrecomputed and corresponding Rnas related to them. I expect N+1 requests problem, if I do this without select_related() call. Here are the timings: First, for reference I won't touch the related model at all: rna_paginator = paginator.Paginator(RnaPrecomputed.objects.all(), 50000) message = "" for object in rna_paginator.page(300).object_list: message = message + str(object.id) Takes: real 0m12.614s user 0m1.073s sys 0m0.188s Now, I'll try accessing data on related model: rna_paginator = paginator.Paginator(RnaPrecomputed.objects.all(), 50000) message = "" for object in rna_paginator.page(300).object_list: message = message + str(object.rna.upi) it takes: real 2m27.655s user 1m20.194s sys 0m4.315s Which is a lot, so, probably I have N+1 requests problem. But now, if I use select_related(), rna_paginator = paginator.Paginator(RnaPrecomputed.objects.all().select_related('rna'), … -
Django form doesn't send back selected radio button
I am writing python/django code to produce a dynamic form which produces a list of radio button options. I'm struggling to pass the selected radio button back to the view running:activities via athID. The page doesn't render as is but if I replace athID= with a hardcoded value Ie '12345' it works. Any ideas? Thanks {% block content %} <h1>{{ club.club_name }}</h1> <form action="{% url 'running:activities' athID= %}" method="post">{% csrf_token %} {% for choice in club.athlete_set.all %} <input type="radio" name="choice" id="choice{{ choice.ath_id }}" value="{{ choice.ath_id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.ath_id }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> {% endblock %} -
Setting upload location when creating an object in Django
I'm wondering how to specify upload location for a file when creating an object in Django in the views, something like this.... step = RouteStep(part_request_number=prn,serialnumber=sn,step=Step.objects.filter(pk=values['step'])[0], upload_drawing=values['upload_drawing']) Here I'm picking up the drawing from another object, but how do I specify its upload location? I'm tried setting various attributes such as upload_to and path with no luck. My guess is that trying to set it after won't work because the object has already been created. Any ideas? -
return object from django query
I'm newbie in Python and building API in Django using rest framework.I'm using mysql for database. I'm trying to get user info while login. I'm using filter query to get values but its returning array. I need object In Login API my code is: isValidUser = users.objects.filter(email=req_email, password=req_password) if isValidUser: response = { 'message': 'success', 'code': 1, 'data':isValidUser.values('uid','first_name','last_name', 'email','gender') } else: response = { 'message': 'User not found', 'code': 0, } return Response(response) For this code I'm this response: { "message": "success", "code": 1, "data": [ { "uid": 6, "first_name": "anuj", "last_name": "sharma", "email": "anujs1991@gmail.com", "gender": "0" } ] } But for this I don't want array of data . Expected result should be : { "message": "success", "code": 1, "data": { "uid": 6, "first_name": "anuj", "last_name": "sharma", "email": "anujs1991@gmail.com", "gender": "0" } } Kindly help me for this. -
integrate reactjs with django on heroku
I have used django framework for server side where django rest framework is used for rest api. I could deploy my django application on heroku but for the frontend part i want to use reactjs. That is why i created a frontend directory inside the root folder of django project. There i have used webpack to run the frontend in localhost:3000. Now how can i integrate the reactjs on already deployed django application. What else should i consider? The root url configuration is urlpatterns = [ url(r'^$', roomFinder, name='roomFinder'), url(r'^api/v1/', include('rents.urls', namespace='rent')), url(r'^api/v1/', include('profiles.urls', namespace='profiles')), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), url(r'^admin/', admin.site.urls), ] Here is my project structure frontend directory is purely reactjs boilerplate whose purpose is only to fetch the data from rest api(rest_framework) and display the content for reactjs i have used this boilerplate https://github.com/react-boilerplate/react-boilerplate -
Confused in the middle of the bridge to go back or forward
hey what can be considered the best modules for web development with python and advice for being a good web developer.i am begging to feel little bored of doing django and python for now any motivational ideas also would be appriciated. -
Django Pipeline 1.6.11: issue updating compiled files
I'm currently using Django 1.10.5 in a project, and I wanted to use Django Pipeline for managing my assets (mainly React components) along with its extension django-pipeline-browserify (0.6.0). These, I think, are my relevant settings: STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder' ) PIPELINE = { 'COMPILERS': ( 'pipeline_browserify.compiler.BrowserifyCompiler', ), 'CSS_COMPRESSOR': 'pipeline.compressors.NoopCompressor', 'JS_COMPRESSOR': 'pipeline.compressors.NoopCompressor', 'BROWSERIFY_ARGS': "--transform [ babelify --presets [ es2015 react ]]".split(), 'JAVASCRIPT': { 'activities': { 'source_filenames': ( 'activities/js/foo.browserify.js', ), 'output_filename': 'js/xxx.js' }, }, } The problem is I can't really figure the rule by which the output files are updated. Most of the times, when I run manage.py collectstatic it just says there are no new files to collect/update (even though I modified the js file). Then, if I remove the output files from STATIC_ROOT to actually force an update it raises this error: File "/home/ritaso/.virtualenvs/ddsi/lib/python3.5/site-packages/django/core/files/storage.py", line 300, in _open return File(open(self.path(name), mode)) FileNotFoundError: [Errno 2] No such file or directory: '/data/dev/ysabel/src/static/activities/js/foo.browserify.browserified.js' It might be worth noting that the Browserify extension expects files to be processed to have the extension .browserify.js and outputs .browserify.browserified.js in STATIC_ROOT. However, it's looking for the output filename in the input dirs! (?) I've been able to get it working a … -
Unresolved attribute reference 'objects' for class '' in PyCharm
I use communicaty pycharm and the version of python is 3.6.1, django is 1.11.1. This warning has no affect for run,but I cannot use the IDE's auto complete. -
(Django )Django Restful Framework autocomplete search bar
I'm trying to create a simple HTML search input based from rest framework API JSON file. so far I manage to GET the data from the JSON file. In console log the data i wanted is there but when I search for it in the search field it gives me this error : GET http://127.0.0.1:8000/nameList?term=a 404 (Not Found) I try to convert it into string but still no different. Here's my code : <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script> </head> <body> <br> <input id="name_search_tags" type="text" placeholder="Search..."> </body> <script> $.getJSON("list/?format=json", function (json) { console.log(json); $.each(json, function(key, val) { var nameList = []; var employee_name = val.employee_name; nameList.push(employee_name.toUpperCase()); var string = nameList.toString(); console.log(employee_name); console.log(nameList); }); $("#name_search_tags").autocomplete({source: 'nameList'}); }); </script> </html> I appreciate everyone help. Thanks -
Django 1.10.6 - Middleware does not work
I'm moving my app from django 1.5 to 1.10 and I don't know why but one of my middlewares doesn't want to work ( there is not problem in django 1.5 ) code from settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'myApp.usersAuth.usersAuth', ] Middleware file - usersAuth.py: class usersAuth(): def test(self, request): request.session['firstName'] = 'test1' request.session['secondName'] = 'test2' and I see an error: File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 82, in load_middleware mw_instance = middleware(handler) TypeError: this constructor takes no arguments -
pip install - command 'cl.exe' failed: No such file or directory on Visual C++ 2015 x86 x64 Cross Build Tools Cmd Prompt
I am running pip install django-auth-ldap but getting the below error on Visual C++ 2015 x86 x64 Cross Build Tools Cmd Prompt. Please help? cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DHAVE_SASL -DHAVE_TLS -DHAVE_LIB LDAP_R -DHAVE_LIBLDAP_R -DLDAPMODULE_VERSION=2.4.28 -IModules -I/usr/include -I/ usr/include/sasl -I/usr/local/include -I/usr/local/include/sasl "-Ic:\work\pytho n 3.6.1\include" "-Ic:\work\python 3.6.1\include" /TcModules/LDAPObject.c /Fobui ld\temp.win32-3.6\Release\Modules/LDAPObject.obj error: command 'cl.exe' failed: No such file or directory -
How to plot the chart with customized point order in django-chartit?
In my application, I have such string value (which is known as version id for a specific application) for x-axis: 1.1, 1.2, 1.11.... The default order of points showing in the chart generated by django-chartit and highcharts is based on lexicographical order such that the x-axis values are displayed in the order 1.1, 1.11, 1.2. How can I customize the plotting order such that they will be shown in the order 1.1, 1.2, 1.11... ? By the way, i have tried several unsuccessful ways to solve this problem, and I find the order of the data source specified in the django backend has nothing to do with the order of that shown in the chart in the front-end. Thus solutions directly working on Highcharts may work. Any ideas will be welcomed. -
Geodjango Distance function not returning Distance object?
This is an unexpected behavior that came up on the road to solve this problem with @Nargiza: 3d distance calculations with GeoDjango. Following the Django docs on the Distance function: Accepts two geographic fields or expressions and returns the distance between them, as a Distance object. And from a Distance object, we can get the distance in each and every one of the supported units. But: Let model be class MyModel(models.Model): ... coordinates = models.PointField() then the following: p1 = MyModel.objects.get(id=1).coordinates p2 = MyModel.objects.get(id=2).coordinates d = Distance(p1, p2) # This is the function call, # so d should be a Distance object print d.m should print the distance between p1 and p2 in meters. Instead we got the following error: AttributeError: 'Distance' object has no attribute 'm' We found a workaround eventually (d = Distance(m=p1.distance(p2))) but the question remains: Why the Distance function didn't return a Distance object? Is this a bug, or we missed something? Thanks in advance for your time. -
ManyToMany self, got error " From product and To product already exists. "
class Product( models.Model ): name = models.CharField(verbose_name="Name", max_length=255, null=True, blank=True) the_products_inside_combo = models.ManyToManyField('self', verbose_name="Products Inside Combo", help_text="Only for Combo Products", blank=True) But i got this error when i tried to put the same values the error -
Django Parse Post Request data (JsonArray)
I have a model Example with 3 fields. class Example(models.Model): name = models.CharField(max_length=200, null=False, blank=False) number = models.CharField(max_length=200, null=False, blank=False) address = models.CharField(max_length=200)` I have a Post API (rest framework). This would have array of objects. I want to parse this array and store each object in my database. This is the Views.py class PostExample(APIView): def post(self, request, format=None): example_records = request.POST["example_data"] print example_records Here "example_data" is the key and value will be an array. Example value:[ { "name": "test", "address": "address", "number": 123456789 }, { ... } ] I am unable to loop through "example_records". "example_records" prints the array but not able to get each object from this. How to achieve this ?? -
How do i integrate sms-otp verification with django-registraion-redux?
i have create a django app. i have use django-registration-redux for user authentication and registrations. now want add/integrate any django sms-gateway for OTP verification? -
Retain edit data for one form when submitting a second
I have a page that I want to behave like this: First, the user only sees a single form, for the sake of example, lets say it allows the user to select the type of product. Upon submitting this form, a second form (whose contents depend on the product type) appears below it. The user can then either fill out the second form and submit it, or revise and resubmit the first form - either way I want the first form to maintain the user's input (in this case, the product type), even if the second form is submitted. How can I do this cleanly in django? What I am struggling with is preserving the data in the first form: e.g. if the user submits the second form and it has validation errors, when the page displays the first form the product type will be rendered blank but I want the option to remain set to what the user picked. This behaviour isn't mysterious or unexpected, but is not what I want. Also, if the user submits the second form successfully, I would like to redirect so that the first form maintains the selection and the second form is cleared. … -
custom Django admin action returning invalid literal error
I have a django model Customer and I built a custom admin action to update one of the model fields. To create the action I created functions as follows: def age(ModelAdmin, request, queryset): if customer.Age == '60 +': customer.Age = 0 elif customer.Age == '36 - 59': customer.Age = 1 else: customer.Age = 2 return customer.Age def education(ModelAdmin, request, queryset): if customer.Education == 'Highschool and below': customer.Education = 0 else: customer.Education = 1 return customer.Education def employment(ModelAdmin, request, queryset): if customer.Employment == 'Student': customer.Employment = 0 elif customer.Employment == 'Contract': customer.Employment = 1 else: customer.Employment = 2 return customer.Employment def stability(ModelAdmin, request, queryset): if customer.Employer_Stability == 'Unstable': customer.Employer_Stability = 0 else: customer.Employer_Stability = 1 return customer.Employer_Stability def residential(ModelAdmin, request, queryset): if customer.Residential_Status == 'Rented': customer.Residential_Status = 0 else: customer.Residential_Status = 1 return customer.Residential_Status def salary(ModelAdmin, request, queryset): if customer.Salary <= 1000: customer.Salary = 0 elif 1000 < customer.Salary <= 10001: customer.Salary = 1 else: customer.Salary = 2 return customer.Salary def loyalty(ModelAdmin, request, queryset): if customer.Customer_Loyalty <= 2: customer.Customer_Loyalty = 0 else: customer.Customer_Loyalty = 1 return customer.Customer_Loyalty def balance(ModelAdmin, request, queryset): if customer.Balance <= 2500: customer.Balance = 0 elif 2500 < customer.Balance <= 10001: customer.Balance = 1 else: customer.Balance = 2 … -
Celery group not executing tasks when number of tasks in the group is greater than number of CPU cores
I have a django project in which celery is configred with redis as broker and backend both. I have a group of tasks which is executed asynchronously and I use the save and restore method of GroupResult so that I can update the progress of tasks on frontend using ajax. This all works correctly when the group size is 1 less than the number of CPU cores. Whenever the group size greater than or equal to number of CPU cores, all the tasks are received by celery and nothing happens next unless I restart celery. All tasks are completed but I have to restart it. My celery settings are as follows: BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['pickle'] CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' I have used Rabbitmq also in place of redis as Broker but the same thing happens in case of Rabbitmq also. Why is this happening? I am not able to find any thing on this issue. -
What is the proper way to pass the id/slug argument to a DeleteView in a test case
Hi I'm running a test on my DeleteView and I'm having an error. def test_ProductDeleteView(self): products = mixer.cycle(20).blend('mainapp.Product') viewfn = views.ProductDeleteView.as_view( success_url='/', template_name='delete.html', ) product = Product.object.first() factory = RequestFactory() request = factory.delete('/wadiyabi/delete/1', args=(product.id,)) #pytest.set_trace() resp = viewfn(request, args=(product.id,)) self.assertEqual(resp.status_code, 200) self.assertEqual(Product.objects.count(), 19) errors AttributeError: Generic detail view ProductDeleteView must be called with either an object pk or a slug. -> resp = viewfn(request, args=(product.id,)) so my question is what is the proper way to pass an id to a DeleteView in a test case. -
Which services to use for creating a multi platform auction app?
I am making an auction application that will run on iOS/Android and the also the web if logged in through a browser. I am having a difficult time coming up with a solution to which backend to use, I have used Django in the past along with the Django REST framework for serving mobile devices. For static images I used an S3 bucket to store and keep references to the images in the Django DB (mySQL). Given that this auction app will need to be fairly real time, I was thinking of using Node, angular, mongodb and express (MEAN) along with featherless and socket.io for real time updates and REST queries. Now, I wanted to know whether this is a good approach or not, is there a better way of setting up the backend by using something that I am not aware of? I would like to keep all of the business side logic on the server, would Node be good for that? In Django, I was able to do quite a lot of server side logic in python which was a real plus, but it seems very outdated.