Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django nginx getting csrf verification error in production over http
I've just deployed my django project on AWS with nginx. Everything works well except for when when I try to make any POST requests (over just http), I get the error: "Forbidden (403) CSRF verification failed. Request aborted." CSRF verification works if I run my server directly using Django which leads me to think that I did not set up my nginx.conf correctly. Can someone give some guidance as to how I can configure nginx to work with csrf? Here's my current config: #nginx.conf upstream django { # connect to this socket server unix:///tmp/uwsgi.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket } server { # the port your site will be served on listen 80; root /opt/apps/site-env/site; # the domain name it will serve for server_name mysite.org charset utf-8; #Max upload size client_max_body_size 75M; # adjust to taste location /media { alias /opt/apps/site-env/site/media; } location /static { alias /opt/apps/site-env/site/static; } location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; proxy_pass_header X-CSRFToken; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto http; proxy_set_header X-Real-IP $remote_addr; proxy_set_header HOST $http_host; proxy_set_header X-NginX-Proxy true; } } I've also turned off both SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE in my django settings. Thanks -
Upload and process a remote file called by an API REST call with a Django backend
The application is written in Django. I need to A) upload a file (an Excel spreadsheet) from a remote location (it could be via HTTP or SFTP), B) triggered by a signal/API call issued by a remote client. The file will be then processed (it could be synchronously or asynchronously) to update a database in the backend (this latter part is already working and is implemented with a file which is read locally). What is the best strategy, and tools to use to solve both points A) and B) above? -
Can't import rest_framework in Django
I'm trying to stand up a Django site and I am attempting to setup Report_builder with that. I just got the front end of report builder to work but it is not returning any data. I suspect the problem is with my rest framework. The settings did not auto create and now when I try to import it to create a serializer restframework is not recognized at all. Here is my settings page: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), } Did I possibly install rest framework in the wrong place or?? I have the latest version. -
Attribute error 'LoginForm' object has no attribute 'cleaned_data' where login is carried out by mail and password
views.py def login_view(request): form = LoginForm() if request.method == 'POST': user = form.authenticate_user() if not user: error(request, 'Wrong credentials!') return render_to_response('login.html') login(request, user) context = user.id return start(str(context)) return render_to_response('login.html', {'form': form}) models.py class User(AbstractBaseUser): phone = models.CharField(max_length=16, unique=True) age = models.PositiveIntegerField(blank=True, null=True) region = models.CharField(max_length=30, blank=True, null=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=30, unique=True) last_name = models.CharField(max_length=30, unique=True) USERNAME_FIELD = 'phone' objects = UserManager() forms.py class LoginForm(forms.Form): email = forms.CharField() password = forms.CharField( widget=forms.PasswordInput(render_value=False) ) def clean(self): user = self.authenticate_via_email() if not user: raise forms.ValidationError("Sorry, that login was invalid. Please try again.") else: self.user = user return self.cleaned_data def authenticate_user(self): return authenticate( email=self.cleaned_data['email'], password=self.cleaned_data['password'] ) def authenticate_via_email(self): """ Authenticate user using email. Returns user object if authenticated else None """ email = self.cleaned_data['email'] if email: try: user = User.objects.get(email__iexact=email) if user.check_password(self.cleaned_data['password']): return user except ObjectDoesNotExist: pass return None why it doesn't work? Message: AttributeError at /auth/ 'LoginForm' object has no attribute 'cleaned_data' Traceback: views.py in login_view user = form.authenticate_via_email() forms.py in authenticate_user email=self.cleaned_data['email'], -
Python Django Rest Framework UnorderedObjectListWarning
I upgraded from Django 1.10.4 to 1.11.1 and all of a sudden I'm getting a ton of these messages when I run my tests: lib/python3.5/site-packages/rest_framework/pagination.py:208: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <QuerySet [<Group: Requester>]> I've traced that back to the Django Pagination module: https://github.com/django/django/blob/master/django/core/paginator.py#L100 It seems to be related to my queryset code: return get_user_model().objects.filter(id=self.request.user.id) How can I find more details on this warning? It seems to be that I need to add a order_by(id) on the end of every filter, but I can't seem to find which code needs the order_by added (because the warning doesn't return a stack trace and so it happens randomly during my test run). Thanks! -
Django social_auth for facebook no longer working
I had social_auth set up with facebook log-in for a Django app. However, recently it stopped working (even though I made no changes to the code as far as I recall). Before it worked fine, but now when I try to log in I get the following error from the Django debug screen that results: Through some further debugging I realized that the "response" variable in the facebook.py file when running the auth_complete function was non-empty, but then the parsed_response variable does not parse the response correctly and thus ends up empty. Thus in the facebook.py file of the social authentication backend, I changed the following line of code: parsed_response = cgi.parse_qs(response) access_token = parsed_response['access_token'][0] if 'expires' in parsed_response: expires = parsed_response['expires'][0] To the following: import ast parsed_response = ast.literal_eval(response) access_token = parsed_response['access_token'] if 'expires' in parsed_response: expires = parsed_response['expires'] And it works! However, this seems like a hack to me. After scouring the web for people experiencing a similar problem with the social_auth login, I couldn't find any relevant posts. Similarly, it seems odd that it just stopped working all of a sudden as it was working this entire time. Thus, I feel like although this is a working … -
Django 1.11: Can't get ManyToManyField to work
I have the following models: class Address(models.Model): address1 = models.CharField(max_length=150, null=True) address2 = models.CharField(max_length=150, null=True, blank=True) city = models.CharField(max_length=50, null=True) state_province = models.CharField(max_length=50, null=True) zipcode = models.CharField(max_length=10, null=True) country = models.CharField(max_length=3, default='USA', null=False) created_at = models.DateTimeField(db_index=True, auto_now_add=True) updated_at = models.DateTimeField(db_index=True, auto_now=True) class Meta: db_table = 'addresses' and this one..... class User(models.Model, AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, max_length=150, unique=True, null=False) first_name = models.CharField(max_length=45, null=False) last_name = models.CharField(max_length=45, null=False) mobile_phone = models.CharField(max_length=12, null=True) profile_image = models.CharField(max_length=150, null=True) is_staff = models.BooleanField(db_index=True, null=False, default=False) is_active = models.BooleanField( _('active'), default=True, db_index=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) addresses = models.ManyToManyField(Address), USERNAME_FIELD = 'email' objects = MyCustomUserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email class Meta: db_table = 'users' My first mystery is that by migrating the models, there is no "addresses" field in the users table, nor a pivot table in the database to keep the multiple relationships. How are ManyToMany payloads kept?? Secondly, my goal is to have multiple addresses for Users. I want Users to have multiple "Addresses" (and not each address having one User) because other models can have addresses too. I don't want … -
Build a js alert
@staff_member_required @require_http_methods(['POST']) def fax_contract(request, pk=None): if request.is_ajax() and pk: print("Sending contract for request {}".format(pk)) try: contract = Contract.objects.get(pk=pk) _fax = contract.request.customer.compress_fax except Contract.DoesNotExist: return HttpResponseNotFound(_('Contract not found')) now = datetime.datetime.now() last_faxed = contract.request.last_faxed_at if last_faxed and (now - last_faxed) < settings.LOANWOLF_FAX_GRACE_TIME: return JsonResponse({ 'error': True, 'reload': False, 'message': _('Please wait at least %(minutes)d minutes to resend the contracts') % { 'minutes': settings.LOANWOLF_FAX_GRACE_TIME.seconds // 60}, }) else: if _fax: contract.request.last_faxed_at = datetime.datetime.now() contract.request.save() subject, msg = ('', '') try: result = send_mail(subject, msg, settings.LOANWOLF_FAX_EMAIL_FROM, [settings.LOANWOLF_FAX_EMAIL_TO.format(_fax)], fail_silently=False) return JsonResponse({ 'success': True, 'reload': True, 'result': result }) except Exception as exception: return JsonResponse({'error': True, 'message': str(exception)}) Here is the html code where I where the previous method : <div class="alert top white-text {{ object.state|request_state_color }}"> <i class="material-icons">info</i> <a href="{% url "contracts:fax" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 btn-process-request" data-turbolinks="false">{%trans "Fax contract" %}</a> {% if object.contract.pk %} <a href="{% url "contracts:as-pdf" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 workflow-bar-btn-spacer" data-turbolinks="false">{%trans "View contract" %}</a> {% endif %} <strong>{% trans "Once the signature is added to the request documents and approved, the deposit will be scheduled." %}</strong> </div> Here is the the class : $('.btn-process-request', node).bind('click', function(e){ e.preventDefault(); var data = {}; if … -
Django ManyToMany intermediary model, move relationship
So, after reading the documentation regarding intermediary model's, it seems that there's no built-in way of changing one side of a relationship without clearing all relationships with that side. But how can I do this anyway? I was thinking that I may have to store all of the relationships in an array / object so I can recreate them when needing to change 1 or more relations. My Models: Company Camera CompanyCameraRelationship I would want to change the relationship between Company 1 and Camera 1 to Company 1 and Camera 2. So in order to do this, I must clear all relationships between Company 1 and other Cameras? Any thoughts would be greatly appreciated! -
In Django 1.8, how can I set settings.py so that manage static files?
Code snippet managed static files in settings.py as follows. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [ os.path.join( os.path.dirname(__file__), 'static', ), ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR + '/templates/' ], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ], 'debug' : True }, }, ] STATIC_URL = '/static/' url.pyfile is as follows. from django.conf.urls import include, url from django.contrib import admin from tweets.views import Index, Profile admin.autodiscover() urlpatterns = [ url(r'^$', Index.as_view()), url(r'^admin/', include(admin.site.urls)), url(r'^user/(\w+)/$', Profile.as_view()), ] views.pyfile is as follows {% load staticfiles %} <html> <head> <title>Django</title> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" media="screen"> </head> <body> {% block content %} <h1 class="text-info">Hello {{name}}!</h1> {% endblock %} <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> </body> </html> When I run server, browser can't find bootstrap.min.js file. Page not found at /static/bootstrap/css/bootstrap.min.css http://localhost:8000/static/bootstrap/css/bootstrap.min.css 'bootstrap/css/bootstrap.min.css' could not be found It seems that the static files url is correct. But browser can't find the static files. Please tell me the reason and how can I handle it? -
Celery 4: How to write logs to syslog
I'm trying to send Celery's workers logs to SysLog. Somebody can help me how to achieve that? Thanks a lot! I tried with this text: http://oriolrius.cat/blog/2013/09/06/celery-logs-through-syslog/ But only logs the prints to syslog. Cant use getLogger of python. -
Fail to push to Heroku: /app/.heroku/python/bin/pip:No such file or directory
I am trying to push a Django project to Heroku, but it keeps telling me that the following: /app/.heroku/python/bin/pip: No such file or directory The complete error message is shown below. How can I address this issue? Do I need to first install pip on Heroku? Counting objects: 451, done. Delta compression using up to 8 threads. Compressing objects: 100% (383/383), done. Writing objects: 100% (451/451), 1.07 MiB | 349.00 KiB/s, done. Total 451 (delta 87), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.5.1 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: /app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51 /bin/steps/pip-install: line 5: /app/.heroku/python/bin/pip: No such file or directory remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to rocky-tor-70537. remote: To https://git.heroku.com/rocky-tor-70537.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/rocky-tor-70537.git' -
Django NullBooleanField - Why does 'Unknown' always default to "No" among "Unknown", "Yes" or "No" choices?
I have a model field that is a NullBooleanField with blank and null set to True. I'm calling this model in my ModelForm with default widgets. The form renders the NullBooleanField as a dropdown box with 3 values: Unknown, Yes and No. Choosing a Yes or No will set the field to their respective choices, but choosing Unknown also sets it to No. How do I make it so that choosing Unknown will result in the field being set to Null or None? This is my code: My models.py: Class ProductDetail(models.Model): in_stock = models.NullBooleanField(blank=True, null=True, default=None) quick_ship = models.NullBooleanField(blank=True, null=True, default=None) My Forms.py: class ProductMessageForm(ModelForm): class Meta: model = ProductDetail fields = ('in_stock','quick_ship') -
Which is better queuing or locking at that case?
Now If I have an otp authentication based on email or sms whatever but when +1k use my app , will it work efficient? Is the email client handles at least 100 request per second ?! if now what should I use ? Locking with deadlock avoidance or celery to queue another question the user should wait more than 30 seconds to recieve my email or sms to authenticate ?! -
'Image' object has no attribute '_committed'
I using Django 1.11 to write an application which takes an image upload by the user and receives the same image but flipped horizontally (using Pillow). In order to do this I made my model like: from django.db import models from django.db.models.signals import pre_save from django.utils.text import slugify # Create your models here. class Image_client(models.Model): """ Image_client has one Image and Slug, height_field and width_field are automatically filled. """ image = models.ImageField(null=True, blank=True, height_field='height_field', width_field='width_field') height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) slug = models.SlugField(unique=True) # better urls def create_slug(instance, new_slug=None): slug = slugify(str(instance.height_field) + str(instance.width_field)) if new_slug is not None: slug = new_slug qs = Image_client.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender=Image_client) views.py def new(request): """ Returns mirror image from client. """ if request.method == 'POST': form = ImageForm(request.POST or None, request.FILES or None) if form.is_valid(): formulaire = form.save(commit=False) image = Image.open(formulaire.image) image = ImageOps.mirror(image) formulaire.image = image formulaire.save() return redirect('img:detail', slug=formulaire.slug) else: form = ImageForm() return render(request, 'img/new_egami.html', {'form':form}) As you see in views.py, I'm trying to take the image from the form, flip it and then … -
Bootstrap mobile navbar dropdown is transparent
I have a Django-powered Bootstrap website. I'm using the theme Modern Business by Start Bootstrap. This is how it looks on the live sample: This is how it looks on my website (note the resources text below the logo): Here's my code for the navbar. {% load static from staticfiles %} <nav class="navbar fixed-top navbar-toggleable-md navbar-inverse bg-inverse"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarExample" aria-controls="navbarExample" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="container" style="height: 48px;"> <a class="navbar-brand" href="index.html"> <img src="{% static 'web/img/header-logo-2.png' %}" height="70px" style="height: 50px; position: absolute; top: 0;"></a> <div class="collapse navbar-collapse" id="navbarExample"> <ul class="navbar-nav ml-auto"> <!--<li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> About </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownPortfolio"> <a class="dropdown-item" href="">Board of Directors</a> <a class="dropdown-item" href="about-staff">Executive Administration</a> </div> </li>--> <!--<li class="nav-item"> <a class="nav-link" href="schools">Schools</a> </li>--> <!--<li class="nav-item"> <a class="nav-link" href="contact.html">Contact</a> </li>--> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownPortfolio" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Resources </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownPortfolio"> <a class="dropdown-item" href="https://www.dropbox.com/s/ngzaxhg4gqlibpx/2016-2017%20OCDL%20Charter.pdf?dl=0" target="_blank">League Charter</a> <a class="dropdown-item" href="https://www.dropbox.com/s/0nh1a93og93vqt0/OCDL%20Affidavit%202015-2016.pdf?dl=0" target="_blank">Student Agreement</a> <a class="dropdown-item" href="https://www.dropbox.com/s/en1t2ek23rxzxlj/OCDL%20Judges%20Affidavit.pdf?dl=0" target="_blank">Judge Agreement</a> <a class="dropdown-item" href="https://www.dropbox.com/s/lwxsnbpmc29vylq/OCDL%20Judge%20Guide-11-4-15.pdf?dl=0" target="_blank">Judge Guide</a> <a class="dropdown-item" href="https://www.dropbox.com/s/tkcvaggipfn91fi/Flow%20Chart%2C%20Orange%20County%20Debate%20League.docx?dl=0" target="_blank">Blank Flowchart</a> <a class="dropdown-item" href="https://www.dropbox.com/s/vphswry1d4rgm0d/Speaker%20Performance%20Rubric%2C%20Orange%20County%20Debate%20League.pdf?dl=0" target="_blank">OCDL Rubric</a> </div> </li> <!--<li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownBlog" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Blog </a> <div class="dropdown-menu … -
AttributeError: 'tuple' object has no attribute 'get'
I am trying to send a fax, and the way to do that is to send a mail with the function send_mail @staff_member_required @require_http_methods(['POST']) def fax_contract(request, pk=None): import ipdb; ipdb.set_trace() if request.is_ajax() and pk: print("Sending contract for request {}".format(pk)) try: contract = Contract.objects.get(pk=pk) except Contract.DoesNotExist: return HttpResponseNotFound(_('Contract not found')) now = datetime.datetime.now() last_faxed = contract.request.last_faxed_at if last_faxed and (now - last_faxed) < settings.LOANWOLF_FAX_GRACE_TIME: return JsonResponse({ 'error': True, 'reload': False, 'message': _('Please wait at least %(minutes)d minutes to resend the contracts') % { 'minutes': settings.LOANWOLF_FAX_GRACE_TIME.seconds // 60}, }) else: contract.request.last_faxed_at = datetime.datetime.now() contract.request.save() subject, msg = ('', '') try: result = send_mail(subject, msg, settings.LOANWOLF_FAX_EMAIL_FROM, [settings.LOANWOLF_FAX_EMAIL_TO.format(contract.request.customer.compress_fax)], fail_silently=False) return send_mail, JsonResponse({ 'success': True, 'reload': True, 'result': result }) except Exception as exception: return JsonResponse({'error': True, 'message': str(exception)}) Here is the html code where I where the previous method : <div class="alert top white-text {{ object.state|request_state_color }}"> <i class="material-icons">info</i> <a href="{% url "contracts:fax" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 btn-process-request" data-turbolinks="false">{%trans "Fax contract" %}</a> {% if object.contract.pk %} <a href="{% url "contracts:as-pdf" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 workflow-bar-btn-spacer" data-turbolinks="false">{%trans "View contract" %}</a> {% endif %} <strong>{% trans "Once the signature is added to the request documents and approved, the … -
How to serve a text file at root with Django
I got a site, say it's "www.site.com". I need to serve a text file at the root, so that "www.site.com/text.txt" will show up. I read through this answer: Django download a file, and I used the "download" function. However I am at a loss how to configure the URL. Can someone help me out? Say I put this this into my url.py, url('^(?P<path>.*)/$', san.views.FileDownload.as_view()), This then supersedes all my other url patterns and render them useless. How do I make this work? Thanks! -
Get ManyToMany through child of self referring model
Company Model: class Company(models.Model): class Meta: verbose_name_plural = "companies" name = models.CharField(max_length=30) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) cameras = models.ManyToManyField( Camera, through='CameraCompanyRelationship', through_fields=('company', 'camera'), ) def __str__(self): return 'Company: %s' % self.name def get_all_children(self, include_self=False): r = [] if include_self: r.append(self) for c in Company.objects.filter(parent=self): _r = c.get_all_children(include_self=True) if 0 < len(_r): r.extend(_r) return r Camera Model: class Camera(models.Model): name = models.CharField(max_length=30) model = models.CharField(max_length=30, default="Dummy") lat = models.FloatField(default=00.00) lng = models.FloatField(default=00.00) notify_offline = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name @property def last_log(self): return self.cameralog_set.last() view: def company_list(request): user = request.user user_company = user.company_id company = get_object_or_404(Company, pk=user_company) children = company.get_all_children() return render(request, 'owl/company_list.html', {'company': company, 'children': children}) Template chunk: <div class="row small-up-2"> {% for child in children %} <div class="column column-block"> <p>{{ child.name }}</p> <p>{{ child.id }}</p> {{ child.cameras }} <ul id="sortable" class="sortable connectedSortable" data-companyid="{{ child.id }}"> {% for camera in child.cameras.all %} <li class="ui-state-default" data-cameraid{{ camera.id }}>{{ camera.name }}</li> {% endfor %} </ul> </div> {% endfor %} </div> So, as you can see... I'm trying to get / display the cameras that belong to the children companies. If I use {{ company.cameras.all }} within the template, I get a proper QuerySet that … -
django enum field error when migrating
I'm using some enum fields in my data model. I've installed django-enumfield package. My django version is 1.10.6 and django-enumfield version is 1.2.1. Anyway I get the following error when db migration is issued. $ python manage.py makemigrations Output: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/Django-1.10.6-py3.5.egg/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/Django-1.10.6-py3.5.egg/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python3.5/dist-packages/Django-1.10.6-py3.5.egg/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/Django-1.10.6-py3.5.egg/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python3.5/dist-packages/Django-1.10.6-py3.5.egg/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/home/indikau/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/home/indikau/workspace/hotel_manager/manager/models.py", line 4, in <module> from django_enumfield import enum File "/usr/local/lib/python3.5/dist-packages/django_enumfield/enum.py", line 6, in <module> from django_enumfield.db.fields import EnumField File "/usr/local/lib/python3.5/dist-packages/django_enumfield/db/fields.py", line 8, in <module> class EnumField(six.with_metaclass(models.SubfieldBase, models.IntegerField)): AttributeError: module 'django.db.models' has no attribute 'SubfieldBase' Is there anyway to fix this problem? Thanks. -
Chemical formula parenthesis regex
I try to program a molar-mass-from-composition(chemical formula)-calculator with python using a regex. Molar-mass-calculators like the one from chempy or molmass.py by Gohlke both have problems with formulas like (Mg2(Si2O6))0.94 because they can't parse .94 after the parenthesis (or I'm blind). I found this regex (https://regex101.com/r/vE6nC7/1) which is almost perfect but has problems with formulas like (Mg2(Si2O6))0.94(Fe2(Si2O6))0.06 with two times double parenthesis (just (Fe2(Si2O6))0.06 works). It works if I substitute the outer parenthesis with []. There should be a nice regex for this problem with just multiple (), or? I played with regex101 but couldn't find something that works. Any help? greetings, philipp -
Django jquery file upload ... I am trying build a functionality to upload files but its not working I tried below code
enter image description here Above picture shows my code. I put all the required data in my code ..Jpg and jpeg is working fine but video files are not working -
pyplot crashing on plt.figure() in macOS
I repeatedly get RuntimeError: main thread is not in main loop when I call plt.figure(). This is in a charting function that creates charts based on user data in a django webapp. I've seen a warning on IDLE in python 3.4 that my version of Tcl/Tk may be unstable which links to http://www.python.org/download/mac/tcltk/ for more information, but this did not provide any guidance on how to determine what version I was running in a venv, or how to update the version in the venv. This error only happens in my mac OS environment. Not sure if I'm using matplotlib wrong, or if I need to update my environment. If I need to update, I have no idea how to go about this with a virtual environment. Code: def visualize(frictionloss): """ Input: an instance of a FrictionLoss model, Return: a bar chart of the losses in b64 encoded image """ # 6 bars ind = np.arange(6) width = .65 # load psi lost in each section to a bar to show losses1 = (frictionloss.ug_1_loss, frictionloss.ug_2_loss, frictionloss.riser_loss, frictionloss.bulk_main_loss, frictionloss.cross_main_loss, frictionloss.head_1_loss) # additionally, show each head loss to later stack on top losses2 = (0, 0, 0, 0, 0, frictionloss.head_2_loss) losses3 = (0, … -
Django survey with forms
I am building a survey tool and I'm wondering how would I continue with this or if my current solution is even the proper way to do it. Admin of the page may add or remove questions from questionnaires, so if I have understood it, I can't use ModelForms to handle the form data? A form may consist of 5 multichoice questions and 2 free text questions or any other amount of different types of questions so there isn't any fixed type of questionnaire How do I then save the values of the form as I do not have a model to use? Is this even possible to achieve without using a model for the form? Thank you for any input in advance. views.py from django.shortcuts import render from .models import Questionnaire, Question, Answer def index(request): all_questionnaires = Questionnaire.objects.all() all_questions = Question.objects.all() return render(request, 'questions/index.html', locals()) def questionnaire_detail(request, questionnaire_id): questionnaire = Questionnaire.objects.get(id=questionnaire_id) questions = Question.objects.filter(questionnaire=questionnaire) return render(request, 'questions/questionnaire.html', {'questionnaire': questionnaire, 'questions': questions}) def calculate(request): if request.method == 'POST': pass models.py from django.db import models MC = 'MC' CN = 'CN' TX = 'TX' CATEGORY = ( (MC, 'Multichoice'), (CN, 'Choose N'), (TX, 'Text'), ) VALYK = '1' VALKA = '2' … -
List Django urlpatterns in Sphinx docs
I'm using sphinx to document my django app. Using sphinx-apidoc I created documentation for the whole app application, but I need to add urlpatterns from app.urls to the documentation. Currently docs for this module contains only its name, and I want to add url regexes and corresponding views information. I'd appreciate any advice on how to do that.