Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Datafile not found, datafile generation failed in confusable_homoglyphs/categories.py
I'm setting up a django project on an apache server. It is running fine on my PC under using manage.py runsslserver. When I load onto the apache server I can run manage.py migrate and collectstatic and a number of setup programs. BUT when I try to enter the webpage I get error message "Datafile not found, datafile generation failed" with this traceback: Environment: Request Method: GET Request URL: https://ekim.hexiawebservices.co.uk/ Django Version: 1.11.5 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'registration', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'djangosecure', 'sslserver', 'ekim'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/var/www/ekim/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/var/www/ekim/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "/var/www/ekim/env/lib/python2.7/site-packages/django/urls/resolvers.py" in resolve 362. for pattern in self.url_patterns: File "/var/www/ekim/env/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/var/www/ekim/env/lib/python2.7/site-packages/django/urls/resolvers.py" in url_patterns 405. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/var/www/ekim/env/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/var/www/ekim/env/lib/python2.7/site-packages/django/urls/resolvers.py" in urlconf_module 398. return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/var/www/ekim/ekim/urls.py" in <module> 30. url(r'^accounts/', include('registration.backends.hmac.urls')), File "/var/www/ekim/env/lib/python2.7/site-packages/django/conf/urls/__init__.py" in include 50. urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/var/www/ekim/env/lib/python2.7/site-packages/registration/backends/hmac/urls.py" in <module> 10. from . import views File "/var/www/ekim/env/lib/python2.7/site-packages/registration/backends/hmac/views.py" in <module> … -
Apache config for Django
Django / MySQL / Apache2 - everything up-to-date (as far as I can tell) and there is Django data in the correct db/table I'm struggling to get my Django stuff to appear on my webbrowser. If I use python3 manage.py runserver 192.168.0.10:8000, I can see the Django install and admin page, but I'd like to see it without specifying a port number, and I'm aware that using runserver is the development side, rather than deployment. Also worth noting that I have NOT used any form of VirtualEnv as this is a dedicate Pi/Project, and I was getting confused with the libraries, local python install, virtual python install etc. Trying to narrow things down, I think I've got one of three problems. 1 - Apache isn't configured correctly 2 - Permissions/ownership issue of MySQL (e.g. apache not reading from table) 3 - Permissions/ownership issue of dir's (e.g. /var/www) I posted a similar question not too long ago, I've revisited that and the links that came with it, but it's not helped. I did have PHP and a VirtualEnv installed that time, and this is a fresh installation without either. I'm looking to have php install to have a bit of a … -
Heroku warning:django.request:not found: /
apologies i need some help. cant find a solution after 3 full days. i'm having this error shown on heroku- warning:django.request:not found: / i suppose this relates to static files and have done the below: a) heroku run ls -l project/ enter image description here --> the static folder here contains css, js, img, vendor files. As static folder appears in heroku, this looks correct? b) heroku run python manage.py collectstatic --dry-run --noinput --> 0 static files copied to '/app/static', 1115 unmodified. I think something could be wrong here? c) followed all deployment steps in django, django cms, aldryn and heroku. Hence I think settings, wsgi should be correct. The guides have been pretty silent on urls.py so I suspect my errors could be: a) potential error 1? urlpatterns = [ url(r'^tools/$',views.tickervalu, name='tools'), url(r'^sitemap\.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^admin/', admin.site.urls), url(r'^', include('cms.urls')), ] if settings.DEBUG: urlpatterns += [ url(r'^static/(?P<path>.*)$', serve,) ] b) potential error 2? BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'aldryn_boilerplates.staticfile_finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Thanking you in advance. Please let me know if more information is needed, really appreciate it. -
ValueError: Related model u'app.model' cannot be resolved when running tests
I have a doubt, so I am asking here for some help. Thanks in advance. I am trying to run some tests on a Django project (Django version 1.11.4) using Python 3.5.0. I have 2 applications inside my project: uploads and testgen. Those are my models: (Here there are only the special fields, like the relationships fields. The rest of the fields are CharField, PositiveIntegerField and BooleanField mainly.) uploads\models.py (a simplified version) class Document(models.Model): (any relationship fields) class Word(models.Model): synonyms = models.ManyToManyField("self") antonyms = models.ManyToManyField("self") class Sentence(models.Model): words = models.ManyToManyField(Word) class Paragraph(models.Model): sentences = models.ManyToManyField(Sentence) class Text(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE) paragraphs = models.ManyToManyField(Paragraph) testgen\models.py (a simplified version) class Issue(models.Model): content = models.OneToOneField(Sentence, related_name="issue_content", null=True) question = models.OneToOneField(Sentence, null=True) class FillableIssue(Issue): replaceable_words = models.ManyToManyField(Word) class StatementIssue(Issue): replaceable_words = models.ManyToManyField(Word) class AppTest(models.Model): text = models.ForeignKey(Text, null=True) fillable_issues = models.ManyToManyField(FillableIssue) statement_issues = models.ManyToManyField(StatementIssue) testgen\tests.py from django.test import TestCase from testgen.models import AppTest class AppTestTestCase(TestCase): def test_apptest_has_positive_number_issues(self): """ has_positive_number_issues() returns True if the test's number issues is greater than zero. """ app_tests = AppTest.objects.get_queryset().all() for app_test in app_tests: self.assertIs(app_test.has_positive_number_issues(), True) project settings file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploads', 'testgen', ] Note: I use the uploads models inside the … -
HTML not rendering arabic [on hold]
I have a website where I want to display a dropdown. The values can be a mixture of english and arabic. My application is in django-python. I have a unicode : u'GO \u062a\u0631\u0641\u064a\u0647' I want to render it on UI as arabic but, If I send it to html as is, I get Uncaught SyntaxError: Unexpected string If i do encode('utf-8') it gets translated to some garbage. What should I do? Note: I have # -- coding: utf-8 -- at the top of my view. I have <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> at the top of my html . What am I missing? -
MultiValueDictKeyError at /accounts/upload_save/ "'image'"
I got an error,MultiValueDictKeyError at /accounts/upload_save/ "'image'". I wrote in views.py @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/accounts/photo.html', {'form': form}) in index.html <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> in forms.py class UserImageForm(forms.ModelForm): class Meta: model = ImageAndUser fields = ('image',) in models.py class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images', null=True, blank=True,) Traceback is Traceback: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/XXX/Downloads/xxx/accounts/views.py" in upload_save 85. data.image = request.FILES['image'] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/datastructures.py" in getitem 85. raise MultiValueDictKeyError(repr(key)) Exception Type: MultiValueDictKeyError at /accounts/upload_save/ Exception Value: "'image'" My ideal system is image& user's data put in ImageAndUser model.Once I wrote in … -
Jumping from Django and basic JS directly into React Native?
For the last months I have this very interesting project of trying to learn how to build an app. I've spent some time on Django and Python and I plan on increasing my knowledge further. Using Django as a backend solution leaves open the question of the technologies to actually built the app. There are web based solutions (Phonegap etc.). But I am very interested in React native. So my question is - can I jump right into React native without knowing ReactJS before? And also I am really interested in the experiences you guys have with Django and React native? Is it a good fit? Thank you. -
Django: Get nearest object in future or past
How can you achieve this with one query: upcoming_events = Event.objects.order_by('date').filter(date__gte=today) try: return upcoming_events[0] except IndexError: return Event.objects.all().order_by('-date')[0] My idea is to do something like this: Event.objects.filter(Q(date__gte=today) | Q(date is max date))[0] But I don't know how to implement the max date. Maybe I've just to do it with Func. Or When or Case in django.db.expressions might be helpful. -
Can't implement partial update in Django REST Framework
I'm trying to implement partial update through PATCH requests on my Profile model. This is my class: class ProfilePartialUpdateView(viewsets.ModelViewSet): serializer_class = ProfileSerializer def partial_update(self, request, username): user = User.objects.get(username=username) serializer = ProfileSerializer(user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) However, when I send in the request, this is the response I get: NotImplementedError at /profile/update/new7/ update() must be implemented How should I implement it? -
DJango Attribute error : object 'A' has not attribute 'B' objects
model.py from __future__ import unicode_literals from django.db import models # Create your models here. class apartmentModel(models.Model): zone = models.ForeignKey('homepage.Zone',default='') siz_Of_house = models.IntegerField() rent = models.IntegerField() contact_number = models.CharField(max_length=14) details = models.TextField(max_length=120) parking_space =models.BooleanField() def __str__(self): a = str(self.siz_Of_house) b = str(self.zone); return a + " sq. feet apartment at " + b view.py from django.shortcuts import render from django.http import HttpResponse from apartment.models import apartmentModel as ap # Create your views here. def apartmentView(request): # template = loader.get_template('apartment/index.html') add_list = ap.obejcts.all() print(add_list) dict ={'ads':add_list} return render(request,'apartment/apartment2.html',None) I am new to django .While trying to load the apartment2.html i get 'Attribute error'like this : Exception Value: type object 'apartmentModel' has no attribute 'obejcts' I have checked few other related questions on the site .But i those were not enough. Thanks in advance . -
Django - how to save json posted data to REST API
I have the following json posted to localhost/api/user_add { "username":"test", "first_name":"First", "last_name":"Last", "address": { "street":"street", "town":"town" }, } The address need to be saved into the mysql table named address while the user info is saved into the table users with a column named address_id. I was able to write a simple model/serializer in order to be able to save username/first_name/last_name into the database, but i don't know how to save the address. I am using the django-rest-framework -
Incorrect view Django
I have a GET part of the view: def get(self, request, event_id, *args, **kwargs): form = self.form_class(initial={}) evnt = Event.objects.get(id=event_id) cmnt = Comments_events.objects.filter(event_cmnt_id=event_id) ANSWR = HOW TO GET? return render(request, self.template_name, {'event': evnt, 'comments': cmnt, 'answers': ANSWR, 'form': form}) Two models: class Comments_events(models.Model): ... class Answers(models.Model): ... comment_answr = models.ForeignKey('Comments_events') ... On the page I post a post, a comment to it, and I want to display the answers to the comments. Tell me how to correctly make GET "answr" in a view to display it in html? -
How to use a view to process different template in django
I would love to this in my project if it ever possible. I have a view like this class TrackUploadView(base.View): template_name = "track/uploadtrack.html" form_class = forms.TrackUploadForm trackdata = ['title', 'artist', 'genre', 'album', 'image', 'date'] def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) template_name = 'track/edittrack.html' form_edit = forms.TrackEditForm() datas = {} if form.is_valid(): audio_file = request.FILES['audio_file'] metadata = mutagen.File(audio_file, easy=True) audio = models.Track(audio_file=audio_file) audio.save() for field in self.trackdata: if metadata and metadata.get(field): data[field] = metadata.get(field) return render(request, template_name, {'form':form_edit,'data':data, ) return render(request, self.template_name, {'form':form}) on request==POST, I want it render another template for editing trackdata and another view will taking control of saving the data. Error i got! on submitting the data i got page not found! -
Jquery hide and django form widget
I'm using some jQuery code to hide and show a select in a form base on some circumstances. Everything it's fine, but I would like start the widget as hidden when the form is loaded the first time. The jQuery hide/show manipulate the style of the select. When is hidden: `display: hidden;' when is shown: 'display:block;'. Is there a way to change the attrs on the Django widget to add the `style="display: hidden;"? In the init of my form: self.fields['state'].widget.attrs.update({..}) Is possible to set the style using the attrs? -
Specifying quantity in django models OneToMany
I've been searching across the interwebs and can't seem to find a way to specify a quantity with django models ForeignKey field. For example, I want to create an apartment model and only want 4 tenant models to be associated with the apartment model. class apartmen(...): ... class tenant(...): tenants = ForeingKey(apartment, limit_choices_to ={(Only allow 4 per apartment model)} Any help is greatly appreciated. -
What is the best way to import a small sized MySQL Database to Django?
Schematics Image I have created a simple 5 table SQL Database for my family company. It consists of tables: Companies, CompanyDetails, Contacts, Continents, Products. I am focusing on making a frontend interface for displaying the Companies using drop-down menus for Type, Category, Country and/or Continent. Since, I already learned a bit of Python, I decided to use the Django framework to get it done. Now, I realize that importing a legacy DB using inspectDB is a non-trivial exercise in Django. Would it be a better/easier approach to just create a fresh model in Django and import csv s obtained from the database into it as there are only 5 tables in the first place? If yes, how do I do this in Django? -
ModelForm has no model class specified How can I connect model&form?
I got an error,ValueError at /accounts/upload_save/ ModelForm has no model class specified. I wrote in forms.py class UserImageForm(forms.ModelForm): owner = forms.CharField(max_length=20) image = forms.FileField() in models.py class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images', null=True, blank=True,) in views.py @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = UserImageForm() data.owner = forms.cleaned_data['user'] data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/accounts/photo.html', {'form': form}) in index.html <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> When I put SEND button, upload_save method is read.And my ideal system is image& user's data put in ImageAndUser model.What is wrong in my codes?How can I connect model&form? -
Cannot remedy :Reverse for 'password_reset_done' with arguments '()' and keyword arguments '{}' not found error
Though I have added the password_reset and password_reset_done module to the Identities/urls.py file, each time I click the Create new password link in my navigation bar I get this error : Reverse for 'password_reset_done' with arguments '()' and keyword arguments '{}' not found This is the link to my repository. If you have the time I would really appreciate the help. Thank you in advance. -
module 'importlib._bootstrap' has no attribute '_w_long'
I am trying to install django-adim-tools using pip, but this is what happens: C:\Users\hugo.villalobos>pip install django-admin-tools Could not import runpy module Traceback (most recent call last): File "C:\Python34\Lib\runpy.py", line 14, in <module> import importlib.machinery # importlib first so we can test #15386 via -m File "C:\Python34\Lib\importlib\__init__.py", line 34, in <module> _w_long = _bootstrap._w_long AttributeError: module 'importlib._bootstrap' has no attribute '_w_long' I have no idea how to proceed to solve it. Thanks for your help -
Django CBV: filter images to only service images
Rewriting the logic for django-jquery-file-upload and one particular feature needs to edited. It lists all Picture model saved instead would prefer if it lists all Pictures with the same user_service the model code is below as is for the view. I show how on form_valid i use service_id from a cookie. Last I remember from CBV there's another function like render_response class PictureCreateView(CreateView): model = Picture fields = "__all__" template_name = 'accounts/upload-file.html' def form_valid(self, form): self.object = form.save() user_service = self.request.COOKIES.get('service_id', None) if user_service: exists = UserService.objects.filter(id=user_service) if exists: service = exists[0] obj = self.object obj.user_service = service obj.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') model class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.FileField(upload_to="uploads") slug = models.SlugField(max_length=50, blank=True) user_service = models.ForeignKey(UserService, related_name="uploads", blank=True, null=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) … -
django - iterate between json response objects
I have a response object that I am receiving from an api call. The response has several objects that are returned in a single call. What I want to do is grab information from each of the objects returned and store them in varialbes to use them within the application. I know to grab info from a json response when it returns a single objects but I am getting confused with multiples objects... I know how to automate the iteration process through something like a forloop... it wont iterate. here is a sample response that I am getting: I want to grab the _id from both items. { 'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=..622d)", 'json':{ '_id':'..6e80', '_links':{ 'self':{ 'href':'https://uat-api.synapsefi.com/v3.1/users/..22d/nodes/..56e80' } }, 'allowed':'CREDIT-AND-DEBIT', 'client':{ 'id':'..26a34', 'name':'Charlie Brown LLC' }, 'extra':{ 'note':None, 'other':{ }, 'supp_id':'' }, 'info':{ 'account_num':'8902', 'address':'PO BOX 85139, RICHMOND, VA, US', 'balance':{ 'amount':'750.00', 'currency':'USD' }, 'bank_long_name':'CAPITAL ONE N.A.', 'bank_name':'CAPITAL ONE N.A.', 'class':'SAVINGS', 'match_info':{ 'email_match':'not_found', 'name_match':'not_found', 'phonenumber_match':'not_found' }, 'name_on_account':' ', 'nickname':'SynapsePay Test Savings Account - 8902', 'routing_num':'6110', 'type':'BUSINESS' }, <class 'synapse_pay_rest.models.nodes.ach_us_node.AchUsNode'>({ 'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=..622d)", 'json':{ '_id':'..56e83', '_links':{ 'self':{ 'href':'https://uat-api.synapsefi.com/v3.1/users/..d622d/nodes/..6e83' } }, 'allowed':'CREDIT-AND-DEBIT', 'client':{ 'id':'599378ec6aef1b0021026a34', 'name':'Charlie Brown LLC' }, 'extra':{ 'note':None, 'other':{ }, 'supp_id':'' }, 'info':{ 'account_num':'8901', 'address':'PO BOX 85139, RICHMOND, VA, US', 'balance':{ 'amount':'800.00', 'currency':'USD' … -
Couldn't find that app while using pg:copy in heroku
I am trying to migrate the data from my source-app "shielded-dusk-74543" to my target-app "safe-journey-99817" following the information in this link: https://devcenter.heroku.com/articles/upgrading-heroku-postgres-databases The link tell me to do the following command. (I already did the commands before this one, taking the standard-0 plan and putting in maintenance mode) heroku pg:copy source-application::OLIVE HEROKU_POSTGRESQL_PINK -a target- application ! WARNING: Destructive Action ! Transferring data from source-application::OLIVE to HEROKU_POSTGRESQL_PINK ! This command will affect the app: target-application ! To proceed, type "target-application" or re-run this command with -- confirm new-application Then I'll run this command from my target application it appears this error: heroku pg:copy source-application::shielded-dusk-74543 HEROKU_POSTGRESQL_MAROON_URL -a target-application ! Couldn't find that app. And sometimes doing the same thing appears this error: heroku pg:copy source-application::shielded-dusk-74543 HEROKU_POSTGRESQL_MAROON_URL -a target-application ! You do not have access to the app source-application. Both applications are in the same account and I am logged in the account. I did a new website and I want to migrate the information I added in the admin panel from the older website to the new one. Struggling with this problem during a week. -
How to display django form in modal window?
I saw this post, but it did not help me In the modal window, the form is not displayed. View: class CreateOrder(FormView): template_name = 'toner/add_order.html' form_class = OrderForm success_url = '/toner/' def form_valid(self, form): form.save() return super(CreateOrder, self).form_valid(form) add_order.html: <div id="order" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <div class="container txt-box"> <form action="{% url 'add_order' %}" role="form" method="post"> {% csrf_token %} {{ form.media }} {{ form.address }} {{ form.room }} {{ form.count }} <button class="btn btn-success" type="submit"> Done </button> </form> </div> </div> </div> </div> main_page.html: {% extends 'toner/base.html' %} {% block main_page %} .... <div> <button class="btn btn-primary" data-toggle="modal" data- target="#order"> Order </button> {% include "toner/add_order.html" %} </div> {% endblock %} urls: url(r'add_order/$', CreateOrder.as_view(), name='add_order'), If I go directly to the url (/add_order) it works. I can see the form. But from main_page.html the modal window is empty. Maybe someone has solved for themselves such a task? -
Angular 4 to Django REST image upload
i have a django REST API with a models.ImageField(), i can upload photos just fine from django itself, my problem is when im trying to do it from angular. .html <div class="form-group"> <label for="usr">Upload your new photo(Optional):</label> <input type="file" accept=".jpg,.png,.jpeg" (change)="attachFile($event)"> <br> <img src="{{imageSrc}}" height="250" weight="250" alt="Image preview..." /> </div> component.ts Update(form){ let body = { house: 3, photourl: this.imageSrc } console.log(this.imageSrc) this.http.Post('http://127.0.0.1:8000/api/photos', body).subscribe( res => console.log(res)) console.log(form) } attachFile(event) : void { var reader = new FileReader(); let _self = this; reader.onload = function(e) { _self.imageSrc = reader.result; }; reader.readAsDataURL(event.target.files[0]); } -
synapse login - 'str' has no attribute 'clinet' - django
I am working on a django project and I am trying to send a request to the synapse api to login to bank accounts through users login information. Within the api, the documentation says to pass a user id for the request and with the login information for the bank account. I am trying to send the request, but it is giving me the following error message. AttributeError at /login_synapse/ 'str' object has no attribute 'client' Request Method: POST Request URL: http://127.0.0.1:8000/login_synapse/ Django Version: 1.11.5 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'client' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/nodes/ach_us_node.py in create_via_bank_login, line 39 Here is what the documentation is showing that I need to pass: Path Params user_id: required string The user ID of the user you wish to add the ACH-US node under Body Params type: required string Type of node you wish to add. In this case its always ACH-US info.bank_id: required string User's online banking username info.bank_pw: required string User's online banking password info.bank_name: required string This is the bank_code (i.e. "capone" for Capital One) available at here This is the code that I have for the request: def authorizeLoginSynapse(request, form): currentUser = loggedInUser(request) currentProfile = Profile.objects.get(user …