Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the best DRY way to repeat a class based view in Django?
I have an app that acts as a booker for the end-user; it's basically a form that calls various apis (BookerApp). It uses two main APIs but in different ways; It calls Google to get geo-location (retrieving lat-long data) to pass through the second api. The issue is I need to use this app in main WebsiteApp and its subsequent templates but with slight modification to the appearance (templates). I know I can repeat the CBV in the website app and modify the leading rendered template file; but was wondering if there was a better DRY method for this? Here is the current structure Project folder > |___ MainProject |__ settings.py |__ urls.py |__ settings.py |___ WebsiteApp |__ Templates |__ views.py <----- repeat the same CBV (found in booker) to here with DRY method |__ urls.py |__ etc.. |___ BookerApp |__ Templates |__ views.py <--- CBV held here |__ etc.. |___ Static I hope this makes sense; I know my project is all over the place and any recommendations would be welcome. In essence the app in Booker is basically a complicated form that I want to be able to use in other templates (mostly held in the WebsiteApp folder … -
Django/inlineformset: override clean method but validation error is not displayed
I try to override clean method in my inlineformset (2 fields app_app_nom and app_dro) but failed I need to test that same app_app_nom is not selected twice To test raise error in clean method (I will code logic after), I try to raise error each time form is submitted (if True: raise error) data are not registered but message error is not displayed and I am redirected...? forms.py class ApplicationInlineFormSet(BaseInlineFormSet): def clean(self): super().clean() # example custom validation across forms in the formset for form in self.forms: # your custom formset validation # app_app_nom = form.cleaned_data.get('app_app_nom') if True: raise ValidationError('You select the same app twice') else: # update the instance value. form.instance.app_app_nom = app_app_nom NAME = Thesaurus.options_list(2,'fr') ACCESS = Thesaurus.options_list(3,'fr') ApplicationFormset = inlineformset_factory( UtilisateurProjet, Application, fields=('app_app_nom','app_dro'), widgets={ 'app_app_nom': forms.Select(choices=NAME), 'app_dro': forms.Select(choices=ACCESS) }, extra=3, can_delete=True, formset=ApplicationInlineFormSet ) template.html <form id="utilisateureditform" method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <a style="margin-right: 40px" data-target="" class="" href="{% url 'project:edit_utilisateur' %}">Nouvel utilisateur</a> <br> <br><div class="dropdown-divider"></div><br> <h2>Applications</h2><br><br> <!-- {{ application|crispy }} --> <!-- curieusement si j'enlève cette ligne le style crispy disparait --> {{ application.management_form|crispy }} <div class="row"> <div class="col-6"><p>Nom de l'application</p></div> <div class="col-5"><p>Droits</p></div> <div class="col-1"><p></p></div> </div> {% for application_form in application %} <div class="row link-formset"> {% … -
Django: how to get a javascript value from template to view?
I am currently using Django framework. I would like to get the value of a javascript value wrote in an html file. I would like to be able to display it in my view file Here is my html file from the folder templates: <script> var toto = "javascript"; document.write(toto) </script> This is my view file: def javascript(request): # print the javascript value here return render(request, "rh/javascript.html") Thank you for your help ! -
Newletter Views not sending Emails after being saved with no error showing
I have created a newsletter app to send emails to subscribers. After adding a new newsletter and setting it to be equal to published it should send the email, but instead, the newsletter is saved with no emails sent. I am sure that the email setting is correct as I am receiving an email after a successful subscription for testing. Here is the complete views.py def newsletter_signup(request): form = NewsletterUserSignupForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): messages.warning( request, 'Your email is already exists in our database') else: instance.save() messages.success( request, 'Your email has been added in our database') subject = "Thank you for Joining our Newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] with open(settings.BASE_DIR + "/templates/newsletter_signup_email.txt") as f: signup_message = f.read() message = EmailMultiAlternatives( subject=subject, body=signup_message, from_email=from_email, to=to_email) html_template = get_template( "newsletter_signup_email.html").render() message.attach_alternative(html_template, "text/html") message.send() context = {'form': form} template = "newsletters_signup.html" return render(request, template, context) def newsletter_unsubscribe(request): form = NewsletterUserSignupForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): NewsletterUser.objects.filter(email=instance.email).delete() messages.success( request, 'Your email has been removed from our database') subject = "You have been removed from our newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] with open(settings.BASE_DIR + "/templates/newsletter_unsubscribe_email.txt") as f: signup_message = f.read() message = … -
Rq worker failed job
I am running a python Django app. It runs rq worker in background to perform additional longer tasks. Every time the call to worker is made it exits with the message Moving job to 'failed' queue (work-horse terminated unexpectedly; waitpid returned 11) The environment setup is redis==2.10.6, rq==0.12.0, python 3.6.10 My system has more than sufficient memory to run the worker thread. When I run the same worker in a docker, it works fine. ------------------------------ ------------ amqp 2.4.2 appdirs 1.4.3 appnope 0.1.0 asgi-redis 1.4.3 asgiref 1.1.2 atomicwrites 1.3.0 attrs 19.1.0 autobahn 19.3.3 Automat 0.7.0 awscli 1.18.69 Babel 2.6.0 bandwidth-sdk 3.0.3 beautifulsoup4 4.7.1 billiard 3.5.0.5 bleach 3.1.0 blis 0.4.1 boltons 19.1.0 boto3 1.9.137 botocore 1.16.19 cached-property 1.5.1 cachetools 3.1.0 catalogue 1.0.0 celery 4.2.1 certifi 2019.3.9 cffi 1.12.3 channels 1.1.8 chardet 3.0.4 Click 7.0 colorama 0.4.3 configparser 4.0.2 constantly 15.1.0 convertdate 2.2.0 croniter 0.3.30 cymem 2.0.2 Cython 0.29.14 daphne 1.4.2 dateparser 0.7.1 DateTimeRange 0.5.5 ddtrace 0.36.1 decorator 4.4.1 defusedxml 0.6.0 dill 0.2.9 dj-database-url 0.5.0 Django 1.11.27 django-appconf 1.0.3 django-axes 4.5.4 django-bower 5.2.0 django-compressor 2.2 django-cors-headers 2.5.3 django-debug-toolbar 1.11 django-extensions 2.1.6 django-htmlmin 0.11.0 django-ipware 2.1.0 django-json-response 1.1.5 django-model-utils 3.1.2 django-phonenumber-field 2.3.1 django-ratelimit 2.0.0 django-redis 4.10.0 django-rest-auth 0.9.5 django-rq 1.2.0 django-static-precompiler 1.8.2 django-test-without-migrations 0.6 … -
Synchronize local CouchDB database with remote CouchDB database when connecting to the internet
The idea is simple, I don't know how the execution is: I'm using CouchDB as an option because it was the only one I found with something like what I need. I have a local application (Python / Django) that writes to a database (CouchDB). The local database should be synchronized whenever possible with the remote database. The connection to the remote database drops a lot so it is important that this web page works locally on the user's computer. Important notes: The database does not have to be exactly CouchDB, it can be another (if there is a better one for this purpose) I am not developing a mobile application, so I will not use a PouchDB, for example. It is actually an offline, but web application, installed on the user's computer. -
psycopg2.errors.InsufficientPrivilege: permission denied for relation django_migrations
What my settings.py for DB looks like: ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fishercoder', 'USER': 'fishercoderuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } I have created a new and empty db named "fishercoder" this way: psql -U postgres create database fishercoder; ALTER USER postgres with password 'badpassword!'; CREATE USER fishercoderuser WITH PASSWORD 'password'; ALTER ROLE fishercoderuser SET client_encoding TO 'utf8'; ALTER ROLE fishercoderuser SET default_transaction_isolation TO 'read committed'; ALTER ROLE fishercoderuser SET timezone TO 'PST8PDT'; GRANT ALL PRIVILEGES ON DATABASE fishercoder TO fishercoderuser; Then I've imported my other SQL dump into this new DB successfully by running:psql -U postgres fishercoder < fishercoder_dump.sql Then I tried to run ./manage.py makemigrations on my Django project on this EC2 instance, but got this error: Traceback (most recent call last): File "/home/ubuntu/myprojectdir/myprojectenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InsufficientPrivilege: permission denied for relation django_migrations I found these three related posts on SO: One, two and three I tried the commands they suggested: postgres=# GRANT ALL ON ALL TABLES IN SCHEMA public to fishercoderuser; GRANT postgres=# GRANT ALL ON ALL SEQUENCES IN SCHEMA public to fishercoderuser; GRANT postgres=# GRANT ALL ON ALL FUNCTIONS IN SCHEMA public to fishercoderuser; … -
Is javascript date object compatible to python datetime object
For example in python, a date can be something like: 2020-06-19T11:32:16.548109Z, is there a way that i can use to convert this to a javascript Date object? -
Django... How to use different several models in one view function?
Any help??? How can I use many models in one view function? I have "get" query from the form template under Q name... like this: class UserSearchRequestView(TemplateView): model=ForQuery template_name='do_requests.html' def get_results(self): query=self.request.GET.get("q") if query: our_object=ForQuery.objects.filter(query_id__iexact=query) return our_object Now I need to pass this object through the search through three models to get results... I know, I could do something like this: def index(request): company_info = Company.objects.all() director_info = Director.objects.all() context = { 'company_info' : company_info, 'director_info' : director_info, } return render(request, 'index.html', context=context) But it is only if this function is outside of the class... But my function inside of the class already... So it doesn't work in my case... I could do like this: def get_context_data(self, **qwargs): conObject = super(DirDetailView, self).get_context_data(**qwargs) conObject['mcons'] = RequestSell.objects.all() conObject['fcons'] = DirDict.objects.all() return conObject But, then these objects are only good for using them in template? How can I bring several models into one view function, do operations with them and return the result. I'm kind of confused and probably don't see obvious? -
Django MultipleChoiceField how show only one item
I am creating a combobox with multiple choices using the MultipleChoiceField component. Everything works perfectly, but the list that appears in the combo brings repeated the item and subitem. I looked in the documentation but found nothing regarding this problem. As I understand it, the choice parameter requires bringing a tuple. The choice_test() returns [('test0', 'test0'), ('Test1', 'Test1'), ('test3', 'test3'), ...] Is there a way to show only one item? combo_test = forms.MultipleChoiceField( label=_("Combo test"), required=False, choices=choice_test(), widget= autocomplete.Select2Multiple(url='autocomplete_test') ) -
"This Field is Required" even though I am uploading my file
This is a follow up question to my last question: Lists are currently not supported in HTML Input . I have learned that Lists are simply not supported in Django-Rest-Framework browsable API, and I am trying to test my ability to POST data using Postman. The error I am getting is: "This Field is Required" for my BreedImages field even though I am posting it. Here are some pictures: Here are my models: class Breed(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BreedImage(models.Model): breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE) breedImage = models.ImageField(upload_to='photos', null=True, blank=True) My Serializers: class ImageSerializer(serializers.ModelSerializer): class Meta: model = BreedImage fields = ['id', 'breedImage'] class BreedSerializer(serializers.ModelSerializer): BreedImages = ImageSerializer(many=True, allow_null=True, required=True) class Meta: model = Breed fields = ['name', 'BreedImages'] My view: class BreedList(generics.ListCreateAPIView): parser_classes = (MultiPartParser,) queryset = Breed.objects.all() serializer_class = BreedSerializer pagination_class = None -
Process Text Files with Python Dictionaries and Upload to Running Web Service lab
I want to write a Python script that will upload the feedback automatically without having to turn it into a dictionary. The script should now follow the structure: List all .txt files under /data/feedback directory that contains the actual feedback to be displayed on the company's website. Hint: Use os.listdir() method for this, which returns a list of all files and directories in the specified path. You should now have a list that contains all of the feedback files from the path /data/feedback. Traverse over each file and, from the contents of these text files, create a dictionary by keeping title, name, date, and feedback as keys for the content value, respectively. Now, you need to have a dictionary with keys and their respective values (content from feedback files). This will be uploaded through the Django REST API. Use the Python requests module to post the dictionary to the company's website. Use the request.post() method to make a POST request to http:///feedback. Replace with 35.193.233.100. Make sure an error message isn't returned. You can print the status_code and text of the response objects to check out what's going on. You can also use the response status_code 201 for created success … -
Can i serve media files on production server in Django?
Actually I created a fully functional web app using Django. I don't have much experience to host a Django web app on a production server. But I'm trying. My problem is that I read from a blog that we can't serve media files using Django. We need Amazon S3 server to serve media files to Django. I'm trying to host my Django app on digital ocean with apache server. Is there any way that I can serve media files using Django in production server. Even I don't have a huge budget to buy a space on Amazon S3. What should I do? -
How to add example in swagger field
I am currently using following libraries of django - Django==2.2.4 django-pdb==0.6.2 django-rest-swagger==2.2.0 django-service-objects==0.5.0 django-timezone-field==3.0 django-windows-tools==0.2.1 djangorestframework==3.10.2 djongo==1.2.33 It is running on Python version 3.7.4 The problem that I am facing is I can able to generate body part of API using corapi.Field in Autoschema. class SwaggerSchemaView(APIView): permission_classes = [AllowAny] renderer_classes = [ renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer ] def get(self, request): generator = SchemaGenerator() schema = generator.get_schema(request=request) return Response(schema) class ParseResume(APIView): permission_classes = [AllowAny] schema = AutoSchema( manual_fields=[ coreapi.Field( "data", required=True, location="body", description='Send Json Data', type="string", schema=coreschema.Object(), ) ] ) def post(self, request): data = request.data response_data = SetConnections.parse_resume(data) return Response(response_data) Now, I can able to generate Swagger view like as follows - enter image description here But I want to add a sample data inside this body part through coreapi.Field like as follows - { "id": "56-df-pt", "fname": "John", "lname": "Doe", "experience": { "employee": "Company X", "period": "1996 - 2002", "engaged_in": [ { "work": "Jr. Manager", "team_size": 5, "time": "Sep. 1996 - Dec. 1998" }, { "work": "Sr. Manager", "team_size": 5, "time": "Jan. 1999 - Dec. 2002" }, ] } How can I add that? I can't change any version of Django or Python at this moment now. -
How Images can be added to HTML in Django, As i tried by static folder but still not getting image on html page
STATIC_URL = '/static/' {% load static %} Why this is not working in my case ... ? -
How do I know if and where my google cloud clogs are getting written
I have added a google-cloud-logging handler to the LOGGING settings of my django app and added it as a handler for my apps logger as below: from google.cloud import logging as google_cloud_logging gcloud_log_client = google_cloud_logging.Client() LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}, "require_debug_true": {"()": "django.utils.log.RequireDebugTrue"}, }, "formatters": { "console": {"format": "%(name)-12s %(levelname)-8s %(message)s"}, "file": {"format": "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"}, }, "handlers": { "console": {"class": "logging.StreamHandler", "formatter": "console"}, "apps_log_file": { "level": "DEBUG", "class": "logging.FileHandler", "formatter": "file", "filename": "/tmp/apps_logfile.txt", }, "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, "gcloud_log": { "level": "INFO", "class": "google.cloud.logging.handlers.CloudLoggingHandler", "client": gcloud_log_client, }, }, # "root": {"handlers": ["console"], "level": "WARNING"}, "loggers": { "apps": { "level": "DEBUG", "handlers": ["console", "apps_log_file", "mail_admins", "gcloud_log"], } }, } When I run this django app locally, the logs from apps logger are getting written to console and to the file as expected. Similarly, when I run this on GAE, I can see the logs on stdout logs. But I am not able to find the logs associated with gcloud_log handler. The stdout logs are not labeled by severity, so I am looking to log as separate google cloud log. The documentation for the google.cloud.logging is not at … -
Get all value selected from bootstrap selectpicker multiselect
Using bootstrap selectpicker for selecting multiple options but when I fetch it using post method I get only the last value selected. However the selected values are displayed properly in the select box. I am using Django framework and when I fetch value using request.POST['selection'] it returns only the last value selected. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script> <select class="selectpicker" name="selection" multiple data-live-search="true"> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </select> -
Django, queryset to find count in manytomany field
I have below model, class Blog(models.Model): name = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=200) class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) head = models.CharField(max_length=255) authors = models.ManyToManyField(Author) How do I find authors count ? Let us say I have an Entry object as Entryobject (Entryobject = Entry.objects.filter(blog__name='a') ), I tried as below but got attribute error. Entryobject.authors.count() # got error here Also please let me know how can I query list of authors in Entryobject . -
Unable Force Download File in Django HttpResponse (HTML/ PDF)
I am trying to output HTML or PDF files for download. I have written few lines of code to generate html & PDF file from a template and download it. However, my code is working for Chrome browser only. When I try to download it from other browser (e.g. DuckDuckGo) I am getting my current page (i.e. roll.html) downloaded instead of the file (i.e. file rendered from html_output_template.html) which I want to export. Here's the code I am trying: views.py def generate_html(request, res): cdict = {'res':res, 'date':datetime.date.today()} if request.method == 'POST': inv_form = InvoiceInfoForm(data= request.POST) if inv_form.is_valid(): inv_data = inv_form.cleaned_data cdict = {'res':res, 'inv_data':inv_data, 'date':datetime.datetime.today().strftime("%d %h %Y")} template = get_template('app_name/html_output_template.html') html = template.render(cdict) response = HttpResponse(html, content_type='application/force-download') filename = "Inv_%s.html" %(datetime.datetime.today().strftime("%d_%h_%y_%H_%M_%S")) content = "attachment; filename= %s" %(filename) response['Content-Disposition'] = content return response def MyView(request): """Some Calculations Here""" if 'download_pdf' in request.POST: if inv_form.is_valid(): return generate_pdf(request, res) elif 'download_html' in request.POST: if inv_form.is_valid(): return generate_html(request, res) return render(request,'app_name/roll.html',context=cdict) Sample of html template: html_output_template.html {% load staticfiles %} <!-- Few Lines here --> <tr> <td style="text-align:left">1</td> <td style="text-align:left">{{inv_data.description}}</td> <td style="text-align:right">{{res.rate_per_gram}} {{res.rate_kilo_gram}}</td> <td style="text-align:right">{{res.wgt_of_goods}}</td> <td style="text-align:right">{{res.total_amount}}</td> </tr> I feel there is some problem with my HttpResponse which is getting auto corrected in Chrome … -
Avoid making multiple Django database calls
I would like to query my Django database once and return a Queryset (assigned the name 'codes'), which I can iterate over to obtain each instance's 'internal_code' attribute without making further calls to the database. Here is my code, but I am unsure as to whether I am querying the database each time I use 'get' on the Queryset, and how I can avoid this: codes = models.RecordType.objects.all() permanent = sorted( [(codes.get(industry_code=category.value).internal_code, self.labels.get(category, category.name)) for category in enums.Category]) -
Render the key value of a dictionary based on an event in Django
I have two dropdowns in my .html file of Django app namely: <select class="form-control" id="exampleFormControlSelect1"> <option>op1</option> </select> <select class="form-control" id="exampleFormControlSelect2"> <option>opt1</option> </select> A dictionary is rendered from the Django views.py.I want the keys to be displayed as options in the first dropdown and whenever a key is selected,the corresponding values need to be displayed in the second dropdown.I tried some js and jina Template but no luck.How can I implement it? -
Filter model object by difference in days
My model has a date field and i want to filter the model by the last 7 days. class Count(models.Model): task = models.ForeignKey(Task, related_name = 'counts', on_delete = models.CASCADE) start_time = models.DateTimeField(null = True, blank = True) end_time = models.DateTimeField(null = True, blank = True) time_spent = models.PositiveIntegerField() deleted = models.BooleanField(default = False) class Meta(): ordering = ['accesses'] def __str__(self): return f'{self.task.department} - {self.accesses.first().user} [{self.time_spent} min]' def stamped_date(self): if not self.start_time: return self.accesses.first().date return self.start_time def users(self): return list(set(map(lambda x: x.user, list(self.accesses.all())))) I need to filter every count that has "stamped_date" in the last 7 days. What i tried to do (in the model): def daysBy(self): return (datetime.now() - self.stamped_date()).days to filter like this: Count.objects.filter(daysBy__let = 7) However, datetime.now() requires a timezone object, otherwise will throw the follwing error: TypeError: can't subtract offset-naive and offset-aware datetimes I'm also feeling this might not be the most correct way of achieving my goal, please correct me with a better way. Or.. give me a way of inserting a timezone object related to the TIME_ZONE setting. -
Static files are not fetching in django
My settings description. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/css') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Also, I had added static files to urls.py urlpatterns += staticfiles_urlpatterns() My HTML template {% load static %} <!DOCTYPE html> <head> <meta charset="utf-8"> <title>Things I eat</title> </head> <body> <h1> Hello world</h1> </body> findstatic command output: > python manage.py findstatic styles.css Found 'styles.css' here: /project_name/static/css/styles.css I use django == 3.0.7 I followed advice from similar questions [1,2,3] But my static files are not fetching while rendering. Any advice for debugging? -
CORS-Error when using django as backend for ionic app
I'm using Django Rest Framework as a backend for my Ionic app. I set up the API with JWT and with postman everything works fine. As soon as I try making a API call from my Ionic app I get the following error messages: Error 1 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mywebsite.com/api/movies. (Reason: header ‘password’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). Error 2 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mywebsite.com/api/movies. (Reason: CORS request did not succeed). I run my django app on a apache2 webserver. django-cors-headers is installed, added to installed_apps, added to the middleware and CORS_ORIGIN_ALLOW_ALL = False In my Ionic app the request looks like this: Service fetchMovies() { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.authService.getToken()}`, 'username': 'USERNAME', 'password': 'PASSWORD' }) } return this.http.get(this.url, httpOptions).pipe(tap(resData => { console.log(resData); })); } I get the token like this: getToken() { return this.http.post('https://www.mywebsite.com/api-token', this.params); } And I use the service as follows: ionViewWillEnter() { this.moviesServcie.fetchMovies().subscribe(); } Does anyone have an idea what I'm doing wrong? If you need more information feel free to write a comment! … -
How to access variables class in a child function in Python/Django
Like I said in title I'm trying to access variables class in a child function. In the class I import Json data from a file and I convert them in dict then in variables so far no worries. but I can't access my variables in JsonForm function below to render them in the Form, I've tried many solution with init and self but any works there is my code : class UpdateSwitch: # folder location of my Json data CWD = os.getcwd() JSON_CONFIG_FILE_PATH = '%s/%s' % (CWD, 'mod_switch/EmailDataScript/mailData.json') # I store the data in this viariable CONFIG_PROPRETIES = {} # data are loaded and converted to a dict try: with open(JSON_CONFIG_FILE_PATH) as data_file: CONFIG_PROPRETIES = json.load(data_file) except IOError as e: print (e) print ('IOError: Unable to open mailData.json') exit(1) print (CONFIG_PROPRETIES) # OUTPUT something like this : {'data': 'somedata', 'data2': 'somedata2', 'data3':'somedata3', 'data4': 'somedata4', 'data5': 'somedata5', 'data6': 'somedata6'} # Convert the dict keys to variables and dict values to value of these variables for key,val in CONFIG_PROPRETIES.items(): exec(key + '=val') # And there is what I get(everything work) : data, data1, data2, data3, data4, data5, data6 def JsonForm(request): if request.method == "POST": stackForm = JsonStacksForm() stackForm.Meta.fields = { "ip" : …