Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: form is valid but is not save because no module named app is found
I'm developing a simple form to upload files. I see that my form is valid because some print statments I've made, however I'm getting an error when saving the form. ModuleNotFoundError at /admineditorial/predica/add/ No module named 'app' And: Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 965 I don't think it has to do something with Bootstrap. I don't know what could be happening. models.py: class Predica(models.Model): audio_file = models.FileField(upload_to = u'audio/', max_length=200) **views.py:** # Create your views here. def predica_upload(request): predicas = Predica.objects.all() if request.method == 'POST': form = PredicaUpload(request.POST, request.FILES) if form.is_valid(): print("### Form is valid ###") form.save() print("Despues del save") print(form) return redirect('today_editorial') else: print("### Form not valid ###") print(form.errors) else: form = PredicaUpload() return render(request, 'predicas/predicas.html', {'form': form, 'predicas': predicas}) urls.py: from django.urls import path from editorial import views from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin', admin.site.urls), path("", views.today_editorial, name="today_editorial"), path('predicas',views.predica_upload, name = 'predica_upload') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) predicas.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Subir</button> </form> {% for predica in predicas %} <div> <img src="{{predica.audio_file.url}}" alt="myvideo"> </div> <p>No audios in my gallery yet :-(</p> {% endfor %} settings.py: """ Django … -
Is it possible to include a ForeignKey inside a JSONField schema? How else can I effect this?
I am building an app in Django that allows users to build their own forms and in effect customise dynamic models. After much research, I've decided to effect this through Django, PostgreSQL and JSONFields where one model holds the schema and another holds the record data: class = Template(models.Model): schema = JSONField(null=True) # Schema for the form/model class = DynamicModel(models.Model): data = JSONField(null=True) # Corresponding data for the form/model template = models.ForeignKey(Template, null=True, blank=False, on_delete=models.SET_NULL) This means users can define their own model templates and I can hold different records using that template in another model. The idea is to parse the template.schema JSONField to display editable forms using jQuery and to store the output as dynamicmodel.data JSONField. Validations are passed on the client side. However, this comes with the drawback if I want to allow users to include ForeignKey lookups in their models. For example, say they wanted to add a choice box that offered selections from different customer.ids in a Customer(models.Model) class. Without hardcoding the ForeignKey directly into the DynamicModel class (which would defeat the point of the exercise) can you think of a way I can achieve this? -
How to get objects from one model to other using ForeignKey in Django
I want to link models with there ids, I am having trouble in getting objects of foreignkey linked with id and creating queryset, I am new to Django I have searched alot about my problem but not getting answer. models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=False) def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name', 'phone', 'address', 'Patient_id', 'consultant', 'Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','date_of_admission'] views.py: @login_required def ipd (request,patient_id): p = Patient.objects.get(pk=patient_id) if request.method=="POST": formtwo = IpdForm(request.POST,instance=p) if formtwo.is_valid() : formtwo.user_id = request.user.id if formtwo.save(): return HttpResponseRedirect('ipd_list.html', messages.success(request, 'Patient is successfully updated.', 'alert- success')) else: return render('ipd_list.html', messages.error(request, 'Data is not saved', 'alert-danger')) else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'p':p ,'form2':formtwo}) html : <div class="card-panel"> <span class="blue-text text-darken-2">Name : {{p.name}}</span> <br> <span class="blue-text text-darken-2">Phone : {{ p.phone }}</span><br> </div> I am having problem with queryset that allows me to use object … -
How can I fix 'ModelForm has no model class specified.'
I am getting the ModelForm has no model class specified. error when trying to use the ModelForm I can't see where the error is coming from. To the best of my knowledge, I have reference the model which I am using properly. Please see my code below: forms.py from django import forms from .models import BlogPost class BlogPostForm(forms.Form): title = forms.CharField() slug = forms.SlugField() content = forms.CharField(widget=forms.Textarea) class BlogPostModelForm(forms.ModelForm): class meta: model = BlogPost fields = ['title', 'slug', 'content'] views.py def blog_post_create_view(request): form = BlogPostModelForm(request.POST or None) if form.is_valid(): form.save() form = BlogPostModelForm() context = {'form': form} template_name = "form.html" return render(request, template_name, context) -
The current path, index, didn't match any of these. http://127.0.0.1:8001/index
I setup webpage via cmd for Django.However, i had problem when accessing index page of 127.0.0.1:8001. I tried to update urls.py but still have problem. Browser page error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8001/index Using the URLconf defined in barry.urls, Django tried these URL patterns, in this order: admin/ The current path, index, didn't match any of these. urls.py file: """{{ project_name }} URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/{{ docs_version }}/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.conf.urls import url from sign import views urlpatterns = [ path(r'^admin/', admin.site.urls), path(r'^'index/$', views.index.urls), ] -
Indexing product list takes way too long with Django, Haystack and Whoosh
I'm experiencing issues indexing a list of products (about 280k) with Haystack and Whoosh. It seems to take more than 28 hrs to run the update of the index. I don't think that's a reasonable time at all. I've got a model: class SupplierSkus(models.Model): sku = models.CharField(max_length=20) link = models.CharField(max_length=4096) price = models.FloatField() last_updated = models.DateTimeField("Date Updated", null=True, auto_now=True) status = models.ForeignKey(Status, on_delete=models.PROTECT, default=1) category = models.CharField(max_length=1024) family = models.CharField(max_length=20) family_desc = models.TextField(null=True) family_name = models.CharField(max_length=250) product_name = models.CharField(max_length=250) was_price = models.FloatField(null=True) vat_rate = models.FloatField(null=True) lead_from = models.IntegerField(null=True) lead_to = models.IntegerField(null=True) deliv_cost = models.FloatField(null=True) prod_desc = models.TextField(null=True) attributes = models.TextField(null=True) brand = models.TextField(null=True) mpn = models.CharField(max_length=50, null=True) ean = models.CharField(max_length=15, null=True) supplier = models.ForeignKey(Suppliers, on_delete=models.PROTECT) I got a search_indexes.py: from haystack import indexes from products.models import SupplierSkus class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) sku = indexes.CharField(model_attr='sku') category = indexes.CharField(model_attr='category') product_name = indexes.CharField(model_attr='product_name') family_name = indexes.CharField(model_attr='family_name') prod_desc = indexes.CharField(model_attr='prod_desc') family_desc = indexes.CharField(model_attr='family_desc') brand = indexes.CharField(model_attr='brand') mpn = indexes.CharField(model_attr='mpn') ean = indexes.CharField(model_attr='ean') attributes = indexes.CharField(model_attr='attributes') def get_model(self): return SupplierSkus def index_queryset(self, using=None): return SupplierSkus.objects.filter(status_id=1) I've noticed a massive performance decrease in the Django versions after 2 when it comes to iterating over a large QuerySet. I'm not sure why that is, … -
Django download link with relative path in template
I have a few download links and I want to use relative paths to the specific files in my template, so I don't need to adjust paths and the full path is not shown when inspecting that element. views: def home(request): template = loader.get_template('home/index.html') context = {'directory': settings.BASE_DIR} return HttpResponse(template.render(context, request)) def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/octet-stream") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 where BASE_DIR from settings.py is: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) urls.py: urlpatterns = [ path('download/<path>', views.download, name='download') ] Snippet from the template: <a href="{% url 'home:download' '{{ directory }}\files\Main.xaml' %}">Download</a> My question is how to properly paste {{ directory }} as a variable in the element as a argument to the download view. It's not working like shown above. -
What email backend should i use to make users send emails ? and how to specify email backends for cerrtain views?
I have an app where users can send feedbacks by filling form containing there basic info and in the same app (same web application no the same application) the app will send emails for confirming their emails when they sign up. the email backend i use for confirming their emails is smtp backend so what should i use for them sending emails and how can i specify it ? -
Pass parameter in string mongo query in python
I have following query in my database query = u'collection.aggregate([{ "$match": { "code": { "$in": {__sensors__}} } },{"$project" : {"_id" : 0}},{"$group" : {"_id": "$code", "data": {"$last": "$$ROOT"}}}])' And I have following arguments, Now I want to pass that argument in the above query. args = {"__sensors__": ["GP0", "GP1", "GP5", "GP6"]} I'm trying following but it is giving me an error. query.format(**args) above statement giving me this error --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-44-7db1aba33ea5> in <module>() ----> 1 a.query.format({"__sensors__": []}) KeyError: u' "$match"' Can anyone give me the solution for the above problem? -
Django paginator not responsive on last page
Iterating over a large QuerySet doesn't seem to be a viable option in Django 2.0 anymore. I've tried to speed it up using Django's own Paginator. def read_from_db_4(): paginator = Paginator(DataSet.objects.filter(status_id=1).order_by('id'), 1000) l = [] print("{} iterations!".format(paginator.num_pages)) for page in range(1, paginator.num_pages+1): l = l + list(paginator.page(page).object_list) print("{}, next page...".format(page)) return l This little function is reasonably quick but will stop on the very last page. I can also not get to the length of this page: len(paginator.page(LASTPAGE).object_list) this will just hang forever. I can get the length of all other pages previously. What's the reason for this odd behaviour? -
How to run a FOR loop on a JSONField in Django referring to specific elements
I have the following JSONField: class Flow(models.Model): flow_title = models.CharField(max_length=200, null=True) flow_data = JSONField(null=True) def __str__(self): return self.flow_title In the flow_data JSONField I have the following JSON: { "section1": { "section_title": "Untitled Section 1", "section_description": "Section description 1", "field1": { "field_name": "Untitled field 1", "field_type": "Text", "field_value": "This is text value 1" }, "field2": { "field_name": "Untitled field 2", "field_type": "Text", "field_value": "This is text value 2" } }, "section2": { "section_title": "Untitled Section 1", "section_description": "Section description 1", "field1": { "field_name": "Untitled field 1", "field_type": "Text", "field_value": "This is text value 1" }, "field2": { "field_name": "Untitled field 2", "field_type": "Text", "field_value": "This is text value 2" } } } Now, I know I can pass context in my views.py to create the required object: def index(request): flow_list = Flow.objects.all() return render(request, "index.html", {"flow_list": flow_list}) And that I can loop through all of my json objects in the template: {% for object in flow_list %} <li>{{ object.id }}>{{ object.flow_data }}</a></li> {% endfor %} However, if I want to format individual parts of the JSON in the loop like below, how would I do this? {% for object in flow_list %} <li>[nth Section]</li> <li><b>[nth Section Description]</b></li> <li>[First Field] - [Field … -
Authentication issue while proxying two django project on same ip
Proxying two Django projects behind Nginx. One is running on port 8000 and other 8001 and nginx is on 5555 and it is all on my same PC. Authentication is done through the port 8000 and it is database session store powered, the project on server 8001 uses the same database. Now, If I login from the main project ie 8000 running project and try to proxy to 8001 in one of my endpoints through nginx, I get 403 forbidden. We have tried shared cache based session store as well. -
My jquery function doesn't work with django
Can't run jquery with my django html page. I tried to run with html and it's work. But with django nothing happens. Here's my main_page.html : {% load static %} <html> <head> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link rel="stylesheet" href="{% static 'js/blog.js' %}"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="form-group"> <textarea class="text" style="display:inline" id="Textarea" ></textarea> <textarea class="text" style="display:inline" disabled="disabled" id="Textarea2"></textarea> </div> <button>Translate</button> </body> </html> and my blog.js file under static/js/blog.js : $(document).ready(function(){ $("button").click(function(){ $("#Textarea2").hide(); }); }); I expect for the Textarea2 to hide. -
find current action in Django 2.2 admin site formfield_for_choice_field function
I am trying to have different choices for one of my combo boxes in admin site form. def formfield_for_choice_field(self, db_field, request, **kwargs): c_object = kwargs.pop('obj', None) if db_field.name == 'setad_confirm_status': if not c_object: out_tup = [i for i in ReserveRequest.CONFIRMATION_CHOICES if i[0] == 'none'] else: if request.user.has_perm('home.can_final_accept'): out_tup = [i for i in ReserveRequest.CONFIRMATION_CHOICES if i[0] != 'accept'] else: out_tup = [i for i in ReserveRequest.CONFIRMATION_CHOICES if i[0] != 'final_accept'] kwargs['choices'] = out_tup return db_field.formfield(**kwargs) I tried to get the obj parameter to find out is it Edit or 'Addaction butobj` is empty in both. can't have any solution to get the current action? -
where is the error in the update function?
i have django project that includes a form to be submit and allow user to create an update the stored data. the problem is that once the user go the update page the system crash and display the below error : Reverse for 'update' with no arguments not found. 1 pattern(s) tried: ['blog/update/(?P[0-9]+)/$'] urls.py path('update/<int:pk>/',update,name = 'update'), update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div><div class="line"></div> </div> {% for member in instance %} <form enctype="multipart/form-data"> <div id='left-column-Input' class="formInput" include="select()"> <div class="forminputs"> <input type="text" id="fname" name="fname" autocomplete="off" required /> <label for="fname" class="label-name"> <span class="content-name" name="fname">{{member.member_name}}</span> </label> </div> <div class="forminputs"> <input type="text" id="lname" name="lname" autocomplete="off" required /> <label for="lname" class="label-name"> <span class="content-name" name="lname">{{member.member_last_name}}</span> </label></div> <div class="forminputs"> <input type="text" id="fatherName" name="fatherName" autocomplete="off" required /> <label for="fatherName" class="label-name"> <span class="content-name" name="fatherName">{{member.member_father_name}}</span> </label></div> <div class="forminputs"> <input type="text" id="motherName" name="motherName" autocomplete="off" … -
Getting django database admin pages with no css
I'm getting the django admin page with no css. I changed static url and re-install both python and pycharm. But still getting it without any css. I'm using windows 10 os. -
How can I get the distinct month and years in the form ModelMultipleChoiceField in django?
I have a model as below: class Program(Model): name = CharField(...) teacher = CharField(...) class ProgramIntake(Model): program = ForeignKey(Program, ...) intake = DateField(null=True, blank=True, ) I have a few object for programs such as math and art as instances of Program model: math = Program.objects.create(name='math') art = Program.objects.create(name='art') each program has a few intakes: math_intake1 = PorgramIntake.objects.create(program=math, intake='2019-01-01') math_intake2 = PorgramIntake.objects.create(program=math, intake='2019-01-15') math_intake3 = PorgramIntake.objects.create(program=math, intake='2020-01-01') art_intake1 = PorgramIntake.objects.create(program=art, intake='2019-01-01') art_intake2 = PorgramIntake.objects.create(program=art, intake='2019-02-18') art_intake3 = PorgramIntake.objects.create(program=art, intake='2020-05-21') in order to build my form I have built this model: class StudyIntake(Model): available_intakes = ManyToManyField(ProgramIntake, blank=True, ...) and the below form usign ModelForm: class StudyIntakeForm(ModelForm): available_intakes = ModelMultipleChoiceField(queryset=ProgramIntake.objects.values_list('intake', flat=True).distinct().order_by('intake'), required=False) class Meta: model = StudyIntake fields = '__all__' I have rendered this form in view as below: def programs(request): template_name = 'programs/programs.html' context = {} if request.POST: study_intake_form = StudyIntakeForm(request.POST) if study_intake_form.is_valid(): pass else: study_intake_form = StudyIntakeForm() context.update({'study_intake_form': study_intake_form,}) return render(request, template_name, context) and in html I have: <form method="post"> {% csrf_token %} {{ study_intake_form.as_p }} <button type="submit">Filter</button> </form> What I expect is that I want to just see the below choices in my form: Jan 2019 Feb 2019 Jan 2020 May 2020 -
How to get objects from Django ForeignKey in forms?
I am trying to relate model one with model two using ForeignKey but in views.py I am Stucked models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=False) def __str__(self): return self.patient.name forms.py: class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','date_of_admission'] views.py : @login_required def ipd (request,patient_id): p = Patient.objects.get(pk=patient_id) if request.method=="POST": formtwo = IpdForm(request.POST,instance=a) if formtwo.is_valid() : formtwo.user_id = request.user.id if formtwo.save(): return HttpResponseRedirect('ipd_list.html', messages.success(request, 'Patient is successfully updated.', 'alert- success')) else: return render('ipd_list.html', messages.error(request, 'Data is not saved', 'alert-danger')) else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'p':p ,'form2':formtwo}) html: <div class="card-panel"> <span class="blue-text text-darken-2">Name : {{p.name}}</span> <br> Phone : {{ p.phone }} Address : {{ p.address }} Gender : {{ p.Gender }} when I use the above code, I get the object that I required, but they do not have relation with other model -
"only protocol 3 supported" error when trying to connect to Postgresl Database through Django
Windows 10 x64 Python 3.6 psycopg2==2.8.3 PostgreSQL 9.1.1.2-1.1C(x64) Django 2.2.1 When trying to execute query to database I get an error "only protocol 3 supported" I run: python manage.py makemigrations I got a big pile of errors with the django.db.utils.InterfaceError: only protocol 3 supported in the end. psql \list The settings.py DATABASES = {} SECTION is set up with valid credentials I can even connect to db using them How can I solve this problem? -
How to expose static files from django container to nginx
I'm trying to expose static files from inside a django docker container so the globally (not in a container) installed nginx can serve static files. What is important i want to do it using ansible. I tried to use volume pointing to public folder inside container, but docker clears this folder when running container. This is my Dockerfile: FROM python:3.7-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/app ADD requirements.txt ./ RUN pip install -r requirements.txt ADD . /usr/src/app RUN python manage.py collectstatic --noinput RUN python manage.py migrate CMD gunicorn testdocker.wsgi -b 0.0.0.0:8000 Static root directory is in /usr/src/app/public Finally, nginx should server static files which are inside docker container. -
How to create, store and access user-defined forms in Django?
I am designing a basic workflow system that allows one user to fill in a form and pass it to another for approval. This is quite easy if I use static models that are pre-configured in models.py; you simply add a new record for each submission with a field designating the status and a few if functions. However, if I want to allow users to design their own forms (i.e. change the number and type of fields they might use), what's the best way of doing this? I still want to be able to identify each form submission as a separate record and to access individual values specific to fields in the forms. For example, lets say a user wanted to define the following "dynamic" fields in a model: CharField 1 DateField 2 FileField 3 I thought maybe one approach could be to use PostgreSQL and an ArrayField; set some constants for the record (e.g. ID and Status) and then store these dynamic fields in the array. However at this point I am stuck; how can I also store the values these fields have and access them as objects (e.g. if I want to display specific values in a template … -
When i visit my heroku app URL i get an application error
When i open my URL for my heroku app, i am greeted with an application error, i open the log, it seems to be an error in the wsgi.py but i havent touched this file so not sure what has gone wrong? does anyone know how to deal with this or what the problem is? the heroku log is below 2019-07-21T11:54:46.385562+00:00 heroku[web.1]: Starting process with command `gunicorn pages_project.wsgi --log-file -` 2019-07-21T11:54:48.492272+00:00 heroku[web.1]: State changed from starting to crashed 2019-07-21T11:54:48.498164+00:00 heroku[web.1]: State changed from crashed to starting 2019-07-21T11:54:48.350477+00:00 app[web.1]: [2019-07-21 11:54:48 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-07-21T11:54:48.351441+00:00 app[web.1]: [2019-07-21 11:54:48 +0000] [4] [INFO] Listening at: http://0.0.0.0:8787 (4) 2019-07-21T11:54:48.351625+00:00 app[web.1]: [2019-07-21 11:54:48 +0000] [4] [INFO] Using worker: sync 2019-07-21T11:54:48.357939+00:00 app[web.1]: [2019-07-21 11:54:48 +0000] [10] [INFO] Booting worker with pid: 10 2019-07-21T11:54:48.371312+00:00 app[web.1]: [2019-07-21 11:54:48 +0000] [10] [ERROR] Exception in worker process 2019-07-21T11:54:48.371321+00:00 app[web.1]: Traceback (most recent call last): 2019-07-21T11:54:48.371328+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2019-07-21T11:54:48.371334+00:00 app[web.1]: worker.init_process() 2019-07-21T11:54:48.371337+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process 2019-07-21T11:54:48.371338+00:00 app[web.1]: self.load_wsgi() 2019-07-21T11:54:48.371340+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2019-07-21T11:54:48.371342+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2019-07-21T11:54:48.371352+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2019-07-21T11:54:48.371354+00:00 app[web.1]: self.callable = self.load() 2019-07-21T11:54:48.371356+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line … -
How to store configuration data such as admob and api configs?
what is the right way to store data such as admob config , api config , website name etc..? basically these infos should be unique and be used throughout the whole website and also editable real-time without needing to reload the server. i came across django-constance but i felt like it gives much more than i need. i came across djang-dynamic-preferences as well , i'm not sure which of these i should spend my time on . else ,is there a simpler way to do this? -
Sending Json object to django server using HttpUrlConnection
I am working on android app which will record audio sound and send the base64 encoded string to django server using HttpUrlConnection. Problem is when i press "Send to server" app goes crash. Could any one help me where is mistake in my code. Thanks in advance for your time. I just only want to send data to server Variables HttpURLConnection connection; URL urlConnection = new URL("My url"); JSONObject jResponse; Code for "Send to server" button File file = new File(Environment.getExternalStorageDirectory() + "/_audio_record.3gp"); try { byte[] bytes = FileUtils.readFileToByteArray(file); encoded = Base64.encodeToString(bytes, NO_WRAP); Log.i("myApp",encoded); Toast.makeText(getApplicationContext(),encoded,Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); } //Sending json to server JSONObject param=new JSONObject(); try { param.put("name",encoded); } catch (JSONException e) { e.printStackTrace(); } makeRequest(param.toString()); makeRequest() private JSONObject makeRequest(String param) { try { HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/json;charset=UTF-8"); connection.setReadTimeout(60000); connection.setConnectTimeout(60000); connection.connect(); DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); Log.d("MyApp" ,param); dataOutputStream.writeBytes(param); dataOutputStream.flush(); dataOutputStream.close(); InputStream in = new BufferedInputStream(connection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } Log.d("MyApp: ",result.toString()); jResponse = new JSONObject(result.toString()); } catch (IOException | JSONException e) { e.printStackTrace(); return jResponse=null; } connection.disconnect(); return jResponse; } -
Passing HTML input tag value to Django view
I have an input element in my django template which has an onclick event written in javascript I want the updated value of this input element to pass to my view in views.py How to achieve this? **Below is my HTML element** <input id="minus" type="button" class="btn btn-black btn-outline-white py-3 px-4" size="5" value="-"> <input id="theInput" type="number" name="quantity" size="2" class="btn btn-primary btn-outline-black py-3 px-1" title="Qty" value="1" min="0" step="1"> <input id="plus" type="button" class="btn btn-black btn-outline-white py-3 px-4" size="5" value="+"> **Below is my script function** <script> input = document.getElementById('theInput'); document.getElementById('plus').onclick = function(){ input.value = parseInt(input.value, 10) +1 } document.getElementById('minus').onclick = function(){ input.value = parseInt(input.value, 10) -1 } </script>