Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show a jquery dropdown menu in a django test with selenium?
I don't find the way to make visible a jquery dropdown menu in a django test with selenium. Here some parts of the code ("admin_user" is the link who has to drop down the menu with link "Coop Admin App"): def wait_loading(self, driver, xpath_string): try: WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, xpath_string))) return True except TimeoutException as ex: print("Exception has been thrown. " + str(ex)) def test_membership_request(self): s = self.selenium s.get('%s%s' % (self.live_server_url, "/")) self.wait_loading(s, '//a[contains(text(), "admin_user")]') s.find_element_by_partial_link_text("admin_user").click() self.wait_loading(s, '//a[contains(text(), "Coop Admin App")]') s.find_element_by_partial_link_text('Coop Admin App').click() The test is always throwing ElementNotVisibleException, so the click in "admin_user" seems not to make visible "Coop Admin App". Any ideas? -
Django Model delete foreign key
I have my Model Config, which contains a ForeignKey PeriodicTask. I want to have an 1 to 1 relation, meaning that when I delete Config that PeriodicTask gets deleted and vice versa. class Config(models.Model): name = models.CharField(max_length=200, unique=True) task = models.ForeignKey(PeriodicTask, default=None, null=True, blank=True, on_delete=models.CASCADE) Using CASCADE only my Config gets deleted, when PeriodicTask gets deleted but not vice versa. Also PeriodicTask belongs to an external module, so I don't have direct access to it. How can I accomplish a 1 to 1 deletion relation? -
nginx+gunicorn+django: Gunicorn timeout within 30Sec How to solve it without changing timeout in Conf file?
My app is running with nginx+gunicorn+DRF. nginx gives 502 because ,for perticular process gunicorn need more than 30 sec. However If I assign process to celery, tasks get completed but Gunicorn gets timeout because it is waiting for Celery to complete the task(Which takes more than 30 Seconds). How can I free Gunicorn when my task is running on Celery. I don't want to change timeout in conf file of Gunicorn because in future many process comes with different processing time.So I need some concrete solution. How to resolve it completely? -
Only list items as url parameters in django
Id like to have url variable that would only accept items from list, but i dont know how to implement it in urls. list = ['foo', 'bar', 'test'] and urls.py, that i dont know how to implement list items: url(r'^(?P<list_item>)/$', views.letnik, name="list_item"), I would really appreciate it if you could help me out! -
deploying django website on apache server
I am new to Django and has no experience deploying website other that to htdocs folder. I want to deploy Django website to apache server seen a lot of tutorial but could not understood what to do. my configuration is : Apache version: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30 server root: c:/xammp/apache python version: 3.6.0 Django version: 1.10.6 -
Django, reading csv from form request throws: Error: line contains NULL byte
I have simple application written in django with one form that uploads CSVfile. My CSV file has a lot of columns with cyrillic letters. Just for testing I made my view handle html form like this: @login_required() @require_http_methods(["POST"]) def upload_csv(request): uploaded_file = request.FILES['csv'].read(200) data = csv.reader(uploaded_file) for row in data: print(row) return redirect('moderator:upload_view') When I try to upload my CSV, I get this error: Traceback (most recent call last): File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python27\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Python27\lib\site-packages\django\views\decorators\http.py", line 42, in inner return func(request, *args, **kwargs) File "D:\myapp\moderator\views\upload.py", line 32, in upload_csv for row in data: Error: line contains NULL byte [08/Apr/2017 13:53:41] "POST /moderator/upload_csv/ HTTP/1.1" 500 87052 -
Can't run manage.py in PyCharm
I made new project in the PyCharm. I selected Django and enabled django-admin. But I encoutered strange issue. I don't have 'run manage.py Task' option in my Tools menu. When I try to run it through terminal with command './manage.py', it throws exception that it 'Couldn't import django' I have older project with same manage.py code. There I can run manage.py via Tools menu and I can't run it through terminal ('Couldn't import django'). -
Integrate let's chat with django
I have recently checked out http://sdelements.github.io/lets-chat/, a really cool group chat application built on NodeJS and MongoDB. I am working on a project in Django/Postgres and need a quick and neat group chat solution. How do I integrate let's chat into my application. The queries I have, Ideally the authentication should happen in django and the creation of users/chat rooms too. How to handle communications between Node server and Django server. In the time of hosting, what should i be worried about? What are the other problems I can run into? Is there any other alternative to let's chat with MIT license and similar features? I am very sorry for being naive in question. I am just a beginner. Please help me out. -
Updating Django from 1.5 to 1.8 BaseModel c __metaclass__?
Good afternoon! I try to update the project from 1.5 to 1.8, in the project there is an application to the models of which there is an appeal through the midsection, the Application with site settings, with the replacement "on the fly", it consists of models.py admin.py, in the model code: class MetaSetting(models.base.ModelBase): """ For easy to use settings(Setting model). Instead of Setting.objects.get(name='KEY'), you can use Setting.KEY """ def __getattr__(cls, key): _model = get_model('options', 'Option') try: val = _model.objects.get(name=key).value except _model.DoesNotExist: val = None if isinstance(val, basestring): val = val.encode('utf-8') return val def set_value(self, key, value, value_type=unicode): """ key = key, value = value, value_type accept following values: unicode int float value_type default - basestring """ _model = get_model('options', 'Option') if _model.objects.filter(name=key).exists(): _model.objects.filter(name=key).update(val=value) else: _model.objects.create(name=key, val=value, value_type=Option.VALUE_TYPE_MAPPING.get(value_type)) class Option(models.Model): """ Simple project settings """ __metaclass__ = MetaSetting class Meta: verbose_name = u'Настройка' verbose_name_plural = u'Настройки' db_table = 'settings_setting' VALUE_TYPE_CHOICES = ( (1, u'Строка',), (2, u'Целое',), (3, u'Вещественное',), # (4, u'Булево',), ) VALUE_TYPE_MAPPING = {float: 3, int: 2, unicode: 1} VALUE_TYPE_CONVERTER = { 1: lambda x: unicode(x), 2: lambda x: int(x), 3: lambda x: float(x), # 4: lambda x: bool(x), } name = models.CharField(u'Ключ', max_length=100, unique=True) val = models.TextField(u'Значение') value_type = … -
django admin css not loading setup
When opening Django admin css of page is not loading.it shows simple page withno css. my setting.py file is set STATIC_URL = '/static/' STATIC_ROOT = "C:/Users/AJAY/AppData/Local/Programs/Python/Python36-32/myprograms/mysite/mysite/static/" STATICFILES_DIRS = [ 'C:/Users/AJAY/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/django/contrib/admin/static/', ] my projecte is in C:/Users/AJAY/AppData/Local/Programs/Python/Python36-32/myprograms/mysite Python version :3.6.0 Django version :1.10.6 -
Creating multiple objects with a single call
I am trying to add multiple objects in my cart using django REST framework. The user will send mutiple sets of data to the cart and the cart will add the rows in the database one by one. My code progress so far is as follows: models.py: class Cart(models.Model): user = models.ForeignKey(User) product = models.ForeignKey(Product) sh_price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.IntegerField() date_added = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: unique_together = ["user", "product"] serializer.py: class CartAddSerializer(ModelSerializer): def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(CartAddSerializer, self).__init__(many=many, *args, **kwargs) class Meta: model = Cart fields = ['user', 'product', 'sh_price', 'quantity', 'date_added'] extra_kwargs = {'date_added': {'read_only': True}, 'sh_price': {'read_only': True},} def create(self, data): product_data = data.get('product' or None) print(product_data) print(product_data.id) product_price = ProductPrice.objects.get(product=product_data) print(product_price) print(product_price.sh_price) return Cart.objects.create(sh_price=product_price.sh_price, **data) views.py: class CartAddAPIView(ListCreateAPIView): queryset = Cart.objects.all() serializer_class = CartAddSerializer lookup_field = 'pk' lookup_url_kwarg = 'id' def get(self, request, *args, **kwargs): try: cart = Cart.objects.filter(user=self.kwargs['id']) print(cart) serializer = CartDetailSerializer(cart, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: print(str(e)) return Response({"status": "failed"}, status=status.HTTP_400_BAD_REQUEST) -
ng-route conflict with django URL
I am trying to use ng-route to load templates. Here is the codes. app.js var app = angular.module('app', [ 'ngResource', 'ngRoute', // 'ui.bootstrap', // 'ngResource', 'student', ]); app.config( function( $locationProvider, $routeProvider ){ $locationProvider.html5Mode({ enabled:true }) $routeProvider. when("/", { template: 'base', }). when("/student/1", { template: "<student-detail></student-detail>", }). otherwise({ template: "Not Found" }) }); student.js var app = angular.module('student', []); app.component('studentDetail',{ templateUrl:'studentDetail.html', controller: function($scope) { $scope.test = 'Got it.' } }); urls.py class SimpleStaticView(TemplateView): def get_template_names(self): return [self.kwargs.get('template_name') + ".html"] urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include("students.api.urls", namespace='students-api')), url(r'^(?P<template_name>\w+)$', SimpleStaticView.as_view(), name='example'), url(r'^$', TemplateView.as_view(template_name='home.html')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When i request /, base field is there, that means ng-view work properly. But when i request /students/1, returns The current URL, student/1, didn't match any of these. Is this because Angular did not get the routing request? How to fix? Thank you -
Django EnumField for Python3 and DRF support
I need EnumField for my Django models. I have tried django-enumfield. But it's not supporting with Django 1.10. I also tried this django-enumfields. But this is not supported with Django REST Framework. My use case, # models.py role = EnumField(UserRoleEnum, default=UserRoleEnum.STUDENT) # enums.py class UserRoleEnum(Enum): STUDENT = 0 TEACHER = 1 ADMIN = 2 -
MySQLdb raises “execute() first” error
how do I fix it? def update_query_extendNum(cls,params): print params sqlString = "REPLACE INTO editor_query(id,extend_num) values(%s,%s)" cursor = connection.cursor() cursor.executemany(sqlString,params) querys = cursor.fetchall() cursor.close() return querys error: # File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner # response = get_response(request) # File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response # response = self.process_exception_by_middleware(e, request) # File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response # response = wrapped_callback(request, *callback_args, **callback_kwargs) # File "C:\work\test\editor\chat_test_service\editor\api.py", line 162, in updataTask # update_query = QueryService.update_query_extendNum([('02f0698462344c9299a93fea2d97b34e',11),('0350d8dcb58e48448f6d9fbabc06a43c',111)]) # File "C:\work\test\editor\chat_test_service\editor\service.py", line 58, in update_query_extendNum # return dao.QueryDao.update_query_extendNum(params) # File "C:\work\test\editor\chat_test_service\editor\dao.py", line 109, in update_query_extendNum # querys = cursor.fetchall() # File "C:\Python27\lib\site-packages\django\db\utils.py", line 101, in inner # return func(*args, **kwargs) # File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__ # six.reraise(dj_exc_type, dj_exc_value, traceback) # File "C:\Python27\lib\site-packages\django\db\utils.py", line 101, in inner # return func(*args, **kwargs) # File "C:\Python27\lib\site-packages\MySQL`enter code here`db\cursors.py", line 382, in fetchall # self._check_executed() # File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 105, in _check_executed # self.errorhandler(self, ProgrammingError, "execute() first") # File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler # raise errorclass, errorvalue # ProgrammingError: execute() first -
Cron(django_cron) not working
I created cron in order to parse data in some period of time. On localhost it worked nice by command python manage.py runcrons. There was a print function inside do which let me see that everything is correct, but the main result is data saving to database. Looks something like this: class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'app.my_cron_job' # a unique code def do(self): page = requests.get('https://karabas.com') tree = html.fromstring(page.content) links = tree.xpath('//div[@class="posters-middle"]/a/@href') print (links) When I deployed my python application(django), and ran python manage.py runcrons there were no any output, no error, and also no data were saved to database. I'v also created the very unix schedule : > crontab -e */5 * * * * source /home/ubuntu/.bashrc && source /home/ubuntu/work/your-project/bin/activate && python /home/ubuntu/work/your-project/src/manage.py runcrons > /home/django/django_project/cronjob.log In five minutes, it output theat I have a mail which contained this: From root@ubuntu Sat Apr 8 05:20:01 2017 Return-Path: <root@ubuntu> X-Original-To: root Delivered-To: root@ubuntu Received: by ubuntu (Postfix, from userid 0) id 5550E7D4CC; Sat, 8 Apr 2017 05:20:01 +0000 (UTC) From: root@ubuntu (Cron Daemon) To: root@ubuntu Subject: Cron <root@ticktock> source /home/ubuntu/.bashrc && source /home/ubuntu/work/your-project/bin/activate && python /home/ubuntu/work/your-project/src/manage.py runcrons > /home/ubuntu/cronjob.log MIME-Version: 1.0 … -
vi nohup.out ,TypeError: unicode argument expected, got 'str'
its in Ubuntu server ,the celery progress does not run. when vi nohup.out , errors happened. i tied to change the encoding.but failed. Traceback (most recent call last): File "/usr/local/bin/celery", line 11, in sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/celery/main.py", line 30, in main main() File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 769, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 307, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 761, in handle_argv return self.execute(command, argv) File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 693, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/usr/local/lib/python2.7/dist-packages/celery/bin/worker.py", line 179, in run_from_argv return self(*args, **options) File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 270, in call ret = self.run(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/bin/worker.py", line 212, in run state_db=self.node_format(state_db, hostname), **kwargs File "/usr/local/lib/python2.7/dist-packages/celery/worker/init.py", line 95, in init self.app.loader.init_worker() File "/usr/local/lib/python2.7/dist-packages/celery/loaders/base.py", line 128, in init_worker self.import_default_modules() File "/usr/local/lib/python2.7/dist-packages/celery/loaders/base.py", line 116, in import_default_modules signals.import_modules.send(sender=self.app) File "/usr/local/lib/python2.7/dist-packages/celery/utils/dispatch/signal.py", line 166, in send response = receiver(signal=self, sender=sender, **named) File "/usr/local/lib/python2.7/dist-packages/celery/fixups/django.py", line 69, in on_import_modules self.worker_fixup.validate_models() File "/usr/local/lib/python2.7/dist-packages/celery/fixups/django.py", line 164, in validate_models num_errors = get_validation_errors(s, None) File "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", line 54, in get_validation_errors e.add(opts, '"%s": CharFields require a "max_length" attribute that is a positive integer.' % f.name) File "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", line 14, in add self.outfile.write(self.style.ERROR("%s: %s\n" % (context, error))) TypeError: unicode argument expected, got 'str' [enter image description … -
How to define two player model in django?
I am having trouble defining models for two player in django. I somehow managed to define models like this. models.py from django.db import models from datetime import datetime class Player(models.Model): name=models.CharField(max_length=40) score = models.IntegerField(default = 0) def __unicode__(self): return self.name def __str__(self): return self.name class Match(models.Model): player_one = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='player_one') player_two = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='player_two') class Score_log(models.Model): match = models.ForeignKey(Match, on_delete=models.CASCADE) log_time=models.DateTimeField(auto_now_add=True, blank=True) class Meta: ordering = ["-match","-log_time"] In Match model, player_one and player_two is defined because i want to validate those with django forms. Also, I am unable to retrieve my objects with Match.player_one.all() and says 'ReverseManyToOneDescriptor' object has no attribute 'all'.Help_me_out? -
I am new to pyton, and would love to learn python framework, which should i opt django or flask?
I surfed a little and found that both were useful in its own means! But would really love to have an expert suggestion! Thanks in advance -
Passing multiples Django Forms in context[] to templates
I have a custom Django user schema to manage roles or user types: StudentProfile ProfessorProfile ExecutiveProfile Due to part of my AbstractBaseUser model stay so: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) slug = models.SlugField(max_length=100, blank=True) is_student = models.BooleanField(default=False) is_professor = models.BooleanField(default=False) is_executive = models.BooleanField(default=False) other fields ... I have the get_student_profile(),get_professor_profile() and get_executive_profile() methods to get the profile user data. I've override the save() method in my custom model User to save the profile data when is_student or is_professor or is_executive have been checked at moment to create an user, their data will be saved in ther respective models: class StudentProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) slug = models.SlugField(max_length=100,blank=True) origin_education_school = models.CharField(max_length=128) current_education_school = models.CharField(max_length=128) extra_occupation = models.CharField(max_length=128) class ProfessorProfile(models.Model): CATHEDRAL_PROFESSOR = 'CATHEDRAL' RESEARCH_PROFESSOR = 'RESEARCH' INSTITUTIONAL_DIRECTIVE = 'DIRECTIVE' OCCUPATION_CHOICES = ( (CATHEDRAL_PROFESSOR, 'Cathedral Professor'), (RESEARCH_PROFESSOR, 'Research Professor'), (INSTITUTIONAL_DIRECTIVE, 'Institutional Directive'), ) user = models.OneToOneField(User,on_delete=models.CASCADE) slug = models.SlugField(max_length=100,blank=True) occupation = models.CharField(max_length=255,blank = False) class ExecutiveProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) slug = models.SlugField(max_length=100, blank=True) occupation = models.CharField(max_length=255,blank = False) enterprise_name = models.CharField(max_length=255,blank = False) I have the forms to each profiles user class UserUpdateForm(forms.ModelForm): class Meta: widgets = {'gender':forms.RadioSelect,} fields = ("username", "email", "is_student", "is_professor", "is_executive",) model = get_user_model() #My … -
How to iterate over object attributes and check for duplicate in python?
I have a list of objects stored in a variable. Each object has two attributes: temp_name and temp_body. Now, I want to iterate through the list of objects and see if the name given by the user already exists in temp_name for any object. I tried doing this: temp_name = request.POST.get('temp_name') templates = EmailTemplate.objects.all() for template in templates: if template.temp_name == temp_name: data = {'status': 'exists'} return JsonResponse(data) else: data = {'status': 'exist_not'} return JsonResponse(data) But this only works for the first item in the list, it won't work from the second item onwards. How do I get this working? -
python-social-auth: pass data to pipeline from url
Clicking on this link: <a href="{% url 'social:begin' 'github' %}?next={{ request.path }}?auth_type={{'authenticate'}}">Authenticate With GitHub</a> With this in settings.py: FIELDS_STORED_IN_SESSION = ['auth_type', ] Later, in a pipeline: auth_type = backend.strategy.session_get('auth_type') print("AUTH TYPE: ") print(auth_type) auth_type is None. What am I doing wrong? -
Can 502 nginx error be anyhow raised because of using django application written in python3 on VPS where python 2.7 is default?
Can 502 nginx error be anyhow raised because of using django application written in python3 on VPS where python 2.7 is default? Django + Nginx/Gunicorn I thought I am getting the issue because of urls.py but that's all correct. Is there any connection, so that it's possible for 502 error to be cause by incompatibility? -
document.getElementsById("").innerHTML does not change the p tag
HTML {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'lessons/style.css' %}" /> <script> function openNav() { document.getElementById("mySidenav").style.width = "20%"; document.getElementById("main").style.marginLeft = "20%"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; document.getElementById("main").style.marginLeft= "20%"; } </script> <div id="mySidenav" class="sidenav"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> <a href="{% url 'home' %}" class="active">Home</a> <a href = "{% url 'lessons:index' %}"class="active">Lessons</a> <a href="{% url 'resources' %}"class="active">Resources</a> </div> <div id="main"> <span style="font-size:30px;cursor:crosshair;display:inline-block" onclick="openNav()">&#9776;</span> <h1>Exercise</h1> <form id = "exercise" action= " "> {% for question in lesson.question_set.all %} {% autoescape off %}{{ question.question_text }} {% endautoescape %}<BR> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} {% if choice.answer %} <input type="radio" name="question{{question.pk}}" value=1 />{% autoescape off %}{{ choice.choice_text }}{% endautoescape %}<BR> {% else %} <input type="radio" name="question{{question.pk}}" value=0 />{% autoescape off %}{{ choice.choice_text }}{% endautoescape %}<BR> {% endif %} <!--<label for="{{question.pk}}choice{{ forloop.counter }}"></label><br />--> {% endfor %} <BR> {% endfor %}<BR><BR> <input type="submit" value="Submit"><BR><BR> </form> </div> <center><p id="grade">Your grade is: </p></center> <button class="accordion"></button> <div class="panel"> {% for question in lesson.question_set.all %} {% autoescape off %}{{question.answer}} {% endautoescape %} {% endfor %} <BR><BR> <p align=center><a href="/../lessons/{{lesson.lesson_id}}" class="backbutton"><span><font-size=14px>Return to Lesson</font></span></a> <a href="/../lessons/quiz/{{lesson.lesson_id}}" class="button"><span><font-size=14px>Quiz {{lesson.lesson_id}}</font></span></a><BR><BR> </div> <BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR> Javascript functions <script type='text/javascript'> //start function document.getElementById("exercise").onsubmit=function() { result … -
Need to extract the first letter of each item in a queryset and pass it to template
I am passing the variable "first_letter" to a view and want to compare this letter to the first letter of each item returned from a query. I can't get to the point where I have a list to compare to, I only get one item returned. Model: class Subjects(models.Model) subject = models.CharField(max_length=75) .... View: def subjects_by_letter(request, first_letter): subject_list = Subjects.objects.all() for item in subject_list: letter = item.subject[0] return render_to_response('/path/to/mytemplate.html', { 'subject_list': subject_list, 'first_letter': first_letter, 'letter': letter, }) With this in the view what I am getting is the first letter of the last record in the query only: ... for item in subject_list: letter = item.subject[0] ... eg: if I have subjects entries of "Apple", "Banana" & "Cucumber" it will return just C instead of a list containing A, B & C. I was hoping someone could pinpoint what simple thing I am missing. Thanks. -
Django - Pass a jQuery array as url argument
I have the following script: jQuery(document).ready(function($) { $( "#continue" ).click(function() { var selected = $("#meds").bootgrid("getSelectedRows"); window.location = "{% url 'meds:prescription' selected %}" }); }); and this view: class PrescriptionView(generic.ListView): template_name = 'meds/prescription.html' context_object_name = 'meds' model = Medicament def get_queryset(self): return Medicament.objects.filter(id__in=self.kwargs['selected']) with this url: url(r'^prescription/(?P<selected>.*)/$', views.PrescriptionView.as_view(), name='prescription') Knowing that selected is an array, for example [3, 6, 4] I'm trying to use it to display the objects with the id in that array but for some reason even when the array is full nothing is passed in the url, it just looks like this http://127.0.0.1:8000/prescription// with an empty page, like the argument didn't pass