Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a fast way to allow list / create / modify / delete model data in a django project?
Basically I want to have the django admin functions in a normal app without having to write separate class or function based views for each function like list / create / modify / delete, etc. Just want to confirm if there is a fast way? -
Django Template getting apparent catchall error: "AssertionError at / No exception message supplied"
I'm getting an error I believe to be secondary damage, or else a catchall error when the real error has not been pinpointed. (N.B. One search result for the error message said to make sure your tags have correct syntax; no {# ... %}. I double-checked, and I didn't notice any failures of properly nesting, opening, and closing tags. The code that Django's 500 page is highlighting is: 5 <table> 6 {% for pet in pets %} 7 {% if not pet.should_hide %} 8 <tr> 9 <th valign="top"> 10 <a href="/pet/{{ pet.slugline }}" 11 ><img src="{{ pet.main_image }}" /></a> 12 </th> 13 <td valign="top"> 14 <h2> 15 {% if pet.slugline %} 16 <a href="/pet/{{ pet.slugline }}"> 17 {% endif pet.slugline %} 18 {% if pet.name %} 19 {{ pet.name }} 20 {% else %} 21 Anonymous 22 {% endif %} 23 {% if pet.breed_or_type %} 24 - <span class="breed-or-type" 25 >{{ pet.breed_or_type }}</span> The line that is labeled as causing the problem is 15, {% if pet.slugline %}. This is after lines 9-10, which include a pripr {% if pet.slugline %} as well as {{ pet.slugline }}%. The whole template is at http://pastebin.com/EQMA9jyU [base template available on request]. Where should … -
django makemigrations fails after removing a class
I have a model like this: class States(Enum): first = 'one' second = 'two' choices = ( (States.first, 'First'), ... ) class MyModel(models.Model): state = FSMField(choices=choices) and another model like: class MyOtherModel(models.Model): new_state = CharField(choices=myapp.choices) For various reasons, I removed the States Enum and replaced it with a bunch of constants like: FIRST = 'one' I then migrated my database, and it all went fine. But when I later run ./manage.py makemigrations, I get an `AttributeError: module 'myapp.models' has no attribute 'States'. The traceback ends like this: File "myapp/migrations/0038_xxx.py", line 12, in <module> class Migration(migrations.Migration): File "myapp/migrations/0038_xxx.py", line 36, in Migration ('new_state', models.SmallIntegerField(choices=[(myapp.models.States('one'), 'First'), (myapp.models.States('two'), 'Second')])), AttributeError: module 'myapp.models' has no attribute 'States' but if I paste the States definition back into my models file, then makemigrations runs fine. How am I supposed to remove this code if old migrations still require it? I have a bunch of migrations that follow this 0038, most of which have already been applied to the production database. -
Google font not working in PDF when using PDF Generation With PISA in Django
I am using PDF Generation With PISA in Django to convert a django view / template into a PDF. Google font Raleway is used. The font works fine with the HTML preview but not in the PDF. Tried the following libraries. ho xhtml2pdf easy_pdf Also tried most of the CSS hacks. But its not working. Is there any possible work around? -
Send PDF attached email using JsPDF with ajax and Django python
I have issue with send pdf attached email using jspdf with ajax and django. The issue is server side views.py print(pdf_s) always retrun 'None' but client side console.log(pdf) returns binary values. Please refer the below code which i was tried. script.js This is client side code. and I'm using Ajax to send data to server function sendMail(){ getCanvas().then(function(canvas) { console.log('Test'); var img = canvas.toDataURL("image/png",0.98); var imgWidth = 200; var pageHeight = 295; var imgHeight = canvas.height * imgWidth / canvas.width; var heightLeft = imgHeight; var doc = new jsPDF('p', 'mm', 'a4', 'pt'); var position = 0; doc.addImage(img, 'JPEG', 5, position, imgWidth, imgHeight); heightLeft -= pageHeight; while (heightLeft >= 0) { position = heightLeft - imgHeight; doc.addPage(); doc.addImage(img, 'JPEG', 5, position, imgWidth, imgHeight); heightLeft -= pageHeight; } var pdf = btoa(doc.output()); console.log(pdf); $.ajax({ type:'POST', url:'sendmail/', data:{ pdf_data: pdf, csrfmiddlewaretoken: csrftoken }, success:function(data){ console.log(data); } }); }); } views.py def SendMail(request,scan_id): pdf_s = request.GET.get('pdf_data') print(pdf_s) fo = open('test.pdf','w') fo.write(pdf_s) fo.close() html_content = "Test Message" email = EmailMessage("test", html_content, "test", ["test@test.com"]) email.content_subtype = "html" fd = open('test.pdf', 'r') email.attach('test', fd.read(), 'application/pdf') res = email.send() if res: status = 'Success' else: status = 'Fail' return HttpResponse(status) -
django-admin-bootstrapped conficts with django-autocomplete-light with error: $("[title]").tooltip() is not a function
I'm setting up a django site using django-autocomplete-light (v3); however, when I add django-admin-bootstrapped, the following error occurs: $('[title]').tooltip(); tooltip is not a function. I installed 'dal' and 'dal_select2' before 'django-admin-bootstrapped' and 'django.contrib.admin' in settings.py as follow: 'dal', 'dal_select2', 'django_admin_bootstrapped', 'django.contrib.admin', It appears to me that, django-autocomplete-light has its own jquery and somehow overrides the django-admin original jquery. It might be a jquery loading issue, because when I run collectstatic, I can clearly see a new jquery.min.js and a jquery.init.js added by django-autocomplete-light. But this is not an issue at all until I add django-admin-bootstrapped which breaks the page loading with that error. In Chrome Dev Tools Network tab, I can see both django admin and django-autocomplete-light jquery being loaded and that appears to be the problem. How to solve this issue ? How to control which scripts get included by vendors in collecstatic ? Do I have to manually delete or edit generated static files by collecstatic ?(which might not work when deploying to heroku for instance) Or is there a better way to control what collectstatic process and create some post processing function to solve this conflict ? -
Combining two queries from different application/models to display them on a single overview page
I have only recently started working with Django and was wondering how one would go around to combine two queries from different application/models and display them in a given overview page. I will display some non-functional pseudo-code below to illustrate what I am trying to do: Index.html Note that I added two seperate context_object_names here just to illustrate what I am trying to do (latest_news and latest_enzyme) {% extends 'base.html' %} {% block body %} <div id="docs-content"> <div class="section" id="s-module-django.db.models.fields"> <div class="page-header text-primary"> <h3 class="info-header-blue-publication-small">Overview</h3> </div> <div> <h3 class="info-header-blue-publication-tiny">Latest news:</h3> </div> {% if latest_news %} {{ latest_news.news_text }} {% else %} <p>No recent news.</p> {% endif %} <div> <h3 class="info-header-blue-publication-tiny">Latest enzyme:</h3> </div> {% if latest_enzyme %} <ul> <li><a href="{% url 'gts:detail' latest_enzyme.id %}">{{ latest_enzyme.barcode }}</a></li> </ul> {% else %} <p>No enzymes are available.</p> {% endif %} </div> </div> {% endblock %} Views.py Note that this contains some commented lines that illustrate the method that I was trying but did not get working, as well as two seperate get_querysets to illustrate my intent. from django.shortcuts import render from django.http import HttpResponse from django.views import generic from gts.models import Enzymes from news.models import News # Create your views here. class IndexView(generic.ListView): template_name … -
Placing div's with float
I have one big list of dictionaries in django view as follows: 'description': [ { 'name': 'Onderdelen', 'good': ['Motor', 'Versnellingsbak', 'Koppeling', 'Carburatie - injectie - Diesel injectie + verstuivers'], 'trace_of_use': ['Differentieel', 'Batterij', 'Radiator', 'Alternator', 'Startmotor'], 'to_repair': ['Cardanhoezen', 'Uitlaat', 'Aandrijfriemen van accessoires'], }, { 'name': 'Wielen en banden', 'good': ['Staat van de banden', 'Reservewiel'], 'trace_of_use': ['Krik'], 'to_repair': [], }, { 'name': 'Verlichtimi: en signalisatie', 'good': ['Kruislichten', 'Grootlichten', 'Mistlichten vooraan', 'Suoolementaire verlichting', 'Standlichten', 'Richtingaanwiizers', 'Alarrn(signaal)', 'Stoolichten', 'Nummerplaatverlichting'], 'trace_of_use': ['Krik'], 'to_repair': ['Mistachterlicht', 'Achteruitri ilicht', 'Enkeltonige claxon', 'instrurnentenbord : verlichting en lampjes'], }, { 'name': 'Uitrustinegen', 'good': ['Zetels', 'Gordels', 'Stuurwiel', 'Brandblusser', 'Verbanddoos', 'Airconditioning', 'Audio installatie ( ootioneel)', 'Elektrische ruiten', 'Centrale vergrendeling'], 'trace_of_use': ['Ruitenwisser en ruitensproeier vooraan', 'Binnen- en buitenspiegels', 'Alarmsvsteem ( optioneel)'], 'to_repair': ['Ooendak', 'Reservewielhouder + druk van het reservewiel', 'Aanhangwagenkopoeling ( ootioneel', 'Gevarendriehoek'], }, { 'name': 'Beglazing - carrosserie', 'good': ['Voorruit en beglazing', 'Deuren en kofferdeksel', 'Motorkao', 'Soatborden', 'Bumpers -afdekplaten', 'Reflectoren achterlichten', 'Laadbak -cabine (bedrijfsvoertuig'], 'trace_of_use': [], 'to_repair': [], }, { 'name': 'Remmen - stuurinrichting', 'good': ['Bedriifsrem', 'Handrem', 'Remvloeistofreservoir', 'Hoofdremcilinder', 'Rembekrachtiging', 'Sturbekrachtiging', 'Staal van rem- en stuurleidingen', 'Vloeistofreservoir stuurbekrachtiging', 'Remblokken', 'Remschijven', 'Remzadels', 'Remkrachtverdelers', 'Handremkabel', 'Stuurhuis', 'Reactiestangen stuurinrichting'], 'trace_of_use': [], 'to_repair': [], }, { 'name': 'Verbindingen met het wegdek - assen', 'good': ['Voortrein', 'Achtertrein', … -
ElasticSearch to Django APIView - Results limited
I'm trying to proxy my ElasticSearch connection via Django so I can filter results and use authentification. I want the django URL to behave as connecting directly to Elastic Search (:9200). The below code connects, and gives the same results as "http://localhost:9200/_search" However, all other requests it makes return the same result. I get no errors. When I connect to ES directly (:9200), it always does OPTIONS & POST. When I connect to ES via Django, it always does POST, rarely OPTIONS services.py def elastic_result(id, request): url = 'http://localhost:9200/_search' r = requests.post('http://localhost:9200/_search', params=request.data) items = r.json() return Response(items) views.py from services import elastic_result class ElasticView(APIView): permission_classes=[] def post(self, request): item_list = elastic_result(id, request) return item_list pass url router.register(r'elastic/_search', ElasticView, base_name='Elastic') -
Django Forms - instance it does not work as expected
I am following a tutorial and I want to create an edit button for my input but when I click the edit button it returns the form but empty: forms.py class RecordingForm(forms.ModelForm): class Meta: model = Recording fields = ['component', 'group', 'failure', 'degree_of_failure'] views.py def edit_recording(request,slug, recording_id): recording = get_object_or_404(Recording, pk=recording_id) if request.method == "POST": form = RecordingForm(request.POST, instance=recording) if form.is_valid(): recording = form.save(commit=False) recording.save() return redirect('data:detail') else: form = RecordingForm(instance=recording) template = 'data/create_recording.html' context = {'form': form} return render(request, template, context) the form is empty :( -
django-autocomplete-light v3 Customising the output of items and conserve it in the form
Following this (Customising the output of items using django-autocomplete-light v3), I customise the list of choices. My code : class WordAutocomplete(autocomplete.Select2QuerySetView): ... def get_result_label(self, obj): template = get_template("autocomplete_light/item.html") context = Context({"item": obj}) return mark_safe(template.render(context)) The Form : class SentenceAdminForm(forms.ModelForm): class Meta : widgets = { 'word':autocomplete.ModelSelect2Multiple('WordAutocomplete', attrs={'data-html': 'true'}), } The Template autocomplete/item.html : <a href="url">{{ item }}</a> As you can see, there are links in every item. And the links are active until I save : links are active in the list and in the select box After saving, the links are no longer there How can I do to maintain the links in the select box ? -
Django/NGINX/Ubuntu: Media files - [Errno 13] Permission denied
I've deployed my web on Digital Ocean VPS - Ubuntu 14.04. I have a ImageField in one of my models which I choose in Django admin (browse pc and upload the image). The problem is that this image can't be saved into /media/categories/. It's raising: [Errno 13] Permission denied: '/home/django/project/media/categories/television_d3q3EM0.png' I thought that it is, because Nginx hasn't write privileges to /media/ directory so I run these commands: sudo chown -R www-data /media/ which didn't help sudo chown -R django /media/ which didn't help neither I'm a newbie in Linux rights so I can't figure out what am I doing wrong. Media folder is in /project/ directory (where the manage.py is). Here are permissions of the /media/ folder. Owner has rights so I don't know why sudo chown -R www-data /media/ didn't work. -
Django static files go missing when debug is set to False
I just set up a small web application in a production environment that uses static css files. This works fine when debug is set to True but as soon as debug is set to False, the css files go missing and I only see the html page as ugly as can be. Any thoughts on how I can fix this? Thanks! -
Call Django view function from AngularJS
I want to get the list of my existing users when a page loads. Everything works when getting the information from the Angular script, but it will be stored serverside. I've made a Django view: def getUsers(request): response = {} response['user'] = { 'username': 'guy1', 'password': 'guy1', 'fName': 'John', 'lName': 'Smith', 'email': 'guy1@host.com', 'role': 'Employee', 'theme': 'default' } return JsonResponse(response) Currently, I just pass my user there, later it will be filled with information from a postgre DB. I think I've set the url correct: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^', views.dashboard, name='dashboard'), url(r'getUsers/', views.getUsers), ] And finally, I call the view from Angular when the page loads: $http.get("getUsers") .then(function(output) { $scope.testUser = output; console.log($scope.testUser); }); When I run everything, the browser console comes up with incorrect output. Any ideas as to what I've done wrong? Thanks. -
Multiple Django app using nginx and gunicorn on Ubuntu 14.04 trusty server
I am new to server configuration. I do some google and config django app using gunicorn and nginx on ubuntu 14.04 trusty server. For first django app I use port number 80 and my configfiles are : /etc/init/gunicorn.conf :- description "Gunicorn application server handling myproject" start on runlevel [2345] stop on runlevel [!2345] respawn setuid setgid www-data chdir /home/myserver/my_virtualenv_path/myproject exec /home/myserver/my_virtualenv_path/myproject/gunicorn --workers 2 --bind unix:/home/myserver/my_virtualenv_path/myproject/myproject.sock myproject.wsgi:application My nginx configuration file for first django app: /etc/nginx/site-available :- server { listen 80; server_name myapp.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myserver/my_virtualenv_path/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/myserver/my_virtualenv_path/myproject/myproject.sock; } } after that i link site to site-enabled . Next i create a new django app inside the first djngo app virtualenv like: FirstApp_Virtual_Env\first_djangoapp\app files FirstApp_Virtual_Env\Second_djangoapp\app files Now i configure gunicorn for second app like : /etc/init/gunicorn_t :- description "Gunicorn application server handling myproject2" start on runlevel [2345] stop on runlevel [!2345] respawn setuid setgid www-data chdir /home/myserver/my_virtualenv_path/myproject2 exec /home/myserver/my_virtualenv_path/myproject/gunicorn --workers 2 --bind unix:/home/myserver/my_virtualenv_path/myproject2/myproject2.sock myproject2.wsgi:application My nginx configuration file for second django app: /etc/nginx/site-available :- server { listen 8000; server_name myapp2.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myserver/my_virtualenv_path/myproject2; … -
How to limit objects an admin (without superuser) can interact with?
I am trying to build a platform and I thought using Djangos administrive user interface was simpler and faster than writing an own. The issue I have is that I don't want all admins to be able to see all objects, just the ones they are affiliated with. I use my own created model called Organisation which basically is the affiliation. I were reading this article: http://reinout.vanrees.org/weblog/2011/09/30/django-admin-filtering.html but it seems old and outdated. Because I copied the example and came up with this: class QuizAdmin(admin.ModelAdmin): form = QuizAdminForm list_display = ('title', 'category', ) list_filter = ('category',) search_fields = ('description', 'category', ) def queryset(self, request): """Limit quizzes to those that belong to the correct organisation.""" qs = super(QuizAdmin, self).queryset(request) org = Organisation.objects.get(user=request.user) if request.user.is_superuser: return qs return qs.filter(org=org) But it seems like the queryset method never runs. Is there another easy way to filter out the objects an admin user can interact with? Thanks in advance for your sage advice and better wisdom. -
DRF PrimaryRelatedField when write and NestedSerializer when read?
I am using a nested serializer. I need ProfileSerializer to return full related Project object for get requests and consider only id switching (changing current) like with relatedPrimaryField behaiviour for post/put requests on ProfileSerializer. any solutions on how to achieve this ? class ProfileSerializer(serializers.ModelSerializer): current = ProjectSerializer() class Meta: model = Profile fields = ('function', 'current') -
django nginx uwsgi not working
i ve created a django application not using virtual environment. I ve installed nginx and trying to integrate them via uwsgi application. Here my configurations files. [uwsgi] chdir = /home/elastic/workspace/ES_Brevetti wsgi-file = ES_Brevetti/wsgi.py master = true processes = 5 uid = nginx gid = nginx socket = unix:///socket/uwsgi.sock chmod-socket = 666 vacuum = true i've created the file /sockect/uwsgi.sock with permission 777 chown nginx:nginx -R /sockect/uwsgi.sock and below nginx conf file: upstream django { server unix:///socket/uwsgi.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } server { listen 80; server_name 10.184.2.231; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; charset utf-8; location /static/ { alias /home/elastic/workspace/ES_Brevetti; } location / { include uwsgi_params; uwsgi_pass unix:///socket/uwsgi.sock; } } When i launch "systemctl start nginx" nginx is started with error: connect() to unix:///socket/uwsgi.sock failed (111: Connection refused) while connecting to upstream, When i run uwsgi --ini /etc/uwsgi/sites/ES_Brevetti.ini it doesnt run with error: ..... lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) bind(): Permission denied [core/socket.c line 230] What i am doing wrong? On google i can only see configurations with VENV while i am not using virtual environment. -
django rest framework : nested model get not working. 'str' object has no attribute 'values'
I have a customer model in Bcustomer app that extends the django User model, So I will save the basic details such as name in User table and the remaining data (city, etc) in customer table. Saving is working perfectly. But now it is showing the following error when I call the GET method. AttributeError at /api/v1/customer 'str' object has no attribute 'values' Request Method: GET bcustomer/models.py class BCustomer(models.Model): customer = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True, blank=True ) address = models.CharField(max_length=50) city = models.CharField(max_length=256) state = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True, on_delete=models.CASCADE, related_name='customer_creator') # more fields to go def __str__(self): # return str(self.name) (This should print first and last name in User model) class Meta: app_label = 'bcustomer' bcusomer/serializers.py class CustomerDetailsSerializer(serializers.ModelSerializer): class Meta: model = BCustomer fields = ('city', 'phone') class CustomerSerializer(serializers.ModelSerializer): customer_details = CustomerDetailsSerializer() class Meta: model = get_user_model() fields = ('id','first_name', 'email', 'customer_details') def create(self, validated_data): request = self.context.get('request') customer_details_data = validated_data.pop('customer_details') customer_user = get_user_model().objects.create(**validated_data) BCustomer.objects.create(customer=customer_user, user=request.user, **customer_details_data) customer_user.customer_details = customer_details_data return customer_user class CustomerListSerializer(serializers.ModelSerializer): model = get_user_model() fields = '__all__' class Meta: model = get_user_model() fields = '__all__' bcustomer/views.py class CustomerViewSet(viewsets.ModelViewSet): customer_photo_thumb = BCustomer.get_thumbnail_url permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] queryset = BCustomer.objects.all() serializer_class = CustomerSerializer def get_queryset(self): queryset = BCustomer.objects.all() … -
Django Pagination with multiple models (tables)
We have multiple models (tables) for storing orders category wise of a customer . class BookOrder(models.Model): user = models.ForeignKey(User) order_details = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class ShoeOrder(models.Model): user = models.ForeignKey(User) order_details = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class MobileOrder(models.Model): user = models.ForeignKey(User) order_details = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Now we need to show list of orders to our customers. But it should be paginated. Can anybody suggest me how to use Django pagination with multiple models ? -
django wsgi app settings
I'm trying to run my django application using the built in wsgi. My directory is structured as follows: /project/ -/project/ - settings.py - wsgi.py - urls.py -/app/ Here is the provided wsgi.py file, which I've modified a bit. import os from django.core.wsgi import get_wsgi_application # used to be crowdlabel.settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_wsgi_application() if __name__ == "__main__": application.run() When running python project/wsgi.py , I get an error that the module project can't be found. To solve this, I change os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings"). Doing this then gives me a new error in the get_wsgi_application() function, ModuleNotFoundError: No module named 'app'. I am beyond confused so if anyone with experience could suggest what I'm doing wrong it would be greatly appreciated. As a note, the app runs fine on the test server. -
CRM for Django - New developments
I've been looking into CRM packages for Django recently. As far as I can see the, main options (koalix and Django-CRM) seem outdated, with unclear status and a lack of python 3 support. I am wodering why this is the case, since I consider Django to be among the best and most powerful tools to base a CRM application on. Therefore, I have invested some time in developing a simple and customizable CRM application for Django (django-leancrm) and I am currently thinking about open-sourcing it. Since maintaining this package will bind future resources, I am unsure if the effort is worth it. So, am I overlooking something? Is anybody aware of other CRM packages for Django currently still maintained or is there anything new currently under development? Thanks for your answers and opinions! -
How make uploaded image to fit in bootstrap div in django
I am using Django ckeditor and if I am uploading an image that is big it does not fit in my div, it goes over it corners. Here is a image what happens: I want that the body image is the same size as the header photo. As you can see the text stays in the div it does not go over the divs borders, but the image is not staying in the div. Why is that so? Here is my html code: {% extends "blog/index.html" %} {% load staticfiles %} {% load mptt_tags %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-8"> <article> <h1><a href="{{ post.get_absolute_url}}">{{ post.title }}</a></h1> <div class="row"> <div class="container" style="padding-bottom: 20px"> {% if post.author.first_name %} <h4>by <a href="{{ post.get_absolute_url_user }}">{{ post.author.first_name }} {{ post.author.last_name }}</h4></p> {% else %} <h4>by <a href="{{ post.get_absolute_url_user }}">{{ post.author.author }}</h4></p> {% endif %} <!-- Kategorija blogova --> <span class="glyphicon glyphicon-folder-open"></span> &nbsp;<a href="#">{{ post.category }}</a> </div> <div class="group1 col-sm-6 col-md-6"> <!-- Tagovi za blogove --> <i class="fa fa-tags" aria-hidden="true"></i> {% for tag in post.tags.all %} <a href="{% url "blogs:post_list_by_tag" tag.slug %}">{{ tag }}</a> {% endfor %} </div> <div class="group2 col-sm-6 col-md-6"> <!-- Comments --> <span class="glyphicon glyphicon-pencil"></span> <a href="singlepost.html#comments">{{ post.comments.count … -
How to use Django RegexValidator with AJAX?
I have a form with an input field. I validate this field with RegexValidator and it works. Also, I use django-crispy-forms. class EncryptionForm(forms.Form): shift = forms.IntegerField( label='Shift', max_value=26, min_value=1, initial=1) input_text = forms.CharField( label='Input', widget=forms.Textarea, validators=[ RegexValidator( r"^[A-Za-z\s0-9-!#$%&'*+/=?^_`{}|~.,<>():;@\\\[\]\"]*$", message='Please use english language!', code='invalid_language' ), ] ) I made this form work trough AJAX. validation for shift still works(max_value, min_value). And validation for input_text doesn't work(RegexValidator). I need to create new validation rule in jQuery or I can pass my RegexValidator(or just error) through AJAX? function submitForm(){ $('#id_intake_form').on('submit', function(){ var link = $(this); var action = $(this).find('#id_action').val(); var shift = $(this).find('#id_shift').val(); var input_text = $(this).find('#id_input_text').val(); $.ajax({ 'url': link.attr('action'), 'type': 'POST', 'dataType': 'json', 'data': { 'action': action, 'shift': shift, 'input_text': input_text, 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val() }, 'success': function(data, status, xhr){ if(status != 'success'){ alert('Error on server. Please try again later.'); return false; } var output_text = data.output_text; $('#output').val(output_text); chart(data.char, data.char_rate); return false; }, 'error': function(xhr, status, error){ alert('Error on server. Please try again later.'); return false; } }); return false; }); } Now when input isn't valid I have "Error on server" alert from AJAX error. -
Django. Advanced search implementation.
I'm looking for relaively simple way to implement advanced search functionality in Django. I need to generate following form and obtain search results using this form. Form schema: general text input (text passed here will be used to search through all specified fields of given model + possible relationships) several checkboxes (those will be used to pick which fields will be included in search [all specified fields by default]) several pairs of inputs (those pairs will responsible for declare the scope used to limit search result e.g: date from -/- to, or mass from -/- to) I've checked several apps (django-watson, django-filters, django-haystack) and tried to bulid my own implementation but I didn't find proper (and simple) solution. Any ideas how could I manage this task? I'll be grateful of any answers!