Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.ProgrammingError: ya existe la columna «user_id» en la relación «django_admin_log»
I am currently developing a project in Django 2.0.2, but when migrating my models I get the following error: django.db.utils.ProgrammingError: ya existe la columna «user_id» en la relación «django_admin_log» This is all that the console shows: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\migration.py", line 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\base\schema.py", line 421, in add_field self.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\base\schema.py", line 117, in execute cursor.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\utils.py", line 89, in … -
How to organize REST-API versioning the right way?
I'm building a website's backend on Django-REST-FrameWork, and currently I have the following structure (below is only a part of it obviously): project_root: apps: app1: models.py serializers.py views.py urls.py app2: models.py serializers.py views.py urls.py urls: urls.py - (Main project urls file) An endpoints: http://localhost:8000/api/app1/ http://localhost:8000/api/app2/ How to add versioning ? should I just add an "v2" folder to each app ? -
No such file or directory: '/django_logs/documents_utils.log'
I pulled repository after two months and after a lot of changes, and after start project I met this problem, and don't know how to solve it. plz help me =( Unhandled exception in thread started by <function wrapper at 0x7f5d6c15d578> Traceback (most recent call last): File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/utils/log.py", line 71, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'utils_log_file': [Errno 2] No such file or directory: '/django_logs/documents_utils.log' UPDATE And there my settings.py file where in Loggins added this path, and path it's show location into server, and how and where I can add it to start my project local? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s path: %(pathname)s module: %(module)s method: %(funcName)s row: %(lineno)d message: %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, … -
ImportError: No module named modilabs.utils.subprocess_timeout
I use KoboToolbox and run KOBOCAT but it give the following Errors when I run manage.py.It works perfect on the port but it shows A server error occurred. Please contact the administrator. And it shows that it cannot import ProcessTimeout. Here is the the Error log: Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/management/base.py", line 82, in run_from_argv return super(CeleryCommand, self).run_from_argv(argv) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/management/base.py", line 75, in execute super(CeleryCommand, self).execute(*args, **options) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/management/commands/celeryd.py", line 25, in handle worker.run(**options) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/celery/bin/worker.py", line 212, in run state_db=self.node_format(state_db, hostname), **kwargs File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/celery/worker/__init__.py", line 95, in __init__ self.app.loader.init_worker() File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/celery/loaders/base.py", line 128, in init_worker self.import_default_modules() File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/loaders.py", line 141, in import_default_modules self.autodiscover() File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/loaders.py", line 144, in autodiscover self.task_modules.update(mod.__name__ for mod in autodiscover() or ()) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/loaders.py", line 179, in autodiscover for app in settings.INSTALLED_APPS]) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/loaders.py", line 203, in find_related_module return importlib.import_module('{0}.{1}'.format(app, related_name)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/sakib/d2WebApp/kobocat/onadata/apps/viewer/tasks.py", line 14, in <module> from onadata.libs.utils.logger_tools import mongo_sync_status, report_exception File "/home/sakib/d2WebApp/kobocat/onadata/libs/utils/logger_tools.py", line 28, in … -
load balancing in django
I have a Django server which responds to a call like this 127.0.0.1:8000/ao/. Before adding further applications to the server, I would like to experiment the load balancing which are supported by Django. Can anyone please explain how to implement load balancing. I spent sometime in understanding the architecture but was unable to find a solution. I work on Windows OS and I am new to servers. -
Day of Week Query with Timezone Enabled
Consider a simple DB Schema: Table XYZ: filter_datetime: DateTime field (With Timezone enabled) Now, if I want to find all XYZ rows where filter_datetime occurred on "Monday", that is doable if I ignore the Timezone. However, how do I query, if I do not want to ignore timezone information? Also, specifically for my case, I can make sure that filter_datetime would have the same timezone. However, once the table is populated, users should be able to query according to different Timezones and get correct results. (That is a user in UTC+6:00 would have different rows when he tries to get Monday rows as opposed to a user who have timezone in UTC-6:00) Bonus (Not really needed for me to accept the answer): Is it possible via Django ORM? -
Django - proper way to implement threaded comments
I'm currently developing a blog site using Django. I'm still a Django rookie so bare with me. My site will allow users to comment on any of my blog posts and also reply to each other and will be displayed using a 'threaded comments' structure (I haven't started user functionality yet, just comments). I've got the threaded comments to work properly using django-mptt (at least, for now), but I have NO CLUE if the route or steps I'm taking are in the right direction. Almost all the tutorials I've gone through only scratch the surface when it comes to comments and don't talk about threaded comments in django. I want some experienced/professional advice on what I might be doing wrong and what I could be doing better. Last thing I want is to find out there was a much more acceptable way of going about, after hours of work put in. So, here is a list of what I need clarity on: django-mptt: I chose this because I can afford slower write times. My site will have more reads than writes. Is this option okay for my case? Is there a better alternative I don't know about? What should I … -
How to create a clean url for user profile in django
I am building an application . One of the functionalities of this application is to display objects created by users to other users when they login .Lets call these objects created by users (x). Each of these objects displays the name of the user who created it . Bellow is my code of my view to display all objects created by users. def CreatedObjects(request): objects=Model-Class-Name.objects.all() # to display all users . users=User.objects.all() template_name="blabla.html" context={"objects":objects,"users":users} return render(request,template_name,context) my html file <div class="objects> <!--Display all available objects created by users--> {% for obj in objects %} <!--Display the name of the user who created object, with a link that will take you to user profile of this user --> <div class="user'> {% for user in users %} <a href="{% url 'app_namespace:url_name' user.pk %}">{{obj.user.username}} </div> {% endfor %} {% endfor %} <div> The userprofile link works ,but since i am using a for loop to loop through available users in the database ,the user name is displayed repeatedly . So my problem is how to avoid this .How can i create a userprfile link without for looping or how can i avoid the user name not to be displayed continuously on a single … -
How to do something after 2 days in django like deleting an object of a model
This is a model for all assignment taken by any user. How can I delete a particular instance of this when the user hasn't submitted his assignment in two days. After submission user data is saved in subassignment model. class UserAssignment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) assignment = models.ForeignKey(Assignment) time_taken = models.DateTimeField(auto_now_add=True) submitted = models.DateTimeField(null=True, blank = True) class SubAssignment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) assignment = models.ForeignKey(Assignment) time_submitted =models.DateTimeField(blank = True, null = True) score = models.IntegerField(default=0) -
How can I clear an image with Django Rest Framework?
I thought my problem was https://github.com/encode/django-rest-framework/issues/937 which should have been fixed by https://github.com/encode/django-rest-framework/pull/1003 but it appears, whether I send in None or empty string, DRF 3.7.7 isn't happy. class Part(models.Model): image = models.ImageField(null=True, blank=True) class PartSerializer(serializers.ModelSerializer): class Meta: model = Part fields = ('id', 'image') class PartDetail(generics.RetrieveUpdateAPIView): queryset = Part.objects.all() serializer_class = PartSerializer parser_classes = (MultiPartParser, FormParser) # put image, works fine with tempfile.NamedTemporaryFile(suffix='.jpg') as fp: image = Image.new('RGB', (100, 200)) image.save(fp) fp.seek(0) data = {'image': fp} self.client.put('/path/to/endpoint', data, format='multipart') # clear image, attempt #1 data = {'image': None} self.client.put('/path/to/endpoint', data, format='multipart') AssertionError: {'image': ['The submitted data was not a file. Check the encoding type on the form.']} # clear image, attempt #2 data = {'image': ''} self.client.put('/path/to/endpoint', data, format='multipart') AssertionError: <ImageFieldFile: None> is not None -
Trying to update two django forms at once
I am trying to use an UpdateView in Django to update two forms simultaneously. I have the get method working properly, but when I submit the update, the post method creates a new instance of the forms. How can I grab the forms from the get method and update them without creating a new instance? Everything is redirecting fine and I am getting no errors. class MotionStudyInstanceUpdateView(UpdateView): model = MotionStudyInstance fields = ['height', 'weight', 'skin_type_score', 'fitzpatrick_skin_type'] template_name = 'data/motionstudyinstance_update.html' success_url = reverse_lazy('data:motion-studies') def get_context_data(self, **kwargs): pass def get(self, request, **kwargs): pk = self.kwargs['pk'] item = MotionStudyInstance.objects.get(id=pk) general_info = item.general_info form = MotionStudyInstanceForm( initial={'height': item.height, 'weight': item.weight, 'skin_type_score': item.skin_type_score, 'fitzpatrick_skin_type': item.fitzpatrick_skin_type}) form_two = GeneralInfoForm(initial={'case_report_form_number': general_info.case_report_form_number, 'form_type': general_info.form_type, 'study_start_date': general_info.study_start_date, 'signed_consent': general_info.signed_consent, 'gender': general_info.gender, 'miscellaneous_notes': general_info.miscellaneous_notes, 'adverse_events': general_info.adverse_events}) return render(request, self.template_name, {'form': form, 'foreign_form': form_two}) def post(self, request, **kwargs): if request.method == 'POST': form = MotionStudyInstanceForm(request.POST) foreign_form = GeneralInfoForm(request.POST) if form.is_valid() and foreign_form.is_valid(): general_info = foreign_form.save() user_form = form.save(commit=False) user_form.general_info = general_info user_form.save() return redirect('data:motion-studies') else: form = MotionStudyInstanceForm() return render(request, self.template_name, {'form': form}) -
Trying to run a web app using Django REST framework as a backend and getting error message after "./manage.py migrate"?
I'm having trouble building a project that uses React as a frontend and the Django Rest framework as a backend (Django/Python is new to me). I'm following the build instructions on the README.md This is exactly what I did: git clone https://github.com/glenstarchman/itcc.git cd itcc git checkout development cd backend virtualenv -p python3.6 ./venv source ./venv/bin/activate pip3 install -r requirements.txt createuser itcc createdb -O itcc -E UTF-8 itcc ./manage.py migrate after running that last (10th) command, I get this error message: Traceback (most recent call last): [....] from ..models.locations import Location ModuleNotFoundError: No module named 'api.models.locations' Any ideas on how to make this error message go away? Thanks in advance! -
what is the regex for 2 float sign valuable in django?
I am new in Django 3 and python I want to set a regex for in urls.py and this address is all I want : www.example.com/map/?Latitude=x&longitude=y I need this 2 parameters x, y in request , these are float numbers, some thing like this : www.example.com/map/?Latitude=123.6666789&longitude=-3.67955408 but I need the value of Latitude , longitude in request at views it is my default : path('map/?Latitude=x&longitude=y, views.map) thanks -
How to serve dynamic DB based video in Django
I've been battling with serving videos directly from the DB, I have a database containing video link but I can't seem to play the video even when I copy the full path to a filepath model field. Am relatively new to Django and any help on how to do this is appreciated. -
Python Social Auth, Google, and refresh token
In a personal project, I am trying to use Django as my front end and then allow data entered by users in a particular form to be copied to google sheets. Google's own docs recommend using https://github.com/google/oauth2client which is now deprecated, and the docs have not been updated. With this, I have started attempting to use Python Social Auth and Gspread. For Gspread to be able to function correctly, I need to be able to pass it not only an access token but also a refresh token. Python Social Auth however is not persisting the refresh token along with the rest of the "extra data". Looking at the data preserved and the URLs routed to, it seems to me more like somewhere it is routing through Google+. I have the following configurations in my Django settings files: AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.associate_by_email', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/spreadsheets'] Is there a better way to access a google sheet? Am I correct that PSA or google is redirecting me into a Google+ auth flow instead of the Google Oauth2? If not, what must change … -
is there a way to use Pytion3, django2.0.2 and MySql together on ubuntu?
I searched alot to install python3.6 and django2.0.2 with MySql server, but I got nothing because django2.0.2 framework doesn't support MySqldb yet. -
Djando ManagementForm error when using custom intermediate page and changeform_view()
I'm using changeform_view to catch saves and only add an intermediate page conditionally. Inside the admin class I have: @csrf_protect_m @transaction.atomic def changeform_view(self, request, object_id=None, form_url='', extra_context=None): survey = Survey.objects.get(pk=object_id) check_against = ['incomplete', 'submitted', 'completed'] if not request.POST.get('confirmed'): if request.method == 'POST' and survey.status == 'in-market' and any(s in request.POST.get('status') for s in check_against): context = { 'title': _('Change in-market survey?'), 'is_popup': False, 'opts': self.model._meta, 'app_label': self.model._meta.app_label, 'object': survey, } return TemplateResponse( request, 'admin/survey/status_from_inmarket_confirmation.html', context) return super(SurveyAdmin, self).changeform_view(request, object_id, form_url, extra_context) My template looks like: {% extends "admin/base_site.html" %} {% load i18n admin_urls %} {% block breadcrumbs %} <div id="grp-context-navigation"> <nav id="grp-breadcrumbs" class=""> <header style="display:none"><h1>Breadcrumbs</h1></header> <ul> <li><a href="{% url 'admin:index' %}">{% trans 'Home' %}</a></li> <li><a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ app_label|capfirst }}</a></li> <li><a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst|escape }}</a></li> <li><a href="{% url opts|admin_urlname:'change' object.pk|admin_urlquote %}">{{ object|truncatewords:"18" }}</a></li> <li>{% trans 'Make Live' %}</li> </ul> </nav> </div> {% endblock %} {% block content %} {% if not perms_lacking and not protected %} <p>{% blocktrans with escaped_object=object %}Are you sure you want to switch this status {{ object_name }} "{{ escaped_object }}"?{% endblocktrans %}</p> <form action="" method="post">{% csrf_token %} <div> <input type="hidden" name="confirmed" value="yes" /> <input type="submit" value="{% trans "Yes, I'm sure" %}" … -
Opengraph tags (og:tags) in Django template not scraped by Facebook
I've been trying to get opengraph tags work for my django website. I use "www.somewebsite.com" as website url during this question. I used the following static code in the header: <meta property="og:title" content="websitename" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://www.somewebsite.com/" /> <meta property="og:description" content="Some description."/> <meta property="og:image" content="https://www.somewebsite.com/static/image.png" /> This did not work, so I've installed django-meta (http://django-meta.readthedocs.io/en/latest/installation.html) and implemented the following code at my landing page view, so the meta data is added dynamically on the server: # basic page view class BasicView(View): template_name = 'landing/landing.html' # get request def get(self, request): context = { "meta": Meta( title="Websitename", description='Some description.', type='website', url='https://www.somewebsite.com/', image='https://www.somewebsite.com/static/image.png', use_title_tag=True, use_facebook=True, use_og=True, ), } return render(request, self.template_name, context) With the following template: <head {% meta_namespaces %}> {% include 'meta/meta.html' %} </head> This results in: <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#"> <meta name="description" content="Some description."> <title>Websitename</title> <meta property="og:title" content="Websitename"> <meta property="og:url" content="https://www.somewebsite.com/"> <meta property="og:description" content="The easiest way of making digital music."> <meta property="og:image" content="https://www.judgemysound.com/static/image.png"> </head> When fetching new scrape information in the facebook debugger tool (https://developers.facebook.com/tools/debug/og/object/) it gives the following information (image): Meta data scraped from my website with facebook sharing debugger The strange thing is; The information which are in my og tags are not … -
How to name python function by seeing the code
Recently I have been playing with some python code. I am trying to name the function by seeing the code. what would be the possible or proper name to function "h" in the code below. import functools from tasks.models import Task, TaskStatus from tasks.exceptions import DuplicateExecution def h(func): @functools.wraps(func) def wrapped(*args, **kwargs): if Task.objects.filter( status_id=TaskStatus.STARTED task_type=kwargs['task_type'} ).count() > 0: raise DuplicateExecution( "cannot run more than one {} task simultaneously" .format(kwargs['task_type'])) return func(*args, **kwargs) return wrapped -
How to serve WSGI Django app under Apache mod-alias directive
I have a website like mydomain.com in PHP, served under Apache. Now I'd like to add a Python-Django app under a specific URL: mydomain.com //PHP mydomain.com/about //PHP mydomain.com/python-app //PYTHON In Apache and PHP I normally use mod_alias for this kind of task: <Virtualhost *:80> ServerName mydomain.com ... Alias /another-app /var/www/another-app #PHP </Virtualhost> Using Python I need to use mod_wsgi, adding additional parameters like: Alias /static /var/www/py_app/static WSGIDaemonProcess py_app python-home=/home/user/.virtualenvs/py_app python-path=/var/www/py_app WSGIProcessGroup py_app How can I scope that directives under my alias? I'd need a vhost scoped to a specific url or something like this: <Alias /python-app> Alias /static /var/www/py_app/static #use this alias only if in that sub-url ... WSGI DIRECTIVES ... </Alias> I hope to have clarified the problem (a Python app under an Apache alias with scoped settings), how can I accomplish that? Thank you, Francesco -
Searching for keywords and creating links automatically in Django
I am creating an information web application (in Django) that often uses some medical terms. The medical terms and their explanations are stored in a separate model/database. As of now, I am manually creating links to description pages for each medical term. I was wondering if there is a way to get the code automatically search a page contents for medical terms, and automatically create links (or popovers) to their description pages. All the pages are dynamic, and the medical terms are stored in their own separate model. So far, the medical terms model does not have a relationship with any other models Any thoughts if this can be done, and if so, how to go about it? Thanks for your time and assistance. -
opencv error file cannot be opened for reading cv::face::FaceRecognizer::read windows
i have been trying to run a django application (attendance system with face recognition). i'm using python with opencv=3.2 and after installing both opencv-python and opencv-contrib-python using pip on anaconda framework ,i still get error like this "opencv error file cannot be opened for reading cv::face::FaceRecognizer::read". file c:\projects\opencv-python\opencv_contrib\modules\face\src\facerec.cpp line 61. i'm new to using opencv and django so any suggentions are welcome -
django-rules Row-Level Permissions on a Model
I have a django project with two models: class Project(models.Model): name = models.CharField(primary_key=True, max_length=12) team = models.CharField(max_length=10) class Task(models.Model): name = models.CharField(max_length=10) project = models.ForeignKey(Project) I would like to control which rows in these models each user can access. My groups in auth_group correspond to team in the Project model. How would I use django-rules to restrict user access to Task rows based on Project team? Let's say there is Team X, and John Smith has been placed in group Team X. How should django-rules be used to only allow John Smith to see tasks that are tied to projects for Team X? I'm not sure how to access Team in order to compare it to the groups the user is a part of. Unsure to the point where I don't have any workable code to show for it. -
NoReverseMatch at /accounts/password/reset/ django registration redux
I'm trying to use django-registration-redux for my authentication in my project, but when testing out the password reset, I come up with an error containing the following traceback Internal Server Error: /accounts/password/reset/ Traceback (most recent call last): File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/views.py", line 418, in dispatch return super(PasswordResetView, self).dispatch(*args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/edit.py", line 183, in post return self.form_valid(form) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/views.py", line 431, in form_valid form.save(**opts) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 289, in save email, html_email_template_name=html_email_template_name, File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 236, in send_mail body = loader.render_to_string(email_template_name, context) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/loader.py", line 68, in render_to_string return template.render(context, request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/base.py", line 207, in render return self._render(context) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit … -
Ajax Django Cart Not Displaying Data Correctly
I am working on a Django Ajax cart where I am stuck with JS to add the products to the cart. I think I have the Ajax part broadly working but it seems to add/remove multiple items in one go. The bit I am struggling with is one the $.each section. For instance if am adding a particular item to the cart it will re-add everything already in the cart. $(document).ready(function(){ var productForm = $(".form-product-ajax") // #form-product-ajax productForm.submit(function(event){ event.preventDefault(); // console.log("Form is not sending") var thisForm = $(this) //var actionEndpoint = thisForm.attr("action"); var actionEndpoint = thisForm.attr("data-endpoint"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function(data){ var submitSpan = thisForm.find(".submit-span") if (data.added){ submitSpan.html("In cart <button type='submit' class='btn btn-link'>Remove?</button>") } else { submitSpan.html("<button type='submit' class='btn btn-success'>Add to cart</button>") } var currentPath = window.location.href if (currentPath.indexOf("") != -1) { refreshCart() } }, error: function(errorData){ console.log("error") console.log(errorData) } }) }) function refreshCart(){ console.log("in current cart") var cartTable = $(".cart-table") var cartBody = cartTable.find(".cart-body") var productRows = cartBody.find(".cart-product") var currentUrl = window.location.href var refreshCartUrl = '/api/cart/' var refreshCartMethod = "GET"; var data = {}; $.ajax ({ url: refreshCartUrl, method: refreshCartMethod, data: data, success: function(data) { console.log("success") console.log(data) …