Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can someone provide a demo/sample app about Agora.io integration in django framework for realtime video/video broadcasting?
I was trying Agora.io for one of my webapp. Havn't found a good documentation about using agora.io in django framework. It would be of great help if someone can provide me a demo/sample app. Thanks in advance. -
how to update the value of some id from another model?
here in the expense model the payment_option comes from ledger model and while adding the expense form if the user select some ledger.id then i want to update the value of amount_to_pay in ledger model of the particular id?How can i do that? models class Ledger(models.Model): ledger_name = models.CharField(max_length=200) account_number = models.CharField(max_length=250,unique=True) account_type = models.CharField(max_length=200) opening_balance = models.FloatField(default=0.0) amount_to_pay = models.FloatField(default=0.0,blank=True,null=True) current_balance = models.FloatField(default=0.0,blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = AutoSlugField(unique_with='id', populate_from='ledger_name') class Expense(models.Model): pay_from = models.CharField(max_length=200) payment_option = models.ForeignKey(Ledger, on_delete=models.CASCADE) amount_to_pay = models.FloatField(default=0.0) expense_date = models.DateField(default=datetime.date.today) expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE) note = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = AutoSlugField(unique_with='id', populate_from='expense_type') -
Zip function with four lists
When i use zip for four lists taken from json it complains that the fourth list is not iterable, no matter which of my lists is the fourth. It works fine with three lists. sta= json.loads(aircraft.stations).get('Stations'); stations = zip(sta.get('name'),sta.get('short'),sta.get('arm'),sta.get('type')); { "Stations": { "name": [ "Aircraft", "Pilots", "Seat 3", "Seat 4", "Seat 5", "Seat 6", "Seat 7", "Seat 8", "Fwd.Baggage", "Rear Baggage", "Inb. Fuel Tank", "Outb. Fuel Tank" ], "values": [ "127,1", "119,0", "159,0", "159,0", "198,0", "198,0", "229,0", "242,0", "43,0", "255,0", "126,8", "148,0" ], "short": [ "ac", "pilot", "s3", "s4", "s5", "s6", "s7", "s8", "fwdb", "rearb", "inbf", "outbf" ], "type": [ "ac", "crew", "pax", "pax", "pax", "pax", "pax", "pax", "bag", "bag", "fuel", "fuel" ] } } zip(s.get('type'),s.get('short'),s.get('name'),s.get('arm')) Traceback (most recent call last): File "", line 1, in TypeError: zip argument #4 must support iteration -
What are other real-world and useful usages of model managers other than filtering?
This is my first time learning Django Model Mangers. I saw videos on YouTube and answers on SO. Everywhere I see they are using model managers for filtering like: example: class BlueManager(models.Manager): def get_query_set(self): return super(BlueManager, self).get_query_set().filter(colour='Blue') class MyModel(models.Model): colour = models.CharField(max_length=64) blue_objects = BlueManager() another example: class AvailableBookManager(models.Manager): def get_query_set(self): return super(AvailableBookManager, self).get_query_set().filter(availability=1) class Book(models.Model): (...)#fields definition objects = models.Manager() #default manager available_objects = AvailableBookManager() #own manager here, I can use books = Book.objects.filter(available=1). Why do I make it so complicated? third example: class BookManager(models.Manager): def title_count(self, keyword): return self.filter(title__icontains=keyword).count() class Book(models.Model): title = models.CharField(max_length=100) publication_date = models.DateField() num_pages = models.IntegerField(blank=True, null=True) objects = BookManager() # The Custom Manager. def __unicode__(self): return self.title These examples are good for understanding what is model manager? but they aren't useful. Some of these examples is against Simple is better than complex, if I can do a simple filter with one line of code why do I have to make a model manager with 5 or 6 line of codes and do that same thing. Can you please help me out understand this by providing more useful and real-world examples.I hope you help me, thank you. -
Django query if field has chosen
I have 2 models : ServiceRequest and Quote like this: class ServiceRequest(models.Model): post_time = models.DateTimeField(default=timezone.now) class Quote(models.Model): service_request = models.ForeignKey(ServiceRequest, on_delete=models.CASCADE) status = models.BooleanField(default=False) My question is: how to get queryset from ServiceRequest can know one of Quote has status is True ? Example : ServiceRequest id = 1 , have 2 Quote. One status is True and one is False. ServiceRequest id = 2 have 2 Quote, both them status is False. I want id=1 return True, and id=2 return False Thank you -
How to resolve the "psycopg2.errors.UndefinedTable: relation "auth_user" does not exist" when running django unittests on Travis
I'm using Travis for CI/CD as part of my Django app, with a postgresql database. (Django 2.1.4) The build consistently fails on Travis as soon as the tests run. I receive this error: psycopg2.errors.UndefinedTable: relation "auth_user" does not exist I have tried: makemigrations, migrate auth, migrate myapp, migrate --run-syncdb. All of which fail with the same error. The tests run locally with a sqlite3 database, and on a prod-like heroku environment with a postgresql database. .travis.yml ... before script: -psql -c 'create database travis_ci_test;' -U postgres services: -postgresql script: -yes | python3 manage.py makemigrations -python3 manage.py migrate auth -python3 manage.py migrate --run-syncdb -python3 manage.py tests test/unit_tests settings.py ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'travis_ci_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost', } } ... INSTALLED_APPS = [... 'django.contrib.auth', ] Here is the output from the failing build on Travis. 'migrate auth' is successful (I think this is the crucial line for auth_user : Applying auth.0001_initial... OK) 0.22s$ psql -c 'create database travis_ci_test;' -U postgres CREATE DATABASE 1.50s$ yes | python3 manage.py makemigrations TEST_ENV... AWS_INTEGRATION... Databases ... {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'travis_ci_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost'} Installed Apps ... ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'races.apps.RacesConfig', 'storages'] No … -
How to dynamically display data from a model using a button in django?
I am trying to load data from a model dynamically, the issue I am having is that I am unable to get the data dynamically, for example this is the model: class mentee(models.Model): application_date_time = models.DateTimeField() full_name = models.CharField(max_length=100) email = models.CharField(max_length=50) phone = models.CharField(max_length=50) gender = models.CharField(max_length=50) university = models.CharField(max_length=500) major = models.CharField(max_length=50) class_standing = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) student_type = models.CharField(max_length=50) profile_pic = models.CharField(max_length=1000) linkedin = models.CharField(max_length=1000) github = models.CharField(max_length=1000) website = models.CharField(max_length=1000) resume = models.CharField(max_length=1000) area_of_concentration = models.CharField(max_length=50) roles_of_interest = models.CharField(max_length=100) meet_in_person = models.CharField(max_length=100) preferred_years_of_experience = models.CharField(max_length=50) organization_of_interest = models.CharField(max_length=50) area_of_expertise = models.CharField(max_length=100) skills_desired = ArrayField(ArrayField(models.CharField(max_length=100))) gender_preference = models.CharField(max_length=50) time_preference = models.CharField(max_length=50) location_preference = models.CharField(max_length=50) In this function I am trying invoke is this def showprofile(full_name): mentee_data = mentee.objects.filter(full_name="Katha Benterman") return mentee_data.values() What this should do is that it should show the data in a bootstrap model which is set in the HTML like this: <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Profile</button></td> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% for profile in show_profile %} {{ profile.full_name }} </br> {{ profile.email }} </br> … -
Django form submit using ajax Javascript
Im trying to post a form from a input datagrid table. I get a None object only, when I print the filter_list(refer the code).But when I check the data from the table by using alert function on success,It returns the correct selected value .I dont know much about ajax. Please help me sort out.I attached the code for views.py,HTML below, In Views.py, def mytable1(request): if request.method == 'POST': filter_list = request.POST.get('regionwiselist') **print(filter_list)** context={'filter_list':filter_list} print(context) return render(request, 'mytable2.html', context) else: sbc = MTD.pdobjects.all() df = sbc.to_dataframe().reset_index(drop=True) df.reset_index(inplace=True) dict1=df.transpose().to_dict() dict=[] for k,v in dict1.items(): dict.append(v) col=list(df1.columns) context={ 'Vertical_value':dict, 'Vertical_header':col } return render(request, 'mytable2.html', context) In mytable2.html, {% extends "base.html" %} {% block body %} {% if Vertical_header %} <script> $(document).ready(function(){ $("#gridContainer").dxDataGrid({ dataSource: {{Vertical_value|safe}}, showBorders: true, paging: { pageSize: 10 }, keyExpr: "RGN", showBorders: true, selection: { mode: "multiple" }, paging: { pageSize: 10 }, filterRow: { visible: true }, pager: { showPageSizeSelector: true, allowedPageSizes: [5, 10, 20], showInfo: true }, columns: {{Vertical_header|safe}}, showBorders: true }); }); </script> <div class="demo-container"> <form id='my_form'> {% csrf_token %} <div id="gridContainer"></div> <button type="submit" class="btn btn-primary btn-lg"><i class="fa fa-angle-double-down"></i></button> </form> </div> <script type="text/javascript"> $(document).on('submit','#my_form',function data(e){ var dataGrid = $("#gridContainer").dxDataGrid("instance"); var selectedKeys = dataGrid.getSelectedRowKeys(); $.ajax({ type: 'POST', url: '{% … -
Not Found: .../asciinema-player.js.map
I'm trying to use asciinema player in my django project to replay session recordings but I keep getting the same error in my terminal: Not Found: .../asciinema-player.js.map HTTP GET .../asciinema-player.js.map 404 this is my code: {% load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'plugins/asciinema/asciinema-player.css' %}"> </head> <body> <asciinema-player src="{{logpath}}"></asciinema-player> <script src="{% static 'plugins/asciinema/asciinema-player.js' %}"></script> </body> </html> logpath is defined in my views.py: class SshLogPlay(LoginRequiredMixin,DetailView): model = Log def get(self,request,pk): return render(request,'myproject/sshlogplay.html') def get_context_data(self, **kwargs): context = super(SshLogPlay, self).get_context_data(**kwargs) objects = kwargs['object'] record = os.path.join(settings.MEDIA_DIR,"records") context['logpath'] = '{0}{1}-{2}-{3}/{4}.json'.format(record,objects.start_time.year,objects.start_time.month,objects.start_time.day,objects.log) return context Could anyone help me please! Thank you. -
Django Slugs and redefining a save method
So I found a code to add a slug to my instance of my model named Product. But my problem comes from the save() function. I cannot understand what the part with super(Article, self) means. class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to="products/", blank=True, null=True) slug = models.SlugField(unique=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Article, self).save(*args, **kwargs) -
Django template filters
Which filter should i use in django templates in order to display my text in the way it was entered including all the spaces and even alignments(whether it's Left, Right etc) For eg: I want to add some description about a title and i want it to be in this form: "My my, 2018 is going by so quickly! Maybe it went by fast because we were too busy loading up on all kinds of yummy food at all the new restaurants that opened up. As usual, we took the liberty of curating a list of eateries that we think you should not keep waiting. So, without much further adieu, there’s your Culinary Bucket List For The Rest Of 2018". Currently my title description is set in this format : {{value:Linebreaks}} -
I get an error message while trying to fetch data from aws s3 (Django)
File "/home/thibault/Desktop/sp3d_cloud/digital/models.py", line 717, in natural_key return {"name":self.file.name.rsplit("/",1)[1], "url":self.file.url, 'id':self.id, 'type':self.type, 'data':self.data, 'size':self.file.size, 'date':str(self.date_created)} File "/home/thibault/.local/lib/python2.7/site-packages/django/db/models/fields/files.py", line 77, in size return self.storage.size(self.name) File "/usr/local/lib/python2.7/dist-packages/storages/backends/s3boto3.py", line 511, in size return self.bucket.Object(self._encode_name(name)).content_length File "/usr/local/lib/python2.7/dist-packages/boto3/resources/factory.py", line 339, in property_loader self.load() File "/usr/local/lib/python2.7/dist-packages/boto3/resources/factory.py", line 505, in do_action response = action(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/boto3/resources/action.py", line 83, in call response = getattr(parent.meta.client, operation_name)(**params) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 312, in _api_call return self._make_api_call(operation_name, kwargs) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 601, in _make_api_call raise error_class(parsed_response, operation_name) ClientError: An error occurred (404) when calling the HeadObject operation: Not Found -
Need to get user lists along Average in django while data in separate table
I am trying to get user list along with average login time Model 1: class User(models.Model): name = models.CharField(max_length=200) age = models.CharField(max_length=200) email = models.CharField(max_length=200) Model 2: class History(models.Model): login_time = models.DateTimeField() logout_time = models.DateTimeField() user = models.ForeignKeyField(User, related_name="user_relation") I need records in list of below format avg_logged_in_time will average of be (logout_time - login-time) Name, email, avg_logged_in_time -
Django deserialize to model instance without saving to DB
I want to serialize an object to Json, then deserialize it as the object, without save it to DB (it's already saved). The reason is that the current state of the model may be different from the state when I serialized it. This is how I currently serialize the object: ser_obj = serializers.serialize("json", [self.instance]) Now, as I understand, in order to deserialize I can do something like: for obj in serializers.deserialize("json", ser_obj): obj.save() But that will save the object to DB, which I don't want to. I guess I can also do something like: MyModel(field1 = ser_obj['field1'], field2 = ser_obj['field2'] ) But it seems wrong. So any idea how can I deserialize json object into Django model without saving to DB? -
Collapse .data-target doesn't work when setting the target id, or even target class, with data from Django template tag
I'm trying to collapse some content rendered in a for loop via Django template tag using bootstrap. If I hard code the collapse target, either as a Class target (data-target=".someclass") or href (href=#sometarget) I can get the function to work. However, since its a for loop, I need different targets for each 'item' so when I try and use dynamic/unique data from database as the target, bootstrap fails to collapse the content. Collapsable trigger {% for set in set_list %} {% get_comment_count for set as comment_count %} <!-- Title --> <a href="{% url 'curate:set_detail' slug=set.slug %}"> <h1 class='title'>{{set.title}} </a> **<button class="btn btn-link btn-sm" data-toggle="collapse" role='button' href='#{{set.slug}}' data-target="" aria-expanded="false" aria-controls="multiCollapseExample1">** <i class="material-icons"> arrow_drop_down </i> </button> Collapsable {% for item in set.items.all %} <div class="col-lg-2 col-sm-2 col-xs-6 item mr-1 set-item-small" id="multiCollapseExample1" aria-expanded="true"> {% if item.type == 'video' %} <a href="{% url 'curate:item_detail' slug=item.slug %}"><img class='img-fluid img-preview' src="{{item.image_sized.url}}" alt="broken"> </img> <span class="badge badge-success badge-positioner collapse multi-collapse show">Video</span> SOME OTHER CODE **<div class="collapse {{set.slug}} multi-collapse" id={{set.slug}}>** <a href="{% url 'curate:item_detail' slug=item.slug %}"> <h5 class='header collapse multi-collapse'>{{item.title}}</h5> <a href="{% url 'curate:set_detail' slug=set.slug %}#comment_thread">{{ comment_count }} comments</a> </a> </div> In the example above, I'm trying to use href targets, which don't work. I can confirm that … -
I am facing an error when using the @login_required decorator, it shows TemplateDoesNotExist at /accounts/login/
I am trying to use login decorator in my project but when I use it it shows me the error TemplateDoesNotExist at /accounts/login/ registration/login.html urls.py path('', login.login_view , name='login'), path('fileupload/', FileUpload.fileup, name='fileupload'), view.py->FileUpload.py->fileup @login_required(login_url='login') def fileup(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() print(form.image) print(form.user_id) send_message(str(form.image), form.user_id) text_filename = 'media/' + str(form.image).rstrip('.jpg') + '.txt' form.text_file = text_filename print(str(form.text_file)) form.save() with open(text_filename, 'r+') as file: new_text = file.read() return render(request, "pd/NewText.html", { 'form': form, 'new_text': new_text, }) else: form = DocumentForm() return render(request, 'pd/FileUpload.html', {'form': form}) I want if user has not signed in and try to access the url fileupload\ then it not allow until he/she has not signed in. -
Django URL parameters and Views
I have a view which at click would accept the leave and do these two things. Deduction of the amount of leaves applied for and change the object status to accepted so it can show up in another template. I've tried the following but not luck def accept_leave(request,id): # accept email all_item = Leave.objects.get(id=id) employee = Employee.objects.get(id=id) context = {'employee': employee, 'all_item': all_item} leave = employee.leave_set.last() #Annual Leave if leave.leave_Type == 'Annual_leave': employee.Annual_leave -= leave.leave_qty leave_status = "Accepted" employee.save() #other conditions are here as well else: subject = "Leave Accepted" # email subject email_from = "settings.EMAIL_HOST_USER" # email from to_email = ['talhamurtaza@clickmail.info'] # email to with open("C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.txt", 'rb') as f: msgbody = f.read() msg = EmailMultiAlternatives( subject=subject, body=msgbody, from_email=email_from,to=to_email) html_template = get_template("C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.html").render() msg.attach_alternative(html_template, "text/html") msg.send() return render(request, 'projectfiles/email.html', context) But I am unable to do so, it gives me url errors and view errors/ e.g. 1. accept_leave() takes exactly 2 arguments (1 given) 2. quereyset doesnot exist 3. no matching querey etc models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from datetime import date,datetime class Employee(models.Model): allowed = models.BooleanField(default=True) employee_name = models.OneToOneField(User, on_delete = models.CASCADE) employee_designation … -
Is it possible to deploy my Django ASGI with apache?
I have Django restframework APIs working with mod_wsgi already deployed Apache2, I am expanding project with implementing a chatby using Django channels, everything is set but no way to deploy its with apache. -
Django or Delphi which is efficient for web application development? [on hold]
I have to start a web application using Django or Delphi. Can anyone help me choosing the more efficient one ? -
Reverse for 'xyz' not found. 'xyz' is not a valid view function or pattern name
I have defined a function in my views.py views.py from django.shortcuts import render, redirect from django.urls import reverse def ax(request): if request.method == 'POST': *** Some code *** else: *** Some code *** return render(request, 'ajmytable2.html', context) And this is my html ajmytable2.html {% extends "base.html" %} {% block body %} ** Some code ** <script type="text/javascript"> ** Some Code ** $(document).on('submit','#my_form',function data(){ var dataGrid = $("#gridContainer").dxDataGrid("instance"); var selectedKeys = dataGrid.getSelectedRowKeys(); $.ajax({ type: 'POST', url: '{% url 'ax' %}', ** Some Code ** } }); }); </script> urls.py from django.contrib import admin from django.urls import path,include from django.contrib.auth import views as auth_views from dash.views import * urlpatterns = [ ** Some url patterns**, path('ax/', ax, name='ax'), ] But when I run my server with the url "ax/", I am getting an error like "Reverse for 'mytable1' not found. 'mytable1' is not a valid view function or pattern name." I don't have a view named mytable1. But I am unable to find from where this error is coming. I am attaching a screenshot of the error image also. Please help me to sort out this. Thanks -
Array value must start with "{" or dimension information django
I have a array filed in my code code = ArrayField(base_field=models.CharField(max_length=225), null=True, default=list) and my base the field contains a list of codes like so 00021200667275,00051141981468,03134375005920,03134375217873,05010027557437,50021200667270,50051141981463,53134375005925 now I'm returning the product my passing the code over url class Product(APIView): def get_product(self, code): try: return ProductModel.objects.filter(code__contains=code).first() except Product.DoesNotExist: raise Http404 def get(self, request, code, format=None): product = self.get_product(code) serializer = ProductSerializer(product) return Response(serializer.data) but I have a problem with the ArrayField and currently the Traceback is Traceback: File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) The above exception (malformed array literal: "00021200667275" LINE 1: ...s_product" WHERE "products_product"."code" @> '000212006... ^ DETAIL: Array value must start with "{" or dimension information. ) was the direct cause of the following exception: So I'm not sure what is happening, can someone help me overcome this, thanks. -
AttributeError at /files/
when I am going to implement tag field I am getting following error AttributeError: Got AttributeError when attempting to get a value for field tags on serializer CategorySerializers. The serializer field might be named incorrectly and not match any attribute or key on the Category instance. Original exception text was: 'Category' object has no attribute 'tags'. models.py class Category(models.Model): name = models.CharField(max_length=100) class Tag(models.Model): tag_name = models.CharField(max_length=30) class FileUp(models.Model): name = models.ForeignKey(Category, on_delete=models.CASCADE) file = models.FileField(upload_to='path') tags = models.ManyToManyField(Tag) def __str__(self): return self.name.name serializers.py class TagSerializers(serializers.ModelSerializer): class Meta: model = Tag fields = ['tag_name'] class FileSerializers(serializers.ModelSerializer): class Meta: model = FileUp fields = ['file'] class CategorySerializers(serializers.HyperlinkedModelSerializer): files = FileSerializers(source='file_set', many=True, read_only=True) tags = TagSerializers(many=True) class Meta: model = Category fields = ['id', 'name', 'files', 'tags'] read_only_fields = ['tags'] here is what I tried, I have put Tag in Category model but when I am going to add files I cannot add tags to it or select tags in the admin panel. But, If I add Tag to FileUp I am getting error above shown. How can I apply to Tag to FileUp? any help please? -
Access variable in def __init__ to outside
I have a class with name UserResponseSearchForm like this : class UserResponseSearchForm(forms.Form): def __init__(self, *args, **kwargs): global gejala_search qry = kwargs.pop('qry') super(UserResponseSearchForm,self).__init__(*args, **kwargs) self.fields['gejala_id0'] = forms.ModelMultipleChoiceField(queryset=Gejala.objects.filter(gejala__icontains=qry).distinct().order_by('gejala'),widget=forms.CheckboxSelectMultiple, required=False) gejala_search = self.fields['gejala_id0'] gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) gejala_id2 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=2).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) gejala_id3 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=3).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) And i want to access the variable gejala_search in def __init__. I access it like this : class UserResponseSearchForm(forms.Form): def __init__(self, *args, **kwargs): global gejala_search qry = kwargs.pop('qry') super(UserResponseSearchForm,self).__init__(*args, **kwargs) self.fields['gejala_id0'] = forms.ModelMultipleChoiceField(queryset=Gejala.objects.filter(gejala__icontains=qry).distinct().order_by('gejala'),widget=forms.CheckboxSelectMultiple, required=False) gejala_search = self.fields['gejala_id0'] gejala_id0 = gejala_search gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) gejala_id2 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=2).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) gejala_id3 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=3).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) I add gejala_id0 = gejala_search to access the variable gejala_search in def__init__ and it return error NameError: name 'gejala_search' is not defined. How to access the variable gejala_search? Hope anyone can help me -
Python package which return country list, ISD codes, and their ISO codes
I have a Django application. I have hardcoded country list, ISD codes, and their ISO codes. Is there any python library which can return all this data? -
When to use Django Permissions?
I am talking about managing object-level permissions with django-guardian. AFAIK, permissions do not filter the queryset. Django queryset permissions So, if i have to filter the queryset and return relevant records, what are permissions for? Is there something permission does which filtering cannot?