Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Microservices with shared database? using multiple ORM's?
I'm learning about microservices and im gonna build a proyect with a microservices arquitecture. The thing is, one of my team mates want to use one database for all services, sharing all tables so "data doesnt get repeated", each service would be built with differente frameworks and lenguages like django and rails, wich use very different ORM standards. What would be the correct aproach? since i think working with one database would involve a lot of "hacking" the orms in order to make them work correctly. -
Local field 'created_at' in class 'Attachment' clashes with field of similar name from base class 'Timestampable'
I have the following two models: class Timestampable(models.Model): created_at = models.DateTimeField(null=True, default=None) updated_at = models.DateTimeField(null=True, default=None) class Meta: abstract = True def save(self, *args, **kwargs): now = timezone.now() if not self.created_at: self.created_at = now self.updated_at = now super(Timestampable, self).save(*args, **kwargs) class Attachment(Timestampable, models.Model): uuid = models.CharField(max_length=64, unique=True) customer = models.CharField(max_length=64) user = models.CharField(max_length=64) file = models.FileField(upload_to=upload_to) filename = models.CharField(max_length=255) mime = models.CharField(max_length=255) publicly_accessible = models.BooleanField(default=False) When I try to migrate these models, I get the following error: django.core.exceptions.FieldError: Local field 'created_at' in class 'Attachment' clashes with field of similar name from base class 'Timestampable' I read here, here, and here that this should work when the base class is abstract. However, I marked it as abstract it still it doesn't seem to work. What else could be wrong? I am using Django 1.8.14. -
Django: Bokeh.safely is not a function
I was trying to embed a bokeh plot into my django app. I followed the instructions given here and here. I am getting the following error on my browser console and not getting any plot output: Uncaught TypeError: Bokeh.safely is not a function at HTMLDocument.fn (localhost/:15) I am not a JS guy but Bokeh.safely is present in the script generated by Bokeh. I have attached the script generated at the end: My views.py file: from django.shortcuts import render from bokeh.plotting import figure from bokeh.resources import CDN from bokeh.embed import components def showGraph(request): arr = [1,4,9,16,25,36] y = [1,2,3,4,5,6] plot = figure() plot.line(arr, y) script, div = components(plot, CDN) return render(request, "data_collection/simple_chart.html", {"script": script, "div": div}) simplechart.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Bokeh example</title> <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.css"> <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.js"></script> {{ script | safe }} </head> <body> {{ div | safe }} </body> </html> Script generated by bokeh: (function(){ var fn = function(){ Bokeh.safely(function(){ var docs_json = {....json.....}; var render_items = [ {"docid": "27fe9292-3142-4617-b273-f9d932e47df3", "elementid": "7b2ef36e-a7d2-4a6b-88e6-186edecde6ca", "modelid": "741db3b0-26ce-45c1-86b4-d95394c7331f"}]; Bokeh.embed.embed_items(docs_json, render_items); }); }; if (document.readyState != "loading") fn(); else document.addEventListener("DOMContentLoaded", fn); })(); -
Serving Django CMS Admin Styles in Production with Apache
I made a simple site using Django CMS. Everything seems to work, except for the styles on the admin toolbar. They are not loading. What should I do to configure the app or server to serve them properly? Here is the settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'some secret here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'aldryn_bootstrap3', 'parler', 'aldryn_apphooks_config', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', 'aldryn_people', 'aldryn_reversion', 'aldryn_translation_tools', 'sortedm2m', 'taggit', 'reversion', 'aldryn_boilerplates', 'absolute', 'aldryn_forms', 'aldryn_forms.contrib.email_notifications', 'captcha', 'emailit', ) MIDDLEWARE_CLASSES = ( 'cms.middleware.utils.ApphookReloadMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ) ROOT_URLCONF = 'iboyko.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, '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', 'sekizai.context_processors.sekizai', 'cms.context_processors.cms_settings', ], }, }, ] WSGI_APPLICATION = 'app_name.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': … -
Install mysqlclient for Django Python on Mac OS X Sierra
I have already installed Python 2.7.13 Django 1.11 MySQL 5.7.17 I want use MySQL with Django, but after install mysql connector I was try to install mysqlclient for Python on $ pip install mysqlclient, but I have this issue: Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/y_/c31n_1v12v169zfv829p_v_80000gn/T/pip-build-f51KhW/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 54, in get_config libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "setup_posix.py", line 12, in dequote if s[0] in "\"'" and s[0] == s[-1]: IndexError: string index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/y_/c31n_1v12v169zfv829p_v_80000gn/T/pip-build-f51KhW/mysqlclient/ -
duplicate key value violates unique constraint "wagtailcore_page_path_key" DETAIL: Key (path)=(0001) already exists
I am working on a system that has been developed by someone else based on Django and wagtail. I managed to import data to postgresql but I believe not everything was imported since I get an error when I try to migrate data. Here is the error I get: # python manage.py migrate /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/treebeard/mp_tree.py:102: RemovedInDjango18Warning: `MP_NodeManager.get_query_set` method should be renamed `get_queryset`. class MP_NodeManager(models.Manager): /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/django/forms/widgets.py:143: RemovedInDjango18Warning: `TaskMonitor.queryset` method should be renamed `get_queryset`. .__new__(mcs, name, bases, attrs)) /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/djcelery/loaders.py:192: UserWarning: Autodiscover: Error importing sauti_mtaani.apps.core.app.CoreConfig.tasks: ImportError('No module named CoreConfig',) app, related_name, exc, /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/djcelery/loaders.py:192: UserWarning: Autodiscover: Error importing sauti_mtaani.apps.sauti_mtaani_main.app.SautiMtaaniMainConfig.tasks: ImportError('No module named SautiMtaaniMainConfig',) app, related_name, exc, /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/djcelery/admin.py:256: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form PeriodicTaskForm needs updating class PeriodicTaskForm(forms.ModelForm): /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/django/forms/widgets.py:143: RemovedInDjango18Warning: `PeriodicTaskAdmin.queryset` method should be renamed `get_queryset`. .__new__(mcs, name, bases, attrs)) Operations to perform: Synchronize unmigrated apps: wagtailsnippets, compressor, modelcluster, djcelery, django_extensions Apply all migrations: core, wagtailusers, wagtailembeds, wagtailadmin, sauti_mtaani_main, sessions, admin, polls, auth, wagtailcore, contenttypes, wagtaildocs, taggit, wagtailsearch, wagtailforms, wagtailredirects, wagtailimages Synchronizing apps without migrations: Creating tables... Installing custom SQL... Installing indexes... Running migrations: Applying wagtailcore.0002_initial_data...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() … -
DRF, caching for as_view()?
In my view, I often use APIView's as_view() to generate json. I'd like to cache the response and tried the following but it won't work def some_complex_view(self, request, *args, **kwargs): pass @method_decorator(cache_page(60, key_prefix='drf')) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) Then, I call MyViewSet.as_view({'get': 'some_complex_view'})(request, format='json') It correctly caches when I request the view using browser, but it won't when using as_view() -
Django-Javascript Modal form validation
I have form in django, which accepts number between 1 and 6 (option list) and multiple image files. The form is modal, so I cannot pass in any errors with Django, because modal closes on refresh. Is there any possibility to validate form using javascript? The form has to be validated in the database- in views.py i have to check if model with this number already exists. I have this code: <!-- Modal --> <div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel"> Add </h4> </div> <!-- Modal Body --> <div class="modal-body"> <form id="form" class="form-horizontal" role="form" method="post" enctype="multipart/form-data" action="{% url 'create_exam' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}" id="post-form"> {% csrf_token %} <div class="form-group"> <label class="col-sm-2 control-label" for="inputEmail3">Number</label> <div class="col-sm-10"> <select class="form-control" id="exam_number" name="exam_number"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> <div class="form-group"> <label class="col-xs-2 control-label" for="inputPassword3" >Image</label><br> <div class="col-sm-10"> <input name="exam_file" type="file" accept="image/*" multiple required> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> </div> </div> </div> <!-- Modal Footer --> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> Close </button> <button type="submit" class="btn btn-primary" id="form-submit"> Add </button> </div> </form> </div> </div> … -
Dynamically generated form choices in Django
I have a form for submitting new articles in Django, in this form you're allowed to place the post into a 'user_group', just a many many relationship between groups and users. However, you're only allowed to add it into groups you belong to. Using the init function of the form class i can pass in an extra field, and I do get the correct choices I need, however on submit I get an error ''QueryDict' object has no attribute 'all'' I'm not sure whats going wrong, heres my form: class PostForm(BaseModelForm): new_image = forms.ImageField(required=False) #GROUPS = user.groups.all() #group = forms.ChoiceField(choices=GROUPS, required=False ) def __init__(self,groups, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['group'].queryset = groups class Meta: model = Post fields = ('title','category', 'group', 'text', 'description', 'style') help_texts = { 'group': _('Do you want this published under your account or a group?') } and heres the view where the error is being thrown: @login_required def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(groups=request.user.user_groups.all()) return render(request, 'blog/post_edit.html', {'form': form}) This line: form = PostForm(groups=request.user.user_groups.all()) Is where I pass in the choices for groups, which does give you … -
Django 1.7 dumpdata on Windows scrambles unicode characters
I use manage.py dumpdata --format xml --some-more-parameters to export a full dump of the database to xml. The database is MS sql server and I'm using pyodbc as the driver. The dumpdata command is run using PowerShell and since Django 1.7 does not support a --output argument for the dumpdata command I redirect the output into a file using PowerShell. Unfortunately the database contains unicode characters (e.g. country \xd6sterreich) and these characters are scrambled int the export file. Here's what didn't work: ./manage.py dumpdata --format xml > export.xml ./manage.py dumpdata --format xml | out-file -encoding utf8 export.xml ./manage.py dumpdata -format xml | out-file -encoding ANY_OTHER_SUPPORTED_ENCODING export.xml None of these commands work. Umlauts and accents are scrambled and additionally the > export.xml method adds an invalid BOM to the file which will result in ./manage.py loaddata export.xml aborting with an error message when I try to import this on another host. Any suggestions on how I could export the data and preserve the special characters? The same problem exists when using the json or yaml serializers. -
How to disable checkboxes in MultipleChoiceField?
I use MultipleChoiceField in form. It shows me REQUIREMENTS_CHOICES list with checkboxes where user can select and add new requirements to database. Is it possible to disable checkboxes (in my case requirements) which is already in the database? Lets say I have A and C in database so I dont need them. First value in tulpe is symbol of requirement, second value is the name of requirement. models.py: class Requirement(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) forms.py: REQUIREMENTS_CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ('D', 'Name D'), ) class RequirementAddForm(forms.ModelForm): symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=GROUP_REQUIREMENTS_CHOICES,) class Meta: model = Requirement fields = ('symbol',) -
Django - Serve files for download
I have a collection of documents(.pptx files) that I wish to make available for download to users. I am using django for this purpose. I have some parts figured out using these links: having-django-serve-downloadable-files The problem I am facing is in connecting these parts. Relevant code pieces- settings.py file MEDIA_ROOT = PROJECT_DIR.parent.child('media') MEDIA_URL = '/media/' The html template. The variable slide_loc has the file location (ex: path/to/file/filename.pptx) <div class = 'project_data slide_loc'> <a href = "{{ MEDIA_URL }}{{ slide_loc }}">Download </a> </div> The views.py file def doc_dwnldr(request, file_path, original_filename): fp = open(file_path, 'rb') response = HttpResponse(fp.read()) fp.close() type, encoding = mimetypes.guess_type(original_filename) if type is None: type = 'application/octet-stream' response['Content-Type'] = type response['Content-Length'] = str(os.stat(file_path).st_size) if encoding is not None: response['Content-Encoding'] = encoding # To inspect details for the below code, see http://greenbytes.de/tech/tc2231/ if u'WebKit' in request.META['HTTP_USER_AGENT']: # Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly. filename_header = 'filename=%s' % original_filename.encode('utf-8') elif u'MSIE' in request.META['HTTP_USER_AGENT']: # IE does not support internationalized filename at all. # It can only recognize internationalized URL, so we do the trick via routing rules. filename_header = '' else: # For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers). filename_header = 'filename*=UTF-8\'\'%s' … -
How to handle Referer in https post reuest in ionic app with backend django?
I am new to ionic development.I am developing an ionic app with backend django. I have write code for login and signup in django project and I deploy the app into heroku.the django app heroku url working fine. CSRFtoken settings: angular.module('starter.controllers', ['ngCookies']) .config(['$httpProvider', function($httpProvider ) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }]) For login code: $scope.doLogin = function(){ console.log($scope.loginData); $http({ method: 'POST', url: 'https://django-ionic-api-app.herokuapp.com/api/login/', data: $scope.loginData, dataType: "json" }).then(function successCallback(response) { console.log(response); if(response.statusText == "OK"){ alert("User login successfully!!"); window.localStorage['userdetails'] = JSON.stringify(response.data.user); $scope.userdetails = JSON.parse(window.localStorage['userdetails']); window.location.href = $state.href('app.home'); window.location.reload(); } },function errorCallback(response) { console.log(response) alert(response.data.message) }); }; In web browser, login and signup working good. But when I bulid an apk and test it in mobile, first time login successful but second time getting below error {"detail":"CSRF Failed: Referer checking failed - no Referer."} I have checked with cross origin headers, but I am getting same error. I think I need to handle this Referer error from ionic? but I don't know how to handle this from angularjs(ionic1). Please help me anyone,Thank you. -
Django admin - custom permissions
The problem is simple. I have a 'cars' application. I want to create a user in admin and give him access to admin, but in such a way that user only sees cars app. This part is easy, I can select permissions for view, delete, etc... And only the cars that user himself created through admin. This is what I don't see enabled buy default in admin UI, so I guess I would need to add something to cars/admin.py to show only certain cars if the user belongs to a certain group. -
ValueError: invalid literal for int() with base 10(Django)
error in cmd Code I tried to create a project where to manage a garage, but when I create the model in application"utiliser", I got this problem. Thanks! -
Calling a Stored Procedure using django-mssql
I'm trying to call a stored procedure on a multi-database project I am working with. I have 2 of my stored procedures working, but this particular stored procedure is not working and returns an error: Traceback (most recent call last): File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\rest_framework\views.py", line 483, in dispatch response = self.handle_exception(exc) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\rest_framework\views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\rest_framework\views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "d:\Projects\Django\HRSys\hrs\hrs_api\views.py", line 79, in post result_set = cursor.fetchall() File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\db\utils.py", line 101, in inner return func(*args, **kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\django\db\utils.py", line 101, in inner return func(*args, **kwargs) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\sqlserver_ado\dbapi.py", line 719, in fetchall return self._fetch() File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\sqlserver_ado\dbapi.py", line 671, in _fetch self._raiseCursorError(FetchFailedError, 'Attempting to fetch from a closed connection or empty record set') File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\sqlserver_ado\dbapi.py", line 488, in _raiseCursorError eh(self.connection, self, errorclass, errorvalue) File "d:\Projects\Django\AAAVirtualEnv\lib\site-packages\sqlserver_ado\dbapi.py", line 103, … -
Getting 502 Bad Gateway while running the Django application within a docker container?
Those are the following steps I am following to run my application within a docker container . docker run -i -t -d -p 8000:8000 c4ba9ec8e613 /bin/bash docker attach c4ba9ec8e613 my start up script : #!/bin/bash #activate virtual env echo Activate vitualenv. source /home/my_env/bin/activate #restart nginx echo Restarting Nginx service nginx restart # Start Gunicorn processes echo Starting Gunicorn. gunicorn OPC.wsgi:application --bind=0.0.0.0:800 --daemon This setup is working fine in the local machine but not working within the docker . -
Django migrating from MySql to Postgres fails user authentication
I changed the database from MySQL to Postgres. after migrating all data password checking fails. I am using AWS RDS, Is this because of Postgres peer authentication? and if so how can I fix it. -
How to get List from Django Model (instead of Map of fields)
I have a Model called Patient. In this table I have a field:id and condition. So, If I want to get the ids given the condition, I can use this following syntax. ids = list(Patient.objects.filter(condition='sick').values(id)) So the ids will contains a list of map: ids = [{id: 123}, {id=345}, ...] However, instead of map, I want to simply get the list like shown below: ids = [123, 345, ...] How can I achieve this from Django query? Thanks. -
Django: icontains case is sensitive for unicode
I'm making a simple search for my blog. I use an armenian language and when I'm searching it's always sensetive for these letters. Here is a part of my code. Thank you in advance. search_query = get.get('search') query_list = search_query.split() posts = post.objects.filter( reduce(operator.and_, (Q(title__icontains=q) for q in query_list))| reduce(operator.and_, (Q(content__icontains=q) for q in query_list)), ) -
Django unable to find FULLTEXT index in mysql database?
The error that i am getting is OperationalError at /work/filter (1191, "Can't find FULLTEXT index matching the column list") Now what is strange is that i implemented them manually on database as can be seen below and the django code that i have is work_list = Work.objects.filter(work_type=job_type,description__search=query).order_by('-created') paginator = Paginator(work_list,10) the description field has index FULLTEXT from mysql console. Where am i going wrong ? Also i already tried to restart both django as well as database server. -
django-allauth: Verification email not sent on SignUp
Hello I am using allauth with: custom Django user: class Profile(AbstractUser) Custom Signup form: class ProfileForm(UserCreationForm) Alluth account adapter: AccountAdapter(DefaultAccountAdapter) And these are my settings: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] # Some really nice defaults ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) ACCOUNT_ADAPTER = 'strateole2.profiles.adapters.AccountAdapter' # SOCIALACCOUNT_ADAPTER = 'strateole2.profiles.adapters.SocialAccountAdapter' # Custom user app defaults # Select the correct user model AUTH_USER_MODEL = 'profiles.Profile' ACCOUNT_SIGNUP_FORM_CLASS = "strateole2.profiles.forms.ProfileForm" LHello I am using allauth with: custom Django user: class Profile(AbstractUser) Custom Signup form: class ProfileForm(UserCreationForm) Alluth account adapter: AccountAdapter(DefaultAccountAdapter) And these are my settings: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] # Some really nice defaults ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) ACCOUNT_ADAPTER = 'strateole2.profiles.adapters.AccountAdapter' # SOCIALACCOUNT_ADAPTER = 'strateole2.profiles.adapters.SocialAccountAdapter' # Custom user app defaults # Select the correct user model AUTH_USER_MODEL = 'profiles.Profile' ACCOUNT_SIGNUP_FORM_CLASS = "strateole2.profiles.forms.ProfileForm" LOGIN_REDIRECT_URL = '/' LOGIN_URL = 'account_login' # SLUGLIFIER AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' When I fill the sgnup form and hit signup, the user is created and I it tells me "We have sent an e-mail to you for verification" like this: https://www.dropbox.com/s/0lk4osoeuoswt9k/Capture%20du%202017-04-25%2012-47-27.png?dl=0 But the e-mail is not sent. But then, when I try to log … -
Filtering with elastic-search and django
I've configured elastic search within my django project. The next step is to apply some filtering options of those searches. The content of each search is Cars, so I'd like to be able to filter on Model, Price, Petrol/Diesel etc. Any thoughts on how to achieve this? Thanks, -
Django MySQL Query Json field
I have a MySQL database with a table containing a JSON field called things. The JSON looks like this things = {"value1": "phil", "value1": "jill"} I have collection of objects that I have pulled from the database via my_things = Name_table.objects.values Now, I'd like to filter the my_things collection by one of the JSON fields. I've tried this my_things = my_things.filter(things__contains={'value': 'phil'}) which returned an empty collection. I've also tried my_things = my_things.filter(things={'value': 'phil'}) and my_things = my_things.filter(things__exact={'value': 'phil'}) I'n using Django 1.10 and MySQL 5.7 Thoughts? -
Django html template in a seperate file
My question is more of an etiquette theme rather than anything else. I'm developing a relatively small application that reads XML data and writes to an Oracle DB and outputs to a webpage. I'm reading through the "The Definitive Guide to Django: Web Development Done Right" book, basically because learning something new is fun I recognise more and more requests for Engineers with Django experience. In the book, there is a recommendation to seperate html templates seperately (for example in .html files in its own folder). Are there any advantages to saving seperately the templates as opposed to just leaving a html template embedded in my python script? The template which I'm using is about 15 lines, and uses the data in a generate list to populate the html text, for example: path_to_be_used = desktop_path + 'XURA_output.html' f = open(path_to_be_used, 'w') string = """<html> <head><title>XURA Messaging</title></head> <body> <p>XURA Message contents: the data contained in this page is the Push Notification output retrieved from the XURA server.<br> Upon arrival this data is subsequently written to the Oracle database. """ f.write(string) line1 = "<p><pre>TAG".ljust(28) + "| " + "TEXT".ljust(40) + " </pre>" f.write(line1) for tag in smsreport_list: tagInfo = tag[0] textInfo = …