Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issues with django rest framework using dynamic serializer
I'm have a dynamic dataset I am trying to use with the Django REST Framework by dynamically creating serializer, but it doesn't seem to process the dynamic attributes I add. Here is the code: -- views.py class DynamicReadings(generics.ListAPIView): def get_serializer_class(self): site = self.kwargs['site'] devices = Device.objects.filter(reader__site__slug=site).order_by('code') dyn_fields = ['x%s' % a.code for a in devices] return SerializerClassFactory(dyn_fields) def get_queryset(self): ... # the query is correct and returns data -- serializers.py def SerializerClassFactory(dyn_fields): class DynamicSerializer(serializers.Serializer): read_at = serializers.DateTimeField() class Meta: fields = ('read_at') for f in dyn_fields: setattr(DynamicSerializer, f, serializers.FloatField()) DynamicSerializer.Meta.fields += ','.join("'%s'" % f for f in dyn_fields) return DynamicSerializer When I execute the code, only the attribute (read_at) specified in the class definition is serialized. None of the dynamic attributes appear to be working. Example: [{"read_at":"2017-05-07T00:12:29Z"},{"read_at":"2017-05-08T00:12:30Z"}] Here is the output of the class after creation in shell: >>> serializer = SerializerClassFactory(['x01', 'x02', 'x03']) >>> serializer.__dict__ mappingproxy({'__module__': 'biomark.api.serializers', 'Meta': <class 'xxx.api.serializers.SerializerClassFactory.<locals>.DynamicSerializer.Meta'>, 'x02': FloatField(), '_declared_fields': OrderedDict([('read_at', DateTimeField())]), '__doc__': None, 'x01': FloatField(), 'x03': FloatField()}) Additionally, I've tried: setattr(DynamicSerializer, f, property(serializers.FloatField())) setattr(DynamicSerializer, f, type(serializers.FloatField())) I'm not sure what I am doing wrong. -
MEDIA_URL didn't work Djnago (development)
py** STATIC_URL = '/templates/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "templates"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL = '/media/' in my models.py files uploade to main_image = models.FileField(upload_to='photos/', blank=True, null=True) in html <img src="{{ MEDIA_URL }}{{ item.main_image.url }}" alt=""> but the images isn't rendering -
Make ModelChoiceField as dropdown to display title and image together using Django
I have forms like this. I just wanna display thumb and title together as dropdown not as a radio button. it makes my form as radio. what's my wrong, i can't figured out this. If i change widget=forms.Select(), it creates dropdown with only title but doesn't display thumb besides title. thanks. class CustomChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe("<img src='https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150'><p>"+str(obj.category)+"</p>") countries_list = ImageModel.objects.all() class SubCatForm(forms.Form): category_pic = CustomChoiceField(widget=forms.RadioSelect(), queryset=countries_list, empty_label=None) class Meta: model = SubCatModel fields = ("sub_category_name", "category", "category_pic") widgets = { 'sub_category_name': forms.TextInput(attrs={'class':'span11'}) } -
page not found is showing (django)
My homepage is login page.So first it will goto the home function and if not logged in it will goto login_user function then after logging in it will redirected to home.But page not found is showing.Here is my code. Filename: views.py def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/') else: return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'retest/login.html', {'error_message': 'Invalid login'}) return render(request, 'retest/login.html') @login_required def home(request): user = request.user if user.groups.filter(name='hod').exists(): return render(request, 'retest/hod.html', {}) elif user.groups.filter(name='principal').exists(): return render(request, 'retest/principal.html', {}) elif user.groups.filter(name='Rep').exists(): return render(request, 'retest/home.html', {}) elif user.groups.filter(name='Ajithzen').exists(): return render(request, 'event/ajithzen.html', {}) elif user.groups.filter(name='graphics').exists(): return render(request, 'event/ashok.html', {}) elif user.groups.filter(name='Event_incharge').exists(): return render(request, 'event/chair.html', {}) elif user.groups.filter(name='IEEE').exists(): return render(request, 'event/ieee.html', {}) else: return redirect('/login') Filename: urls.py url(r'login^$', views.login_user, name='login_user'), url(r'^$', views.home, name='home'), -
Get all related field in Django model
I am struggling to understand how one-to-many and many-to-many relation works in Django model. My schema looks something like this so far, I am open for suggestions to make it better. A many-to-many relation between users and team. Also, there will be schedules that belong to a particular user of a team. This is how my model looks like so far, class Team(models.Model): tid = models.AutoField(primary_key=True) team_name = models.CharField(max_length=30) manager_name = models.CharField(max_length=30) class Schedule(models.Model): sid = models.AutoField(primary_key=True) user = models.OneToOneField(User) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() pay_rate = models.CharField(max_length=30) location = models.CharField(max_length=50) class BelongsTo(models.Model): bid = models.AutoField(primary_key=True) user = models.OneToOneField(User) team = models.ForeignKey(Team, on_delete=models.CASCADE) schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) Question: I want to get the information of each user, what are their schedules and which team each schedule belongs to. What would be the best way to do it? Note: I am open for suggestions, if something is wrong with my schema or model or the approach, please let me know. -
TweepError at /hashtag/
Error Message: TweepError at /hashtag/ Failed to send request: HTTPSConnectionPool (host='api.twitter.com',port=443):3 Max retries exceeded with url: /1.1/search /tweets.json?q=%23trump&rpp=2 (Caused by NewConnectionError ('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x04EEF050>: Failed to establish a new connection: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',)) and sometimes i'm getting this error: ConnectionError at /hashtag/ HTTPSConnectionPool(host='gateway.watsonplatform.net', port=443): Max retries exceeded with url: /natural-language-classifier/api/v1/classifiers/90e7b7x198-nlc-50734/classify (Caused by NewConnectionError('<requests.packages.urllib3.connection. VerifiedHTTPSConnection object at 0x04F281B0>: Failed to establish a new connection: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',)) Before that, i was getting the tweets and results as expected but now i'm getting this error. By the way, I'm not running any VPN. Here is the code: def hashtag(request): if request.method == "POST": form_hashtag = HashtagForm(request.POST or None) instance = form_hashtag.save(commit = False) instance.save() if instance.hashtag == "": instance.hashtag = "#trump" print instance.hashtag search_number = 2 search_result = api.search(instance.hashtag, rpp=search_number) count = 0 nhate =0 terrorism=0 hate=0 result = [] tweets =[] for i in search_result: if … -
Django send Javascript file to client sent AJAX request
Let's say client side Javascript needs a specific file, all this file has is a Javascript Object, but it has functions/getters/setters so it can't be passed as JSON. So it makes an AJAX request to the django server, specifying the file/object it needs. How do I send this file/object? What format do what send it in? How do I interpret the received file/object in the Javascript client? I'm guessing eval isn't the best way -
Upgrading to Django 1.7. Import Error: No module named dashboard
I was upgrading from Django 1.6 to 1.7. Python 2.7 is installed which is compatible with Django 1.7. While I was deprecating with the code "python -Wall manage.py test", I got the following error message: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist- packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 123, in create import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named dashboard Reading the Django 1.7 release note, I understood "django.utils.module_loading.import_by_path" has been changed to "import_string()". I couldn't figure out where can I find this piece of code. If anyone can give me a guideline how to deal with this issue would be appreciated. -
Django - Select Which Forms Will Be Active in Django Models
i have a model which named ClassRoom in my django models.py and i write some ModelForms based on another models (which considered just for forms). based on classes entries on ClassRoom , i want to active and deactivate forms for students. how can i choose which forms will be active for students if they are joined to those classes? in other language consider i have 4 forms named 'form a' , 'form b' ,'form c' , 'form d' , and i add some classes in my ClassRoom table such as 'class 1' , 'class 2' , 'class 3' and 'class 4' , normally i added students into the class (by another model such as Students which have a foreignKey to ClassRoom) i want to active 'form a' and 'form b' for Students who belongs to 'Classb' and something like that. how can i choose wich forms will be available for ClassRoom ? is there any way ? -
django templates for one row 4 objects
I send to my django template page.html 12 objects with different heights. I want display them per one .row 4 object. In python terminal I can do this. I need alternative for template if a % b == 0: print('</div> <div class="row" ') else: print('<div class="item">') I couldn't use forloop.counter result must be like this a b d f b f d k d k a b -
How to get a form to pop-up using Jquery/Ajax in Django?
I have a button on a webpage that I would like to have a form pop up when clicked. The problem is, I have no idea how to pass information for html with ajax. I can successfully pass database information with ajax like so: View: def ajax_shipping(request): id_quote = request.GET.get('quote', None) quote = HomeTable.objects.filter(id=id_quote).values_list('quote_num_id', flat=True) items = ItemDetails.objects.filter(quote_num_id=quote).values_list('item', 'quan', 'shipped') detail_list = [] for x in items: detail_list.append(x) data = { 'item': detail_list } return JsonResponse(data) JQuery and Ajax: $("#id_iden").on('change', function(){ if ($(this).val() !== ""){ var qn = $(this).val() $.ajax({ url: "/ship/ajax-shipping/", data: { 'quote': qn }, dataType: 'json', success: function(data){ if (data.item[0]){ $('#id_item1').val(data.item[0][0]) $('#id_quan1').val(data.item[0][1]) $('#id_ship1').val(data.item[0][2]) var bo = (data.item[0][1]) - (data.item[0][2]) $('#id_bo1').val(bo) } } }) } }) However, I have no idea how to send form and html information while making it popup. I am looking for a tutorial or some guidance so I can achieve this. Thanks. -
Move Django DB data from one DB to another
As part of my development process, I'm creating multipule objects in the DB that has a foreign key to another object in the DB. For example: I created "object 1", "object 2", and "object 3" (that are new the DB) and they all have a foreign key to "object A" (that exists in all DB's). Now, I would like to 'move' all the new objects from one environment to another. I know that one option is to use: Fixtures but it looks like this can cause some issues: Can I use it to export and import just a single object and not an entire app? How do I prevent duplicate keys? How do I compare objects before making any change in order to avoid overwriting changes that were made to "object A" in the DB that I'm trying to import the data to? -
Django Redirect With Using Ajax
I have one app name register_login and this app manages login and register opeartions. I have a form on localhost:8000/login page and i want that the button redirects to my func in register_login app but i cant do it. I'm new at Django Framework. How can i handle this? MAIN URLS.PY from django.conf.urls import include,url from django.contrib import admin from register_login.views import login, register, test urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^homepage/', include('homepage.urls')), url(r'^login/$', login), url(r'^register/$', register), url(r'^success/$', test), ] LOGIN PAGE .HTML <form id=registerLogin style="margin-top: 30px; margin-left: 350px;"> <header>Login</header> <label >Username <span>*</span></label> <input id="username"/> <label >Password <span>*</span></label> <input id="password"/> <button id="login">Login</button> <h1 style="margin-left: 20px;">Are you not registered?</h1> <button id="register">Register</button> </form> At the end of this html there is my .js file. I didnt forget. JAVASCRIPT if (!jQuery) { throw new Error("This page requires jQuery") } function readInput() { e.preventDefault(); var userName = document.getElementById('username').value; var password = document.getElementById('password').value; debugger $.ajax({ type: "POST", url: "/success/", data: {'username':username,'password':password, csrfmiddlewaretoken: '{{ csrf_token }}'}, dataType: 'json', success : function(json) { $('#post-text').val(''); // remove the value from the input console.log(json); // log the returned json to the console console.log("success"); // another sanity check }, }); } (function ($) { $("#login").click(function(){ readInput(); }); })(jQuery); And finally my … -
django rest swagger not detecting path variables properly by method
I am using APIView for an api and during the swagger doc generation it is not detecting the proper path variables for each method type. Here are my urls: url(r'^org/$', OrgView.as_view(), name='org_api'), url(r'^org/(?P<org_id>\w+)/$', OrgView.as_view(), name='org_api'), Here is my view: class OrgView(ApiView): """ Org API """ def get(self, request, org_id=None): if org_id: ... ... def put(self, request, org_id): ... def post(self, request): ... def delete(self, request, org_id): ... Notice that get has an optional parameter org_id which is accounted for in the two different urls. Swagger documentation accounts for this and documents two different get methods, one with org_id and another without. My problem is with my post method, it has no option for an org_id (because the id will not even have been created until after the post) yet django-rest-swagger does not recognize this and only includes the post method for the second url, forcing the user to provide one org_id in order to 'Try it out!'. I started to do some things to mess with the coreapi.Fields being generated and I have eliminated the problem with the field being required, but it feels kind of hacky and I would like to avoid it, it also still shows the path … -
how to collect admin templates file in django
I just created a STATIC_ROOT and collected all the static files, like css, js, fonts. etc. But I need to see some django admin templates as well and I would like to collect them into a folder. Is there anyway to do that? I would appreciate it. -
Trouble with Carousel images in Wagtail
I'm relatively new to Django and a complete beginner in Wagtail. The website I am building only has one carousel and it is on the homepage. I have created the following two models in models.py: class CarouselItem(Orderable): image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) caption = models.CharField(max_length=255, blank=True) page = ParentalKey('HomePage', related_name='carousel_items') panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] class HomePage(Page): nila_intro = RichTextField(blank=True) content_panels = Page.content_panels + [ InlinePanel('carousel_items', label="Carousel Items"), FieldPanel('nila_intro', classname="full"), ] class Meta: verbose_name = "Homepage" In order to get the template tags right I referred to the Wagtail Demo site on Github to try and replicate what has already been done. Basic operations such as {% if page.carousel_items %}, {% for carousel_item in page.carousel_items.all %} and {{ carousel_item.caption }} work just fine. Also in the admin everything is exactly as I intended. I am however having issues getting the images and/or image src url's to show. I have tried both adding the following to the src and nothing happened: {{ carousel_item.image.url }} and then I tried removing the <img> tag altogether and doing a {% image carousel_item.image alt="Slide Image" %} it gave me an error. So I'm not really sure what to do! I … -
Django migrations on MySQL and Waiting for table metadata lock
I'm using Django 1.11 and I have a migration that creates a boolean field. I run this on development environment and it's successful. But when run migrate command on production environment it's keep a long time. In MySQL I can see that table is on status Waiting for table metadata lock. I think this trouble is caused for somes active querys while trying to add field on table. I tried to kill the processes of those querys, but as it's in production, other querys for that table arrive. -
django framwork,i dont konw how to deploy the project about blog demo,who can help me?
i need some help , i am greenhand。i hope you can help me,there is console on under picture enter image description here this is me first use python, the project is django demo from github,i dont know where modify database username and database password,this is my first use sqlite3,i feel this problem about database. this is github link:https://github.com/MoreYoungGavin/my_blog thank you very much in advance. -
Bootstrap Popover not responding to click event
I can see in the console that my data is populating within the popover but it's not responding to my click events at all and it's a bit maddening. Here's a snibbet of the function containing the popover: $(function(){ $(".run-btn").click(populateSteps); $(".run-all-suite").click(getId); $(".run-all-btn").click(runAll); $('[data-toggle="popover"]').popover(); }); var table_draw = '<table class="table table-bordered"><tr><th>Title</th><th>Status</th><th>Holly</th><th>Call ID & TestRail ID</th><th>Failure reason</th></tr>'; $.each(cases.cases, function (index, value) { var popupControl = "<button type='button' class='btn btn-default' data-container='body' data-toggle='popover' data-content='" + value.script + "' data-original-title='' title=''></button>"; table_draw += "<tr><td class='title col-xs-2'>" + value.title + popupControl +"</td>" + "<td class='status col-xs-1'><i class='fa fa-spin fa-spinner'></i><span> Running...</span></td>" + "<td class='holly col-xs-1'>" + cases.holly + "</td>" + "<td class='call-id col-xs-1'></td>" + "<td class='reason col-xs-2'></td></tr>"; $('body').on('click', function (e) { $('[data-toggle="popover"]').each(function () { if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) { $(this).popover('hide'); } }); }); }); Console output: Order of my reference files: <!-- Load Bootstrap JS source for popover --> <script src="{% static 'common/jquery/1.10.2/jquery.min.js' %}"></script> <script src="{% static 'common/tooltip/tether.min.js' %}"></script> <script src="{% static 'common/bootstrap/3.3.5/dist/js/bootstrap.min.js' %}"></script> This is a Django project. The popover is in a JS file which is referenced on the page of which it displays which is dashboard.html: <script> {% include 'runner/dashboard.js' %} </script> The base.html file holds the above … -
Is it safe to bypass login on development environment?
I am developing a site in django and need to login with different user profiles to test it. Currently I set the password of all users on my database to a string that django decrypt and interpret as "1234". To avoid that, I wrapped the default login in the function below. Is it safe to have this code on production? def login(request, redirect_field_name=REDIRECT_FIELD_NAME, *args, **kwargs): from django.contrib.auth.views import login as django_login from django.contrib.auth import login as auth_login if settings.DEBUG: redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if request.method == "POST": user = request.POST.get('username', '') user = Usuario.objects.filter(cpf=user) if user.exists: user = user.first() user.backend = 'django.contrib.auth.backends.ModelBackend' auth_login(request, user) return HttpResponseRedirect(redirect_to) return django_login(request, *args, **kwargs) -
django redirect to to second option from drop down menu
Currently I have urls.py which defined like below url(r'^$', BaseView.as_view(), name='base'), url(r'^option2/$', Option2.as_view(), name='option2'), So when I load localhost it goes to class BaseView(View): def get(self, request): return render(request, 'option1.html') And when I select option from dropdown menu option2 it goes to option2 view with url localhost/option2 and after clicking on option1 it goes back to url localhost which displays option1.html But when I load page first load can I redirect to go to localhost/option2 which is equivalent to selecting option2 on from page dropdown on page load. -
ldapdb: "'NoneType' object is not callable" when adding ldap database to django
Running django 1.11 and trying to connect to LDAP server by using django module ldapdb (django-ldapdb==0.8.0): DATABASES = { 'ldap': { 'ENGINE': 'ldapdb.backends.ldap', 'NAME': 'ldap://192.168.1.39/', }, 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'prot', # Or path to database file if using sqlite3. 'USER': 'prot', # Not used with sqlite3. 'PASSWORD': 'geheim', # Not used with sqlite3. 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '5432', # Set to empty string for default. Not used with sqlite3. }, } DATABASE_ROUTERS = ['ldapdb.router.Router'] However I get an error in the ldapdb code. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f4ba61ff840> Traceback (most recent call last): File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models errors.extend(model.check(**kwargs)) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/db/models/base.py", line 1284, in check errors.extend(cls._check_long_column_names()) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/db/models/base.py", line 1699, in _check_long_column_names connection = connections[db] File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/db/utils.py", line 212, in __getitem__ conn = backend.DatabaseWrapper(db, alias) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/ldapdb/backends/ldap/base.py", line 187, in __init__ super(DatabaseWrapper, self).__init__(*args, **kwargs) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/db/backends/base/base.py", … -
Django: register template filter / tag per instance
I'm using Django Template low-level libraries to parse some strings like this: [..] from django.template import Template, Context options = Template('''{{% autoescape off %}}{0}{{% endautoescape %}}'''.format(options)).render(Context(self.context)) [..] So, if I have a template instance like this: template = Template('''{{% my_custom_tag %}} ''') how can i programmatically register my_custom_tag as a simple_tag (django.template.Library.simple_tag()) in my execution context? I know you can register it globally with django.template.Library(), but I only want this tag (or a filter) in this context. Thanks -
Wagtail: Pre-populate InlinePanel
I have a combination of two page models ParentPage and ChildPage which both contain a Parentalkey to the same Orderable: # The Orderable class AbstractSnippetLink( Orderable ): # Here are some ForeignKeys to Snippets not important here # Some extension to the mere snippet status = models.CharField( max_length = 32, default = 'available' ) class Meta: abstract = True # The Page models: class MyParentPage( Page ): subpage_types = [ 'myapp.MyChildPage' ] # some definitions class MyChildPage( Page ): parent_page_types = [ 'myapp.MyParentPage' ] base_form_class = MyParentPageAdminForm # see below # Other definitions # Orderable for ParentPage model: class ParentPageSnippetLink( AbstractSnippetLink ): page = ParentalKey( 'myapp.MyParentPage', related_name= 'linked_snippet', on_delete = models.SET_NULL, null = True ) # Orderable for ChildPage model: class ChildPageSnippetLink( AbstractSnippetLink ): page = ParentalKey( 'myapp.MyChildPage', related_name= 'linked_snippet', on_delete = models.SET_NULL, null = True ) I would like the related_snippets from MyParentPage be the default value when creating a new MyChildPage as a child of MyParentPage. I have implemented my own form for editing MyChildPage: class MyParentpageForm( WagtailAdminPageForm ): def __init__( self, data = None, files = None, parent_page = None, *args, **kwargs ): # get the data from MyParentPage super( MyParentpageForm, self ).__init__( data = data, files … -
How to make a function run along with my views
I have this function, I want it to be working with my view, how could I do it ? Def PlaySound(self): while(True): if GPIO.input(Snare) == False: os.system("path/to/the/sound") return ("Is activated") Def view(request): return render(request, "page.html")