Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to install mysqlclient on windows
An error occurred when i was installed mysqlclient.I have search for many methods to resolve it,but it did't work.I am using Windows7 64bit and python 3.4 64bit.error Then i download mysqlclient-1.3.10-cp34-cp34m-win_amd64.whl and install it with pip,another error occurredthis file is not a supported wheel on this platform I really need your help! -
Use image tag and source in django template language system
I have a encoded 64 image in json which going to insert into django html template. How should I translate this <img src="R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp(Some 64 bit image);base64 /> into django template? I have a body tag to receive the data and a style tag to put in css. -
Using icons with django-select2
I would like to set an icon in front of the selectable items in a multiple choice field I'm rendering with django-select2. Per the documentation, it looks like I'll need to use templateResult, but not sure how in my case. My HTML (simplified below) is rendered with django-crispy-forms and django-select2 as follows: <form class="form-horizontal" method="post" > <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" type="text/css" media="screen" rel="stylesheet" /> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> <script type="text/javascript" src="/static/django_select2/django_select2.js"></script> <label for="id_recipients" class="control-label col-lg-2 requiredField">Recipient(s)<span class="asteriskField">*</span> </label> <select multiple="multiple" class="select2multiplewidget form-control django-select2" data-allow-clear="false" data-minimum-input-length="0" data-placeholder="Select one or more recipients" id="id_recipients" name="recipients"> <optgroup label="Groups"> <option value="group_6">Group 6</option> <option value="group_2">Group 2</option> <option value="group_8">Group 8</option> </optgroup> </select> </form> I thought I'd be able to use JS like on the Example page, with the below, but the function is never called. $(".select2multiplewidget").select2({ templateResult: formatState }); -
generating multiple pdf's from Excel in Django
I am using an Excel sheet to import data, save to databaseand then generate a pdf for every row of the data. Its just returning 1 pdf if i use return response. Is there a way to access the canvas object and form a zip or download all the pdf's views.py def uploadcertificate(request): book = open_workbook('../myproduct/media/Sheets/Certificate.xlsx') sheet = book.sheet_by_index(0) col = sheet.ncols for row_index in range(sheet.nrows): col = sheet.ncols d = Certificate() d.name = (sheet.cell(row_index, sheet.ncols - col).value) col -= 1 d.course = (sheet.cell(row_index, sheet.ncols - col).value) d.date = datetime.date.today() d.date=str(d.date) row=str(row_index) d.certificateId = "Skill / 18050123 / 00"+row d.save() response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Certificate.pdf"' #Genarating pdf buffer = BytesIO() logo = ImageReader('../myproduct/media/logo.png') p = canvas.Canvas(buffer) p.setFont('Helvetica', 20) p.drawImage(logo, 0, 0, width=600, height=400) p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return(response) return render(request, 'trainer/index.html') -
How to create / update 2 objects [Django Rest Framework]
I'm new to django rest framework and I'm trying to create / update 2 objects in the same request: class PessoaSerializer(serializers.ModelSerializer): user = UserSerializer(required=False) class Meta: model = Pessoa fields = ('id', 'user', 'nome', 'email', 'cargo', 'fone', 'cep', 'celular', 'endereco', 'observacao', 'municipio') def create(self, validated_data): usuario = User() usuario.first_name = validated_data.get('nome') usuario.username = validated_data.get('email') usuario.last_name = validated_data.get('nome') #TODO usuario.email = validated_data.get('email') usuario.is_active = True usuario.is_staff = False usuario.is_superuser = False usuario.set_password(validated_data.get('email')) #TODO usuario.last_login = datetime.datetime.now() usuario.date_joined = datetime.datetime.now() usuario.save() validated_data['user'] = usuario return Pessoa.objects.create(**validated_data) def update(self, instance, validated_data): #TODO This is the best way to to it? Or I'm missing something? -
RequestError: TransportError(400, u'parsing_exception')
I am using django-haystack and Elasticsearch for my app. I have loaded all the requirements and trying to search my indices using search.html But whenever I tried to retrieve the results using an API at http://localhost:8000/search, I am getting the below error and I have googled much about this but couldn't able to get any help: RequestError: TransportError(400, u'parsing_exception') -
django rest framework category parent and child count
There is my model: class Category(models.Model): ..... slug = models.SlugField(verbose_name=_('Slug')) description = RedactorField(verbose_name=_('Description')) parent = models.ForeignKey('self', null=True, blank=True, default=None, verbose_name=_('Parent')) The thing is I need to make a api resource, using DjangoRestFramework, and serializer should contain count of childs for each category. Something like this, i made with inbox DRF tools like generics.ListAPIView: [ { "id": 1, "created": "01-08-2017 10:42 UTC", "modified": "01-08-2017 10:55 UTC", "name": "Category_1", "slug": "", "description": "", "parent": null, "child_count": 12, }, { "id": 2, "created": "01-08-2017 10:42 UTC", "modified": "01-08-2017 10:55 UTC", "name": "SubCategory_1_1", "slug": "", "description": "", "parent": 1, "child_count": 0, }, ... ] so the queryset Category.objects.annotate(child_count=models.Count('parent')) gonna show only the count of parents (and its always equals to 1 or 0). There is MPTTModel lib, that possibly could solve this, but i can't use it, because of some project specific issues exists. -
after uploading Django on host admin style does not show
After making a website with Django, I uploaded that on cpanel. All things is OK, but the admin can't display the css. what is the problem? -
Postgresql warning: "could not flush dirty data: Function not implemented"
I'm trying to create a new database on postgres, by running command: CREATE DATABASE dbname; and I face the error: WARNING: could not flush dirty data: Function not implemented many times! and finally I get the message CREATE DATABASE Can anyone help me to undrestand and solve this error please? -
Django - send prefetch_related() response inside array of objects
Below is my views.py def books(request): books = books = Book.objects.prefetch_related('book_stat_set').all() for book in books: for book_stat in book.book_stat_set.all(): book.stats = book_stat # what is wrong here pprint(vars(book_stat)) # prints book_stat dict perfectly books_serial = serializers.serialize("json", books) return HttpResponse(books_serial) Here is my models.py class Book(models.Model): title = models.CharField(max_length=200) image = models.FileField(upload_to="mp/", blank=True) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=150) def __str__(self): return self.full_name class Book_stat(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book) rating = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal('0.00')) like = models.BooleanField(default=False) def __str__(self): return self.book.title + ' by: ' + self.user.profile.full_name When i send the json data it does not have stats dictionary inside each fields object, but pprint outputs to terminal perfectly from views.py -
Validation error prevent saving data
I have a little issue with the following method in the customers/forms.py file def clean(self): cleaned_data = super(CustomerBaseForm, self).clean() bank_account = cleaned_data.get("bank_account") ssn = self.cleaned_data.get('ssn') bank = self.cleaned_data.get('bank') bank_transit = self.cleaned_data.get('bank_transit') v = CustomerProfileFormCleaner(self) v.clean() # The concatenation of bank transit, the bank account and the bank # number must be unique. Hence, the following message would be # displayed if it is already in use. msg = _('The bank, the bank transit and the bank account are already in use') customer = CustomerProfile.objects.filter(ssn=ssn) qs = FinancialProfile.objects.filter( bank=bank, bank_transit=bank_transit, bank_account=bank_account) if customer.count() == 1: qs = qs.exclude(customer_id__in=[cust.id for cust in customer]) if qs.count() > 0: self.add_error('bank_account', msg) self.add_error('bank', '') self.add_error('bank_transit', '') Views.py class CustomerCreateView(StaffRestrictedMixin, FrontendMixedFormView): template_name = 'loanwolf/customers/create.html' form_class = CustomerCreateForm url_namespace = 'customers' def get_success_url(self): self.session['success'] = True return reverse('%s:profile' % self.url_namespace, kwargs={'cust': quote(self.customer.pk)}) def form_valid(self, form): g = form.cleaned_data.get self.customer = User(**{ 'first_name': g('first_name'), 'last_name': g('last_name'), 'username': g('email'), 'email': g('email'), }) I have an error form because of error_1_id_bank_transit which give me as information that prevent me to save that form. grep --color -rn 'id' | grep --color 'error_' | grep --color 'small' venv/lib/python2.7/site-packages/crispy_forms_materialize/templates/materialize_css_forms/field.strict.html:23: <small id="error_{{ forloop.counter }}_{{ field.auto_id }}" class="error"> venv/lib/python2.7/site-packages/crispy_forms_materialize/templates/materialize_css_forms/field.html:28: <small id="error_{{ forloop.counter }}_{{ field.auto_id }}" … -
Left Join between two external DB's
I want to do a left join with another db, What would be the django equivalent of this query ? USE PARTNER_DB; SELECT CLIENT_ID, PARTNER.FIRST_NAME, PARTNER.LAST_NAME, RPM, DRAWDOWN_PROTECTION, CONCAT(EMPLOYEE_DB.EMPLOYEE.FIRST_NAME, " ", EMPLOYEE_DB.EMPLOYEE.LAST_NAME), EMPLOYEE_DB.EMPLOYEE.MAIL FROM PARTNER LEFT JOIN EMPLOYEE_DB.EMPLOYEE ON RM_ID = EMPLOYEE_DB.EMPLOYEE.EMP_ID WHERE CLIENT_ID = 'X1234' I am using multiple databases in my project and both of these databases are not managed by django. I tried to dig into django documentation but was unable to find a way to achieve this, instead i bumped into this https://docs.djangoproject.com/en/1.11/topics/db/multi-db/#no-cross-database-relations. I am sure that there will be a hack / workaround this. Looking forward to your solutions. These are two different db's not managed by django. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'PARTNER_DB', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '3306', }, 'employeedb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'EMPLOYEE_DB', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '3306', } } My db models are class Partner(models.Model): client_id = models.CharField(db_column='CLIENT_ID', primary_key=True, max_length=25) first_name = models.CharField(db_column='FIRST_NAME', max_length=50) last_name = models.CharField(db_column='LAST_NAME', max_length=50, blank=True, null=True) mobile = models.CharField(db_column='MOBILE', max_length=10, blank=True, null=True) active_from = models.DateField(db_column='ACTIVE_FROM') rm_id = models.CharField(db_column='RM_ID', max_length=10, blank=True, null=True) preferred_name = models.CharField(db_column='PREFERRED_NAME', max_length=50, blank=True, null=True) rpm = models.IntegerField(db_column='RPM', blank=True, null=True) drawdown_protection = models.IntegerField(db_column='DRAWDOWN_PROTECTION', blank=True, null=True) depository_id … -
TypeError: unbound method check() must be called with Signature instance as first argument (got nothing instead)
I am upgrading an existing Django application from 1.3 to 1.11, most things are working fine and now trying to get Celery working. I got some unknown column errors related to Celery so I figured I need to run migrations. However running ./manage.py check or ./manage.py makemigrations gives me the error in the title and I have not been able to fix this. It seems to be coming from Django's code and not my application - here is the full stack trace: Traceback (most recent call last): File "./manage.py", line 7, in <module> execute_from_command_line(sys.argv) File "/var/www/caretaker/www/production/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/var/www/caretaker/www/production/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/caretaker/www/production/env/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/caretaker/www/production/env/lib/python2.7/site-packages/django/core/management/base.py", line 327, in execute self.check() File "/var/www/caretaker/www/production/env/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/var/www/caretaker/www/production/env/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/var/www/caretaker/www/production/env/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/var/www/caretaker/www/production/env/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models errors.extend(model.check(**kwargs)) TypeError: unbound method check() must be called with Signature instance as first argument (got nothing instead) I had to upgrade my manage.py which now contains the following (running just ./manage.py brings up the list of commands so it seems to be working): #!/usr/bin/env python import os, … -
Django filter by annotated field is to slow
I use DRF and I have model Motocycle, which has > 2000 objects in DB. Model has one brand. I want to search by full_name() is: queryset = Motocycle.objects.prefetch_related( "brand" ).annotate( full_name=Concat( 'brand__title', Value(' - '), 'title', ) ) ) I want to filter by full_name, but query is running very slowly: (1.156) SELECT "mp_api_motocycle"."id"... Without filtering with pagination: (3.980) SELECT "mp_api_motocycle"."id"... There is some possibilty to make this query faster? -
Django Sass Comile on model save
I'm making a django website with some products. Now I want to be able to customize some things from the admin. Like the background image and some primary and secundairy colors. How I see this : I have a class SiteAppearance with an imagefield and a charfield for a color. When I save the model I generate the a small scss file with the def of $prim_color and $hero_bg ... This file is included in my general scss file. So after this file is made and saved I want to re-compile this sass file so I get a new css file. Any idea how i can compile the sass file from inside my save function? -
Detect field change using post_save instead of pre_save signal
I need to do some actions when one field has changed. Since this action needs to work with already saved object, I can't use pre_save signal like this: @receiver(pre_save, sender=reservation_models.Reservation) def generate_possible_pairs(sender, instance, **kwargs): try: reservation_old = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass # Object is new, so field hasn't technically changed, but you may want to do something else here. else: if not reservation_old.datetime == instance.datetime: # Field has changed do_something(instance) # It would be better to be sure instance has been saved Is it possible to use post_save signal for this? I would like to avoid adding temporary attributes to this model. -
Django - ImportError: No module named djangochat.settings
Here is my error trace of python manage.py runserver I am using django 1.10.7 with python 2.7 (faavenv) user@ubutnu:~/Documents/faa-backend$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/home/user/Documents/faa-backend/faavenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/user/Documents/faa-backend/faavenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/home/user/Documents/faa-backend/faavenv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/user/Documents/faa-backend/faavenv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/user/Documents/faa-backend/faavenv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named djangochat.settings Here is my requirements.txt amqp==2.2.1 anyjson==0.3.3 asn1crypto==0.22.0 Babel==2.4.0 backports-abc==0.5 bcrypt==3.1.3 BeautifulSoup==3.2.1 beautifulsoup4==4.6.0 billiard==3.5.0.3 bleach==2.0.0 boto==2.48.0 boto3==1.4.4 botocore==1.5.80 celery==4.1.0 certifi==2017.4.17 cffi==1.10.0 chardet==3.0.4 cryptography==1.9 Django==1.10.7 django-celery-beat==1.0.1 django-contrib-comments==1.8.0 django-debug-toolbar==1.8 django-environ==0.4.3 django-nocaptcha-recaptcha==0.0.19 django-storages-redux==1.3.3 docutils==0.13.1 enum34==1.1.6 Fabric==1.13.2 feedparser==5.2.1 filebrowser-safe==0.4.7 flower==0.9.2 future==0.16.0 futures==3.1.1 grappelli-safe==0.4.6 html5lib==0.999999999 idna==2.5 ipaddress==1.0.18 jmespath==0.9.3 kombu==4.1.0 Mezzanine==4.2.3 nltk==3.2.4 numpy==1.13.0 oauthlib==2.0.2 olefile==0.44 pandas==0.20.2 paramiko==2.2.1 Pillow==4.1.1 psycopg2==2.7.1 pyasn1==0.2.3 pycparser==2.17 pycryptodomex==3.4.6 pyjwkest==1.3.6 PyJWT==1.5.2 PyNaCl==1.1.2 python-dateutil==2.6.0 python-openid==2.2.5 pytz==2017.2 requests==2.18.1 requests-oauthlib==0.8.0 s3transfer==0.1.10 scikit-learn==0.18.2 scipy==0.19.1 singledispatch==3.4.0.3 six==1.10.0 sklearn==0.0 social-auth-app-django==1.2.0 social-auth-core==1.4.0 sqlparse==0.2.3 tornado==4.5.1 tzlocal==1.4 urllib3==1.21.1 vine==1.1.4 webencodings==0.5.1 Problem is that I haven't install Django chat in my environment. Still, it is showing above error. Not only this project but in all project, I am receiving this error. I tried to reinstall all library again but … -
Pass username and password to Django RESTful backend with Angular 4 frontend
I have a functional Django backend running in localhost using Django Rest Framework (communicating with a postgreSQL server, but that's probably not relevant). At present the following console command successfully returns the JSON data I need from Django: curl -H 'Accept: application/json; indent=4' -u username:password http://127.0.0.1:8000/users/ I'm trying to replicate this in Angular 4, with this code I found in the HTTP API docs: this.http.get('http://localhost:8000/users/', { headers: new HttpHeaders().set('Authorization', 'username:password'), }) .subscribe(data => { // Read the result field from the JSON response. this.results = data['results']; }); But I'm getting a 403, with detail: "Authentication credentials were not provided." The same message that's returned when I pass in no authentication details via curl, or try to access the admin area of the REST API via the web browser without logging in first. I have made sure CORS in enabled in Django and that the Angular server at loopback:port is whitelisted. I'm fairly new to Full Stack, having only thus far successfully created a Full Stack system using Angular 4, Firebase and Angularfire 2, but the querying etc on Firebase was not sufficient for my needs. Thus I am not particularly familiar with the workings of RESTful API on a practical … -
Graphite : Internal Server Error - string 'datapoints' not found on
I've graphite server and intermittently its daemon fails with this error, HTTP CRITICAL: HTTP/1.1 500 Internal Server Error - string 'datapoints' not found on 'http://192.168.12.15:8000/render/?target=sys.example_com.snmp.if_octets-Gi0_0_0.rx&amp;format=json&amp;from=-5min' - 723 bytes in 0.002 second response time |time=0.002067s;;;0.000000 size=723B;;;0 So I restarted apache which fixed the issue. But I would like to fix the root cause of this issue, I can't restart apache every time. This is what I found in error logs, [Tue Aug 01 20:16:01] [wsgi:error] RuntimeError: populate() isn't reentrant [Tue Aug 01 20:16:21] [wsgi:error] Target WSGI script '/usr/lib/python2.7/dist-packages/graphite/wsgi.py' cannot be loaded as Python module. [Tue Aug 01 20:16:21] [wsgi:error] Exception occurred processing WSGI script '/usr/lib/python2.7/dist-packages/graphite/wsgi.py'. [Tue Aug 01 20:16:21] [wsgi:error] Traceback (most recent call last): [Tue Aug 01 20:16:21] [wsgi:error] File "/usr/lib/python2.7/dist-packages/graphite/wsgi.py", line 14, in <module> [Tue Aug 01 20:16:21] [wsgi:error] application = get_wsgi_application() [Tue Aug 01 20:16:21] [wsgi:error] File "/usr/lib/python2.7/dist-packages/django/core/wsgi.py", line 14, in get_wsgi_application [Tue Aug 01 20:16:21] [wsgi:error] django.setup() [Tue Aug 01 20:16:21] [wsgi:error] File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 21, in setup [Tue Aug 01 20:16:21] [wsgi:error] apps.populate(settings.INSTALLED_APPS) [Tue Aug 01 20:16:21] [wsgi:error] File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 78, in populate This is my /usr/lib/python2.7/dist-packages/graphite/wsgi.py, import os import sys try: from importlib import import_module except ImportError: from django.utils.importlib import import_module os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'graphite.settings') # … -
Django upgrade and 3rd party app migrations
I'm in the process of upgrading an old project from Django 1.5 to the latest version (Django 1.11). I understand the process of upgrading from South for the migrations and, in general, this has worked fine. However, I'm having some problems with a particualr 3rd party app - Django Fluent Pages - whose version I had to upgrade to get the project working. Their initial (non-South) migration contains CreateModel instructions for models that I already have in the database as well as models that they have added between the version I had and the version I've upgraded to. That means that Django tries to actually run this migration (to create the new tables) when I migrate my db but some of the tables in the migration already exists and it fails. How do I get round this? I'm using the --fake-initial argument on my migration. The problem seems to be the fluent pages initial migration file. Should that only contain the models that their initial South migration had in it? Or have I done something wrong? Surely I don't have to migrate through every single intermediate version of their app to make this work?! -
Pass a variable in an html template in django
I need to create in a html django template a form with a select dinamically created: I read values from a txt file and I store it in a dict, when I call the render to response I pass this dict but when I try to print its values in the template it doesn't print anything. This is my views: def home(request): i=0 d = {} with open("static/my_file.txt") as f: for line in f: key=i val = line.rstrip() d[int(key)] = val i=i+1 return render_to_response('home.html', var=d) and this is the print in the html template: {% for val in var %} {{ val.value }} {% endfor %} Can help me? -
AJAX gets access to Django HttpResponse variables
I am writing a small test app for a bigger project. I would like to use asynchronously FileReader() to read a txt file from client side and pass the textbody to the Django server by using AJAX. When the server succeeds to get the "posted" text, it will return the length of the text. It worked well on the server and I got what I expected. But now I would like to pass the size of the text(length) back to the client and display it somewhere on the web page asynchronously. But failed... Here is my code: HTML <script type="text/javascript"> var render_text = function(csvFile, onLoadCallback){ var reader = new FileReader(); reader.onload = onLoadCallback; reader.readAsText(csvFile); } $(document).ready(function(){ $("#id_csvFileInput").on("change", function(e){ render_text(this.files[0], function(e){ var text = e.target.result; $.ajax({ url: "", type: 'POST', async: true, data: {'text': text}, success: function(data){ $("#id_test").text(data.size); } }); }); }); }); </script> <p> <input type="file" name="csvFileInput" id="id_csvFileInput" accept=".csv"> </p> <div> <p>Waiting for reponse context....</p> <span id="id_test">?</span> </div> View.py # Home page. @csrf_exempt def home(request): template = 'hbvapp/home.html' context = {} if request.method == "POST" and request.is_ajax(): context['test'] = request.POST.get('text') context['size'] = len(context['test']) print context['size'] return render(request, template, context) else: return render(request, template) ANY HELP WILL BE DEEPLY APPRECIATED ! … -
Submit button for a formset doesn't work when generated by ajax [duplicate]
This question already has an answer here: Event binding on dynamically created elements? 18 answers I have a formset to update my models and I display forms from my formset based on the search query. I have an ajax keyup function to send post requests so I can generate search_results.html that I then pass to in search.html. Now, if I generate the forms dynamically the submit button does not work. If I ditch the search and pass the content of search_results.html to search.html directly it does work. I have two views, SearchReportView which supposed to be the main one, and SearchReports to handle generating the report. I guess I might just merge them at this point - it doesn't solve my problem though. Also I had this working before when I used multiple forms but I had to switch to a formset. body of search.html <div class="container"> <div class="navbar"> <div class="navbarItem"> <a href="{% url 'EnbListView' %}"><img src="{% static 'back.png' %}" width="20px" height="12px" \>Back</a> </div> </div> <div> <h3>Search:</h3> {% csrf_token %} <input type="text" id="search" name="search" /> <span class="button-checkbox"> <button id="mybutton" type="button" class="btn" data-color="primary">Recent</button> <input type="checkbox" class="hidden" name="reports_checkbox" checked /> </span> </div> <div class="normalText" id="search-results"></div> </div> search_results.html {% if reports_and_formset %} <form … -
Login required decorator with JWT using django and AngularJS
I have a project with AngularJS, JWT and django as back-end framework. JWT user authentication works OK. At the same time I'm trying Send $http.get('/myview/') from my angular service To myview in django which is decorated with login_required. After research I understand that it shouldn't work because request.session is not set. So the question is how can I allow to obtain requests in this view only from authenticated users? I have idea to create custom decorator in django that will check the token that will be sent within my get/post request from angular service but I have doubts that it will work. -
Django - objects.values() and prefetch_related() in same query
I have Book, Profile, Book_stat model as below. I am trying to minimize the fields from Book model and prefetch_related method to get the data from Book_stat model. models.py class Book(models.Model): title = models.CharField(max_length=200) image = models.FileField(upload_to="mp/", blank=True) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=150) def __str__(self): return self.full_name class Book_stat(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book) rating = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal('0.00')) like = models.BooleanField(default=False) def __str__(self): return self.book.title + ' by: ' + self.user.profile.full_name views.py def books(request): books = Book.objects.prefetch_related('book_stat_set').values('id','title', 'image') for book in books: for book_stat in book.book_stat_set.all(): # error here: 'dict' object has no attribute 'book_stat_set' book.stats = book_stat pprint(vars(book_stat)) return HttpResponse(books, content_type= 'json') 1) I would like to send the json response to front end as below 2) If possible i want to use book_stat_set.values('like', 'rating') instead of book_stat_set.all() so that i query for like, rating only books = [ { id: 1, title: 'some title1', image: 'image1.jpg', stats: { like: true, rating: 3.50 } }, { id: 2, title: 'some title2', image: 'image1.jpg', stats: { like: true, rating: 3.50 } } ]