Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
open PDF in mobile app using python
I am using FPDF for Python to generate PDF in my djnago application.I open the PDF in my desktop but unable to open the file in android mobile and in my app.When try to open the file it loading for long time and mobile hang.How to open the PDF in new tab in android. -
how to create multiple instances in django?
def form_creation(request): if request.method=='POST': eventlist=request.POST.getlist('events') print(eventlist) for e in eventlist: form=Registration_Form(request.POST) form.username= request.POST['username'] form.email= request.POST['email'] form.phone_number=request.POST['phone_number'] form.college_name=request.POST['college_name'] form.year=request.POST['year'] form.events=EventClass.objects.get(events=e) print(form.is_valid()) if form.is_valid(): form.save() return render(request,'app/result.html',{'form':form}) else: err="Please Enter Correct Data" content={'form':form,'err':err} return render(request,'app/form.html',content) else: form=Registration_Form() content={'form':form} return render(request,'app/form.html',content) -
Django runserver error after startproject
I'm new to Django and web frameworks in general. Right off the bat, I can't seem to run the server after django-admin startproject mytestsite. I've tried this with and without a virtual environment, and with Python's built-in virtual environment tool as well as virtualenv. This is the error I get: (my_django_environment) MacBook-Pro:mytestsite alialsabbah1$ python3 manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x108caef28> Traceback (most recent call last): File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/alialsabbah/.virtualenvs/my_django_environment/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in … -
Pass object id to view from form submission
I have a website where user submitted entries are displayed and have an upvote count along with a button to upvote it yourself. These are represented with the Entry model. How do I pass the id of the particular Entry instance the user upvotes to a view? html: {% for entry in entries %} <div id="upvote_count"> <form action="upvote" method="GET"> {% csrf_token %} {{ entry.upvotes }} <button id="upvote" type="submit">Upvote</button> </form> </div> {% endfor %} models.py: class Entry(models.Model): #... upvotes = models.IntegerField( blank = True, null=True) current url: url(r'^upvote$', views.upvote), -
how can I convert an incorrectly-saved bytes object back to bytes? (python/django)
I've downloaded some web pages with requests and saved the content in a postgres database [in a text field] using Django's ORM. For some sudocode of what's going on, here ya go: art = Article() page = requests.get("http://example.com") art.raw_html = page.content art.save() I verified that page.content is a bytes object, and I guess I assumed that this object would automatically be decoded upon saving, but it doesn't seem to be... it has been converted to some weird string representation of a bytes object, ostensibly by Django. It looks like this in the interpreter when I call art.raw_html: 'b\'<!DOCTYPE html>\\n<html lang="en" class="pb-page" And if I call it with print I get this: b'<!DOCTYPE html>\n<html lang="en" class="pb-page" And for the life of me I can't re-encode it to a bytes object, even if I trim off the leading b' and trailing '. I feel like there's an easy solution to this and I feel like an idiot... but after lots of experiments and googling, I'm not figuring it out. Incidentally, if I manually copy what's returned from the print statement (like with my cursor), I can convert the clipboard contents back to a bytes object just fine and then decode it into … -
DRF ListSerializer and FieldSerializer
I use django rest in my project and until now for list of objects I used ListSerializer, when I needed to have min length and max length of list I googled and reached to ListField. Before that my code worked fined without any error and misbehavior. Now I use ListField for my list field serializer, But I didn't get when to use ListSerializer? Can someone explain the difference between ListSerializer and FieldSerializer? My sample code with ListSerializer: tags = serializers.ListSerializer(child=serializers.CharField(allow_blank=False), required=False) My sample code with FieldSerialzier: open_hour = serializers.ListField(child=serializers.DictField(), max_length=7, min_length=7) -
How to make django-summernote editor's height grow as content increases
I have a django-summernote widget SummernoteWidget implemented but now I wish to allow the height of the editor to grow as the editor content grows as described in the summernote documentation here I have tried removing the height property from the django_summernote\settings.py file because in the documentation it states that the height will automatically grow when there is no height property declared. My apps settings.py looks like this: SUMMERNOTE_CONFIG = { "summernote":{ "toolbar":[ ["state", ["undo", "redo"]], ["insert", ["table", "hr" ]], ["style", ["bold", "italic", "underline", "clear"]], ["font", ["style", "fontsize", "color", "strikethrough", "superscript", "subscript"]], ["paragraph style", ["ol", "ul", "paragraph", "height"]], ] } } Is there a way to make the height of the editor grow as the content area content grows? -
Test interoperability between Django and a client application
I have a project that includes a Django web service exposing a rest API (using DRF) and an python application that issues requests (using urllib.request) to that server. They are both in the same github repo and share a set of Travis-CI jobs, where some jobs test the Django site and other jobs test the python application. After writing several tests for each individually, I would like to create some tests that will trigger the entire flow, starting somewhere in the application code then issue a request that will directed to the django app which will in turn return a response that will be processed by the application. I believe I need some kind of a hook somewhere along my request.Request or opener.Open functions that normally send the HTTP request, and I'm certain this has been done before. I couldn't find anything on Django's documentation for that. -
What is the best way to draw simple line on image in django app
I am still new in django and I want to ask if I have a form to upload image what is the best way to edit it by drawing simple line upon the image -
raise AppRegistryNotReady Error when run django models.py using pycharm
i am a new django, i am trying to write a post api, but when i run the models.py using pycharm, there is a error about class Event(models.Model). the error details as below. Blockquote Traceback (most recent call last): File "F:/Auto_Projects/pydj/guest/sign/models.py", line 6, in class Event(models.Model): File "C:\Python27\lib\site-packages\django\db\models\base.py", line 110, in new app_config = apps.get_containing_app_config(module) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "C:\Python27\lib\site-packages\django\apps\registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. django version:1.11.14 python version:2.7 Blockquote INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sign', 'bootstrap3', ] my app name is 'sign', and i have added the 'sign' to the INSTALLED_APP of the settings.py. waiting for your suggestion,thx. -
EventSource addEventListener callback method is not called when event comes from Django server
EventSource addEventListener callback is not called when event comes Settings: Django 2.0.7 Chrome 67.0.3396.99 MacOSX 10.13.6 (17G65) Source code: In my chat.html: <script src="{% static 'django_eventstream/json2.js' %}" charset="utf-8"></script> <script src="{% static 'django_eventstream/eventsource.min.js' %}" charset="utf-8"></script> <script src="{% static 'chat/jquery-3.2.1.min.js' %}" charset="utf-8}"></script> <script type="text/javascript"> var testPubSub = function(user) { var uri = 'events/?channel=room-' + encodeURIComponent('{{ room_id }}'); var es = new EventSource(uri, { lastEventId: '{{ last_id }}' }); var firstConnect = true; es.onopen = function() { if (!firstConnect) { console.log('*** Connected'); } firstConnect = false; } es.onerror = function() { console.log('*** connection lost'); }; console.log('before addEventListener'); es.addEventListener('message', function(e) { console.log('addEventListener event'); console.log('event: ' + e.data); msg = JSON.parse(e.data); console.log(); }, false); console.log('after addEventListener'); $('#send-form').submit(function() { var text = $('#chat-input').val(); $.post('/rooms/{{ room_id }}/messages/', {from: user, text: text} ).done(function(data) { console.log('send response:' + JSON.stringify(data)); }).fail(function() { alert('failed to send message'); }).always(function() { $('#chat-input').val(''); $('#chat-input').focus(); }); return false; }); $('#chat-input').focus(); }; $(function() { testPubSub('{{ user|escapejs }}'); }); </script> </head> <body> <div id="chat-input-area"> <form id="send-form"> <button id="send-button">Send</button> <span id="chat-input-span"><input type="text" id="chat-input" autocomplete="off" /></span> </form> </div> </body> From console log, I can see that when I push the send button, the following log is printed: before addEventListener after addEventListener send response:"333" but addEventListener event is not printed … -
How to pre-populate the chosen box of the FilteredSelectMultiple in Django for user side?
I am trying to have the user's chosen item be shown in the FilteredSelectMultiple chosen box when he/she revisits the page. I have managed to save it to the database and had tried appending options via javascript but that didn't help. I have seen a stackoverflow question on how to pre-populate the same widget as well but that seems to be for the Admin side only. My FilteredSelectMultiple widget is on the user side. The options appending works for a select multiple defined in the template manually, but not for the widget Here is the code I used: models.py: class Roles(models.Model): role_id = models.AutoField(primary_key=True) role_name = models.CharField(max_length=18, unique=True, validators=[letters_only]) class Meta: db_table = "arc_roles" verbose_name_plural = "Roles" ordering = ['role_id'] def __str__(self): return self.role_name class Staffs(models.Model): staff_id = models.AutoField(primary_key=True) admission_number = models.CharField(max_length=5, unique=True, help_text="Enter 5 digits", validators=[numeric_only, MinLengthValidator(5)]) staff_full_name = models.CharField(max_length=70, help_text="Enter staff's full name", validators=[letters_only]) created_by = UserForeignKey(auto_user_add=True, editable=False, related_name="staff_created_by", db_column="created_by") created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_by = UserForeignKey(auto_user=True, editable=False, related_name="staff_updated_by", db_column="updated_by") updated_at = models.DateTimeField(auto_now=True, editable=False) roles = models.ManyToManyField(Roles, through='Designations') class Meta: db_table = "arc_staffs" verbose_name_plural = "Staffs" ordering = ['staff_id'] def __str__(self): return '%s (S%s)' % (self.staff_full_name, self.admission_number) class Designations(models.Model): designation_id = models.AutoField(primary_key=True) curriculum = models.ForeignKey(Curricula, on_delete=models.CASCADE) role = … -
Django giving me no reverse match error
NoReverseMatch at /errorcodes/error_codes/2 Reverse for 'relatedpartsview' with no arguments not found. 1 pattern(s) tried: ['errorcodes\/error_codes\/relatedparts\/(?P[^/]+)$'] Currently I am trying to pass a PK into my link as an argument. However, I keep getting no reverse match. I have added a redirect statement, but that doesn't seem to be resolving the issue. views.py class RelatedPartsListView(ListView): context_object_name = 'related_parts_list' model = models.ErrorCodes template_name = 'related_parts_list.html' def get_context_data(self, **kwargs): # xxx will be available in the template as the related objects context = super(ErrorCodeView, self).get_context_data(**kwargs) context['relatedparts'] = RelatedParts.objects.filter(related_error_code=self.get_object()) return context return redirect('RelatedPartsListView', pk='pk') urls.py urlpatterns = [ path(r'error_codes/',views.ErrorCodeList.as_view(), name='errorcodelist'), path(r'error_codes/<pk>',views.ErrorCodeView.as_view(), name='errorcodeview'), path(r'error_codes/relatedparts/<pk>',views.RelatedPartsListView.as_view(), name='relatedpartsview') ] Link {% url 'errorcodes:relatedpartsview' %} -
is there an equivalent of pip install ... --exists-action [option] for make?
I'm migrating a django app (python env 3.5.3) from CircleCi 1.0 to 2.0 and running CCI suite from .circleci/config.yml currently, tests are failing from a - run: make circle-deps --always-make command in the CCI build because of a specific requirements.txt dependency: -e git+https://github.com/celery/billiard.git@7dcbf6125ba60d103571228aec2aa7acb5ce193c#egg=billiard err: Obtaining billiard from git+https://github.com/celery/billiard.git@7dcbf6125ba60d103571228aec2aa7acb5ce193c#egg=billiard (from -r requirements.txt (line 8)) Directory /home/ubuntu/foo/bar/src/billiard already exists, and is not a git clone. The plan is to install the git repository https://github.com/celery/billiard.git What to do? (i)gnore, (w)ipe, (b)ackup Exception: Traceback (most recent call last): File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/basecommand.py", line 141, in main status = self.run(options, args) File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/commands/install.py", line 299, in run resolver.resolve(requirement_set) File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/resolve.py", line 102, in resolve self._resolve_one(requirement_set, req) File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/resolve.py", line 256, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/resolve.py", line 193, in _get_abstract_dist_for req, self.require_hashes, self.use_user_site, self.finder, File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/operations/prepare.py", line 321, in prepare_editable_requirement req.update_editable(not self._download_should_save) File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/req/req_install.py", line 835, in update_editable vcs_backend.obtain(self.source_dir) File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/vcs/__init__.py", line 372, in obtain response = ask_path_exists('What to do? %s' % prompt[0], prompt[1]) File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/utils/misc.py", line 156, in ask_path_exists return ask(message, options) File "/opt/circleci/python/3.5.3/lib/python3.5/site-packages/pip/_internal/utils/misc.py", line 167, in ask response = input(message) EOFError make: [circle-deps] Error 2 (ignored) what I want to do with the make command is something like pip's --exists-action i, but if I … -
Issue with ajax call csfr token
I am trying to add an ajax call that changes the status of a listing, between listed and unlisted, when submitting the form I am having a 403 forbidden error in the console of the browser, I made some checking and it appears that Django is forbidding the form because of a lack of csrf token, however I am not good in javascript, so any help would be appreciated. Here is my code in my view: @require_POST @ajax_required @login_required def unlist_ajax(request): pk = request.POST.get('pk', None) is_visible = request.POST.get('is_visible', None) if pk and is_visible: listing = get_object_or_404(Listing, pk=pk) if is_visible == 'true': listing.is_visible = False listing.save() messages.success(request, _("Listing unlisted")) return JsonResponse({'status': 'ok'}) else: listing.is_visible = True listing.save() messages.success(request, _("Listing re-listed")) return JsonResponse({'status':'ok'}) and here is the template script: in the top of the template, in the header: <script> function unlistPostAjax(listing_id, is_visible) { var confirmation = confirm("{% trans 'are you sure you want to change the status of your listing?' %}"); if (confirmation) { $.post("{% url 'dashboard:unlist_ajax' %}", {pk: listing_id, is_visible: is_visible}, function (response) { console.log('sending delete query'); location.reload(); }) } } </script> and in the bottom of the body: <script src="{% static 'js/jquery.cookie.js' %}"> </script> <script> $(document).ready(function () { var csrftoken … -
Django - UpdateView form does not save
My code for using forms inside CBV(UpdateView) won't save to DB when clicking Submit button. I don't see what's wrong. views.py class BHA_UpdateView(UpdateView): template_name = 'bha_test.html' context_object_name = 'bha' model = BHA_List success_url = reverse_lazy('well_list') pk_url_kwarg = 'pk_alt' form_class = BHA_overall_Form def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) api = get_well_api(self.request) context['single_well_bha_list'] = BHA_List.objects.filter(well=api) return context def form_valid(self, form): self.object = form.save() return super().form_valid(form) models.py class WellInfo(models.Model): api = models.CharField(max_length=100, primary_key=True) well_name = models.CharField(max_length=100) status = models.CharField(max_length=100) class BHA_List(models.Model): well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list') bha_number = models.CharField(max_length=100) class BHA_overall(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall') drill_str_name = models.CharField(max_length=111) depth_in = models.CharField(max_length=111) bha_test.html <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" class='btn btn-primary' value="Submit"> </form> forms.py from django import forms from contextual.models import BHA_overall class BHA_overall_Form(forms.ModelForm): class Meta(): model = BHA_overall fields = '__all__' So there is a model = BHA_List, and there is another form that is related to the model by a foreign key. The form fields will be displayed to the users, and upon clicking a submit button, it should save the user input to DB, but it doesn't. What's wrong? -
Why is this url not being resolved by reverse on Django?
I have a method that updates an entry: @require_POST def update(request, uuid): posti = get_object_or_404(Post, uuid=uuid) f = PostForm(request.POST) if f.is_valid(): posti.title = request.POST['title'] posti.text = request.POST['text'] posti.save() return HttpResponseRedirect(django.urls.reverse('posti:detail', args=(posti.uuid,))) else: messages.error(request, "No title in form") return render(request, 'posti/detail.html', {'form': f}) I'm trying to test this method with a case: def create_post(): """ :rtype : Post """ data = {'title': 'Esto es un titulo', 'text': 'Esto es un texto de prueba'} post = Post.create_post(data['title'], data['text']) post.save() print('The UUID is: ', post.uuid) return post def test_updating_post_with_no_title(self): """ A post with no title should not be saved :return: """ p = create_post() print('(test) The UUID is: ', p.uuid) data = {'title': '', 'text': 'Esto es un texto de prueba'} url = reverse('posti:update', args=(p.uuid,)) response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, "No title in form") Whatever I do I always get this error: django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['posti/update/(?P[0-9a-zA-Z-_]+)/$'] The UUID does show up in the test using print(p.uuid) in both methods but it's not reaching the fourth line from bottom to top. Why is it not calling it? -
How to add an extra field to a Django ModelForm?
So I'm working on an admin page. I'm registering the form with admin.site.register. And I want to add an extra field to the form, which will let me populate a TextField with a file contents. Therefore I need to add an extra FileInput to upload the file and populate the TextField with its contents. I am trying this: class PersonForm(forms.ModelForm): extra_field = forms.FileInput() class Meta: model = Person fields = '__all__' but the field is not showing. Any ideas? Also I have no clue where to access the file contents and populate the TextField with that before saving the model. Thanks in advance. -
Python Twitter APi using OAuth not providing email
I need to use Twitter API to allow Twitter login for my site. Using Python (Django), I have been able to get the user's name and username and other relevant data, but not the user's email. I have already checked the box for email permission on apps.twitter.com, and the user is prompted that his/her email will be used when login in. But the request doe not contain the email. Here's my code: def get_user_details(self, response): """Return user details from Twitter account""" try: first_name, last_name = response['name'].split(' ', 1) except: first_name = response['name'] last_name = '' print response return {'username': response['screen_name'], 'email': 'response['email']', 'fullname': response['name'], 'first_name': first_name, 'last_name': last_name} The response that is printed contains and screen_name and name, but not the email. I know my tokens are correct because I get all the other data. This is the API call I'm making: TWITTER_CHECK_AUTH = 'https://%s/1.1/account/verify_credentials.json?include_email=true&include_entities=false&skip_status=true' % TWITTER_SERVER Any ideas? -
Django API works locally but not when deployed on Elastic Beanstalk
I'm working with Django Rest Framework and Django Rest Framework JWT, but I'm running into an issue in regards to local behavior vs external behavior. When I make a POST request to get a JWT token, everything works as desired both locally and on my EC2 instance. However, once I have the token, when I make a request to my server that requires authentication, only my local server returns the expected response. On my deployed server, I get the following error: {"detail":"Authentication credentials were not provided."} What I've tried so far: Editing http.conf by sshing into my server and enabling WSGIPathAuthorization. (saw a similar post here and tried the solution) What could be causing this behavior? My local machine and my deployed code are identical, leading me to believe that this has something to do with server-side configuration. All help is appreciated. Thanks! -
How To Get Django Form To Validate Multiple Fields Together
I'm trying to write a clean method that validates whether 3 fields (percentages) add up to zero. I followed the django documentation and added the clean() method to my form class but Django still redirects after the form submits, indicating the is_valid() function passed successfully. It seems like the clean method just be called by the Django is_valid() and not allow the form to submit... Have checked out a similar answer but no luck. forms.py class RequirementsForm(forms.ModelForm): class Meta: model = Profile fields = ('cal_req', 'prot_bool', 'carb_bool', 'fat_bool', 'stf_bool', 'fib_bool', 'sug_bool', 'sod_bool', 'cho_bool', 'clc_bool', 'irn_bool', 'vta_bool', 'vtc_bool', 'prot_perc', 'carb_perc', 'fat_perc', 'stf_g_thr', 'fib_g_req', 'sug_g_thr', 'sod_mg_thr', 'cho_mg_thr',# must opt-in for dietary cholesterol reqs. But default is 300 / Decimal(2000) 'clc_mg_req', 'irn_mg_req', 'vta_mcg_req', 'vtc_mg_req' ) def clean(self): cleaned_data = super().clean() prot_perc = cleaned_data.get('prot_perc') fat_perc = cleaned_data.get('fat_perc') carb_perc = cleaned_data.get('carb_perc') if sum([prot_perc, fat_perc, carb_perc]) != 1.0: raise forms.ValidationError(_('Macro percents must add up to 1!')_) views.py @login_required(login_url='/login/') def questionaire(request): prof, created = Profile.objects.get_or_create(user=request.user) # Careful, this clashes with the reciever in models.py if created: prof.save() if request.method=='POST': # Will post requirements form req_form = RequirementsForm(request.POST, instance=prof) if req_form.is_valid(): req_form.save() return HttpResponseRedirect('/') else: req_form = RequirementsForm(instance=prof) context={'req_form':req_form, 'prof':prof} return render(request, 'core/questionaire_form.html', context) form.html </tr> <tr> <th … -
Bad Request 400 Django App on Heroku
guys there is a issue in deploying my django app in heroku here is my procfile web:gunicorn drf.wsgi:application --log-file - web: python manage.py runserver 0.0.0.0:$PORT wsgi.py import os from whitenoise.django import DjangoWhiteNoise from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "drf.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) added allowed hosts as well ALLOWED_HOSTS = ['mxiondrf.herokuapp.com'] here are my logs 18-07-23T23:34:50.814903+00:00 heroku[router]: at=info method=GET path="/" host=mxiondrf.herokuapp.com request_id=f4f07d1 b-be4a-4f62-85e0-6701c420da1c fwd="103.49.121.34" dyno=web.1 connect=0ms service=93ms status=400 bytes=154 protocol=https 2018-07-23T23:34:51.408577+00:00 app[web.1]: [23/Jul/2018 23:34:51] "GET /favicon.ico HTTP/1.1" 400 26 2018-07-23T23:34:51.410953+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=mxiondrf.herokuapp.com request _id=951b1ad8-0716-43c0-b21e-a8390ff59e63 fwd="103.49.121.34" dyno=web.1 connect=0ms service=79ms status=400 bytes=154 proto col=https 2018-07-23T23:34:54.506740+00:00 heroku[router]: at=info method=GET path="/" host=mxiondrf.herokuapp.com request_id=581d35d 6-bdf3-49f9-9c4f-a74d6c39da08 fwd="103.49.121.34" dyno=web.1 connect=1ms service=60ms status=400 bytes=154 protocol=https 2018-07-23T23:34:54.506394+00:00 app[web.1]: [23/Jul/2018 23:34:54] "GET / HTTP/1.1" 400 26 2018-07-23T23:34:55.006560+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=mxiondrf.herokuapp.com request _id=c0c33673-f212-4679-ada8-7e7719e283eb fwd="103.49.121.34" dyno=web.1 connect=0ms service=124ms status=400 bytes=154 prot ocol=https 2018-07-23T23:34:55.004234+00:00 app[web.1]: [23/Jul/2018 23:34:55] "GET /favicon.ico HTTP/1.1" 400 26 any kind of help is appreciated -
MaxLength for Integer field in Django
I want to limit the length of my integer field, but I don't want to use something like: validators=[MaxValueValidator(999999999)] what can I use instead of that? Thanks. -
i need to let form errors to be shown on my bootstrap modal template
I have made LoginView as CBV approach, and try to validate the credentials of the user plus adding some validations on the email_address. my problem is when I raise ValidationError the errors haven't appeared on the template. p.s: I don't want to use Ajax solution.i just need to use the Django rendering form error messages solution. the errors messages are printed on the terminal. <ul class="errorlist"><li>__all__<ul class="errorlist nonfield"><li>crediantials errror</li></ul></li></ul> my views.py: class LoginView(FormView): form_class = login_page template_name = 'login.html' def get_success_url(self): return reverse('home') def get_form_kwargs(self,*args,**kwargs): kwargs=super().get_form_kwargs(*args,**kwargs) kwargs['request'] = self.request return kwargs def form_valid(self, form): return JsonResponse({ "case":'valid', 'to_page':self.get_success_url() }) # return redirect('/') def form_invalid(self, form): print(form.errors) print(form.non_field_errors()) print(form['Email'].errors) return super().form_invalid(form) my forms.py: class login_page(forms.Form): Email = forms.EmailField(required=True,widget=forms.EmailInput( attrs={"class": "form-control", "placeholder": "Email address", "id": "exampleInputEmail2"})) Password = forms.CharField(required=True,widget=forms.PasswordInput(attrs={"class": "form-control",'id':'exampleInputPassword2', "placeholder": "Password"})) def __init__(self,*args,**kwargs): self.request=kwargs.pop('request',None) super().__init__(*args,**kwargs) def clean(self): email = self.cleaned_data.get('Email',None) password = self.cleaned_data.get('Password',None) user = authenticate(email=email, password=password) if user is not None: login(self.request, user) else: print("crediantials errror") raise forms.ValidationError("crediantials errror") return self.cleaned_data def clean_Email(self): if (self.cleaned_data.get('Email', '') .endswith('hotmail.com')): raise forms.ValidationError("Invalid email address.") return self.cleaned_data.get('Email', '') my template <div class="row div_Modal"> <div id="loginModal" class="modal fade loginModal-content col-sm-8 col-sm-offset-2 col-md-5 col-md-offset-3"> <div class="loginModal-content"> <div class="loginModal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Login</h4> </div><div class="loginModal-body"> … -
Wagtail: Can I display a Page's siblings on the admin side?
Is it possible, within Wagtail, to query a Page's siblings, then display them on the Pages admin page in checkboxes? So far, I have: class MyPage(Page): def siblings(self): siblings = MyPage.objects.live().sibling_of(self) return siblings def sibling_titles(self): sibling_choices = () for sibling in self.siblings: title = sibling.title title_slug = slugify(sibling.title) sibling_choices.append(tuple((title_slug, title))) return sibling_choices CHOICES = sibling_titles sibling_checkbox = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=CHOICES, ) sidebar_content_panels = [ FieldPanel('sibling_checkbox'), ] but it's throwing this error: django.core.exceptions.FieldError: Unknown field(s) (sibling_checkbox) specified for MyPage My limited Django skills make me believe I'm close, but I'm not quite sure where to go from here. Can anyone help?