Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
html table search using <a>
<div id="changelist-filter"> <h2>SEARCH BY:</h2> <h3> By Student Users </h3> <ul id="myUL"> <li class="selected"> <li> <a href="?Student_Users__id__exact=6" title="" id="myInput" onclick="myFunction()">Mark Joshua</a></li> <li> <a href="?Student_Users__id__exact=5" title="">Bea mae</a></li> <li> <a href="?Student_Users__id__exact=4" title="Marvin Salvahan Makalintal">John Mark</a></li> </ul> </div> <table id="result_list"> {% for student in studentsEnrollmentRecord %} <tr> <td class="action-checkbox"></td> <th class="field-lrn">{{student.Student_Users.lrn}}</th> <td class="field-Student_Users nowrap">{{student.Student_Users}}</td> <td class="field-School_Year nowrap">{{student.School_Year}}</td> <td class="field-Courses nowrap">{{student.Courses}}</td> <td class="field-Section nowrap">{{student.Section}}</td> <td class="field-Payment_Type nowrap">{{student.Payment_Type}}</td> <td class="field-Education_Levels nowrap">{{student.Education_Levels}}</td></tr> </table> <script> function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("result_list"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> I have this code in my html, I just want if the user click the "Mark Joshua" it will search to the table if it is exist or not, please help me. -
Remember number of items as the previous one entered in form if no number of items is inputed from post
I have a form accepting the number of items to be listed on the page. I have implemented this form in a template (lets say it show.html).As the page is called initially it doesn't accept any value so i display the 5 list items by default.But the trouble comes as i am using the pagination . The pagination doesn't have any relation with form so when i click next in pagination the default value which is set by default( ie 5 in this case) when no post action is called is getting executed.My requirement is such that (at first i display 5 items).Then when i give value to the input box it must be remembered and this value must used to do the number of list items until and unless i change the number of items in the list. view def show(request): category_list= Category.objects.all() count= request.POST.get('noofitems',5) //number of items is 2 if no post request is send paginator = Paginator(category_list, count) # Show 25 contacts per page page = request.GET.get('page') categories = paginator.get_page(page) return render(request,"show.html",{'category':categories}) Form ------- <form action="/show" method="post"> {% csrf_token %} <label >Number of items </label> <input type="text" name="noofitems" /> <input type="submit" value="OK"/> </form> -
build Filter using Django RestFramework and Angular fronted
i try build a filter for my fronted Angular from Django backend, or how i can build filter using restframework_filter please people help , i have this in the backend viewset.py from snippets.models import Snippet from .serializers import SnippetSerializer from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from django_filters import rest_framework as filters class SnippetFilter(filters.FilterSet): class Meta: model = Snippet fields = { 'title': ['icontains'], 'created': ['iexact', 'lte', 'gte'], } class SnippetViewSet(viewsets.ModelViewSet): queryset = Snippet.objects.all() serializer_class = SnippetSerializer filterset_class = SnippetFilter @action(methods=['get'], detail=False) def newest(self, request): newest = self.get_queryset().order_by('created').last() serializer = self.get_serializer_class()(newest) return Response(serializer.data) -
Reconciling Global and Virtual uWSGI installs
Deploying Django backend to an Ubuntu 18.04 AWS EC2. uWSGI, NGINX, and Django (everything) works fine when I launch from my pipenv shell's virtual environment. When I try to use a global uWSGI install for automated startup, uWSGI fails with the apparently common "module not found" error. Ubuntu system python is 2.7.15. My app runs 3.7.3 and runs virtual install of uWSGI compiled with 3.7.3. I compiled a python3 uWSGI plugin from here: https://www.paulox.net/2019/03/13/how-to-use-uwsgi-with-python-3-7-in-ubuntu-18-x/ It fires, but still reports using python 2.7 (see example below). I built an .ini and I've tried so many different combinations of settings, I lost track of which ones. I've tried setting the virtual environment in python path twice. I've tried setting different uWSGI binaries. I've adjusted permissions. Here is what it currently looks like: [uwsgi] pythonpath=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9-/lib/python3.7/site-packages pythonpath=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9-/lib/python3.7/site-packages plugins=python37 binary-path=/usr/bin/uwsgi virtualenv=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9- pythonpath=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9-/lib/python3.7/site-packages chdir=/home/dpcii/tube-backend-django/ module=video_backend.wsgi:application home=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9- master=false processes=10 threads=2 socket=video_backend.sock chmod-socket=666 vacuum=true When I fire up the Emperor using global (instead of python environment) uWSGI executable, this is what I get: *** Starting uWSGI 2.0.15-debian (64bit) on [Mon Oct 28 12:57:50 2019] *** compiled with version: 7.3.0 on 28 September 2018 15:41:15 os: Linux-4.15.0-1051-aws #53-Ubuntu SMP Wed Sep 18 13:35:53 UTC 2019 nodename: ip-172-30-0-12 machine: x86_64 … -
Adding tests and testing django-polls as its own package
Django newb here who recently finished the tutorial on the Django website. I was able to follow all 7 parts and then in the advanced tutorial I made the polls app its own package. Going through the 7 parts in order means that you test the polls app while it is still part of the overall django project and uses the project's settings with no issue. So I had no problem testing the polls app. Now that I've made the polls app into its own separate package, I'm confused as to how to test it exactly. Let me explain. In part 5 I was able to test the polls app while it was still inside the mysite project. To do so, I would run python manage.py test polls from the mysite directory, and that manage.py file contained the line os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings'). In other words, the polls app testing relied on the general project's settings at mysite/mysite/settings.py. Then, like I said, eventually the polls app became its own package (as instructed by the advanced tutorial). I was able to separate out everything related to the polls app and everything has been fine. Except now I decided to go back and add … -
Django - How to re-render a page to display data based on a form's field?
I have a form in which the first field is the User's ID #. What I'm trying to achieve is displaying the name on top of the field where they enter they number but I'm not sure how to do this. I was thinking about maybe somehow refreshing the page once the user tabs/clicks out of the field, but I don't know if there would be a more efficient way that could render in real time, in case the user fills out other fields before their ID# field. Currently, I have this in my views to get the User's name based on their #, but I'm not sure how to use this in the html part, or if something else needs to be modified too views.py def get_e_name(request): e_number = request.POST.get('e_number') e = Saved.objects.get(a_number=e_number) e_name = e.saved_name return e_name -
Django can not create test databse using MySQL
I'm developing a large Django project and I'm beginning to write some tests. But I ran into a problem when running them. When I run python manage.py test I get the following error: $ project/ python manage.py test project/env/lib/python3.7/site-packages/django/db/models/base.py:319: RuntimeWarning: Model 'accounts.manager' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_partyadvisor'; database exists") Type 'yes' if you would like to try deleting the test database 'test_partyadvisor', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "project/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "project/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "project/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 312, in _query db.query(q) File "project/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 224, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'content' used in key specification without a key length") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line … -
Cannot Install psycopg2 in virtualenv in windows
I am trying to install Psycopg2 in my VirtualEnv, initially i was facing error it could not find pg_config.exe and i solved it by adding complete path in PATH. But then it gave error Microsoft Visual C++ 14.0 is required. To remove this i have Installed VC_redist.x64 VC_redist.x86. I have also installed C++ development modules in VS community. but it still gives this Error. My Environment: Windows 10 SL, Python 3.8.0, VirtualEnv 16.7.7, pip 19.3.1 psycopgmodule.obj : error LNK2001: unresolved external symbol _PQfreemem psycopgmodule.obj : error LNK2001: unresolved external symbol _PQencryptPasswordConn psycopgmodule.obj : error LNK2001: unresolved external symbol _PQencryptPassword psycopgmodule.obj : error LNK2001: unresolved external symbol _PQinitOpenSSL psycopgmodule.obj : error LNK2001: unresolved external symbol _PQconninfoParse psycopgmodule.obj : error LNK2001: unresolved external symbol _PQerrorMessage psycopgmodule.obj : error LNK2001: unresolved external symbol _PQlibVersion psycopgmodule.obj : error LNK2001: unresolved external symbol _PQconninfoFree green.obj : error LNK2001: unresolved external symbol _PQclear pqpath.obj : error LNK2001: unresolved external symbol _PQbinaryTuples pqpath.obj : error LNK2001: unresolved external symbol _PQsetnonblocking pqpath.obj : error LNK2001: unresolved external symbol _PQgetvalue pqpath.obj : error LNK2001: unresolved external symbol _PQresultStatus pqpath.obj : error LNK2001: unresolved external symbol _PQoidValue pqpath.obj : error LNK2001: unresolved external symbol _PQcmdStatus pqpath.obj : error LNK2001: unresolved … -
How to dynamically pass in Model class name in Django view
"""Please, I have created some model classes in my django app.models. I want to access to objects of any of the models in my views based on request. My view looks like this: def profile(request, course): Course_name = course Contents = model.objects.get() context = {obj: contents} return render(request, "pro.html", context) """My question is, I want to replace model in model.objects.get() with the variable "course_name" But am getting this error, 'str' object has no attribute 'objects' Please Help""" -
Django-Rest-Framework File Upload
I am using Django Rest Framework to upload a file My view file looks like this: class FileViewSet(viewsets.ModelViewSet): queryset = Files.objects.all() serializer_class = FilesSerializer #+++++++++++++++++++++++++++++++++++++ parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): serializer = FilesSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) else: return Response(serializer.error, status=HTTP_400_BAD_REQUEST) My view works well with file upload even if there is no bottom part of the comment. So why should I use the code under the comment? I used the translator. Please understand if there is a mistake. -
Django subquery annotation - Set default value if no result
Is it possible to set the default value on a subquery if no result is returned? for example in the below query I would like the annotation to say 'Down' as a string if there is no record. active_circuit = Subquery( DeviceCircuitSubnets.objects.filter(device__site_id=OuterRef('id'), \ active_link=True, \ circuit__decommissioned=False ).values('circuit__name')[:1]) site_data = Site.objects.all().annotate(active_circuit=active_circuit) the above could return, where down is actually a annotation that did not have a record site | active_circuit --------------------------- London | Fibre Manchester | 4G Edinburgh | Down -
Auto added primary key trying to insert the value of NULL
I have a Django site, and am using windows auth for it. When I try to logon as a new user it gives the error Cannot insert the value NULL into column 'id', table 'table.auth_user'; column does not allow nulls. INSERT fails. One other thing to mention is that that I have a separate db for my Auth (but the AuthDB is the default one). models.py class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' def __str__(self): return self.username In settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'AuthDB', 'HOST': 'MyHost', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'driver':"ODBC Driver 13 for SQL Server", }, 'CONN_MAX_AGE': 60, }, I am not sure why django is trying to insert the value of NULL into the the auto added primary key id. Maybe I am missing something? Does anyone have any idea why? Thanks for the help! -
Loading image with blob and arraybuffer on django doesn't work
Now I have to load images on html with some headers, so I used blob and arraybuffer method to load it instead of simply linking with img src. But it doesn't seem to work well because: On blob method, Request status is 0 and ready status is not always DONE. On arraybuffer method, onload is not called in any browser. I'm sure that link is not broken, because I tested it with python with same url and headers. This is the code: <script type="text/javascript"> function getimg(linksrc,imgid){//using arraybuffer var oReq = new XMLHttpRequest(); oReq.open("GET", linksrc, true); oReq.setRequestHeader('User-Agent',"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"); oReq.setRequestHeader('Referer',"https://dccon.dcinside.com/"); oReq.setRequestHeader('Sec-Fetch-Mode',"no-cors"); // use multiple setRequestHeader calls to set multiple values oReq.responseType = "arraybuffer"; oReq.onload = function (oEvent) { var arrayBuffer = oReq.response; // Note: not oReq.responseText if (arrayBuffer) { var u8 = new Uint8Array(arrayBuffer); var b64encoded = btoa(String.fromCharCode.apply(null, u8)); var mimetype="image/png"; // or whatever your image mime type is document.getElementById(imgid).src="data:"+mimetype+";base64,"+b64encoded; } }; alert("aa") oReq.send(null); } function getimg2(linksrc,imgid){ var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; //so you can access the response like a normal URL xhr.onreadystatechange = function () { if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { alert("inin"); var … -
Django: Model Queryset to Pandas to Django Rest Framework
I am trying to accomplish the following workflow in my Django project: Query my database Convert the returned queryset to a pandas dataframe in order to perform some calculations & filtering Pass the final dataframe to Django REST API Framework if I understand correctly, I have to use django-pandas for Step 2. and Django REST Pandas for Step 3. I installed both and read the documentaton, but I have no clue how to make it work. What I have achieved to far is to set up my model, views, serializes and urls to have the original queryset rendered via the Django Rest Framework. If anyone could give me a hint on how to integrate pandas in this workflow, it would be highly appreciated. my models.py file from django.db import models class Fund(models.Model): name = models.CharField(max_length=100) commitment_size = models.IntegerField(blank=True, null=True) commitment_date = models.DateField(blank=True, null=True) def __str__(self): return self.name my views.py file from rest_framework import generics from rest_framework.views import APIView from pages.models import Fund from .serializers import FundSerializer class FundAPIView(generics.ListAPIView): queryset = Fund.objects.all() serializer_class = FundSerializer my serializers.oy file from rest_framework import serializers from pages.models import Fund class FundSerializer(serializers.ModelSerializer): class Meta: model = Fund fields = ('name', 'commitment_size', 'commitment_date') -
django-rest-framework auto generate html id / css
I'm trying to assign css styling to html generated by the django-rest-framework. Rendering a form in django generates html where the html controls have an id based on the form field name. The documentation that describes that is in the "Form rendering options" section of the documentation: https://docs.djangoproject.com/en/2.2/topics/forms/ I'm using the id to assign css styling to html controls. Is there similar functionality in django-rest-frammework ? I am rendering an object using a template (code below) but the html does not have any id tags. ''' @api_view(('GET',)) @renderer_classes([TemplateHTMLRenderer, JSONRenderer]) def snippet_detail (request, pk, format=None): snippet = django.shortcuts.get_object_or_404 (Snippet, pk=pk) if request.accepted_renderer.format == 'html': return Response({'serializer':SnippetSerializer (snippet), 'snippet':snippet}, template_name='company.html') serializer = SnippetSerializer (instance = snippet) return Response (serializer.data) ''' Is there another way to assign css to the html generated by django-rest-framework? Thanks. -
How to activate a virtual environment using Python
I am struggling to activate my virtual environment located here C:\Users\HP\project1_env. I have tried the following commands - Microsoft Windows [Version 10.0.17134.165] (c) 2018 Microsoft Corporation. All rights reserved. C:\Users\HP>project1_env\scripts\activate C:\Users\HP>project1_env\scripts\activate.bat C:\Users\HP>cd project1_env\scripts\activate The directory name is invalid. C:\Users\HP>cd C:\Users\HP\project1_env\Scripts C:\Users\HP\project1_env\Scripts>activate C:\Users\HP\project1_env\Scripts>cd C:\Users\HP\project1_env\Scripts\activate The directory name is invalid. C:\Users\HP\project1_env\Scripts>C:\Users\HP\project1_env\Scripts\activate.bat Does anyone have any other suggestions? -
Django cache data for answers?
I have the following problem: I made a crud with django rest framework, and everything works great, but there are times (most of the time) that I make POST requests to save data and django replies that the data was saved and everything That's right, but when I try to make a GET request to get the data back and see if they exist, I DON'T SHOW THEM. My solution in development mode was to stop my process (python3 manage.py runserver) and turn it on again so that now it can show me the data. The problem got bigger when I already launched my application to production and the same thing happens on my server (in Digitalocean) and I can't turn off and on every moment the server. I have my urls configured as the documentation shows. In the same way I have my viewsets and serializers but I still don't understand what is happening ... Is it some kind of cache on the server? Is there a way to correct it? What am I doing wrong? Thank you -
django admin site: Is it possible that i can display two models here?
How to I display another listview here? or it is impossible? -
Django - How can I render User's name after they enter their ID #?
This is more of a guidance question. I have an app in which a user can enter their ID # and a few other fields to submit. What I'm trying to achieve is that, once the user types their 6 digit number and tabs/clicks out of the field, it displays the User's name (a field already existing in the db, connected to their ID #). How can I go about rendering this in real time, and also requesting this information from the database? -
invalid literal for int() with base 10: '' in Django on Postgres, but not SQLite
I have been running a Django app for a couple of years and it has suddenly started to throw errors when I am updating the Postgres database used to drive the live site. When I am testing using the SQLite database there are no issues. Whenever I try to make any changes to the database objects I get a invalid literal for int() with base 10: '' error. This is the traceback I am getting: Traceback: File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File ".\Indicators\views.py" in edit_indicator 227. indicator_to_be_edited.save() File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\base.py" in save 806. force_update=force_update, update_fields=update_fields) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\base.py" in save_base 836. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\base.py" in _save_table 903. forced_update) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\base.py" in _do_update 953. return filtered._update(values) > 0 File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\query.py" in _update 664. return query.get_compiler(self.db).execute_sql(CURSOR) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 1191. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 863. sql, params = self.as_sql() File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\sql\compiler.py" in as_sql 1157. val = field.get_db_prep_save(val, connection=self.connection) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\fields\__init__.py" in get_db_prep_save 770. prepared=False) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\fields\__init__.py" in get_db_prep_value 762. value = self.get_prep_value(value) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value 1853. return int(value) Exception … -
Django. Sentry. How can I pass user agent info into using sentry sdk?
I use this code to setup sentry sdk sentry_sdk.init( sentry_dsn, environment=sentry_env, release=release, send_default_pii=True, integrations=[ LoggingIntegration(event_level=WARNING), DjangoIntegration(), CeleryIntegration(), ], ) Usage of send_default_pii=True helped me to send user info, but browser still unknown (img with that view) request.header contains the User-Agent param -
Best practice for accessing submitted form data in django for use before saving to database
I am developing an app in Django where I am suppose to save user Invoice details to database. One of the inputs from the user is a selection of payment type. I am supposed to pick this selection value and retrieve amount from database before I save to invoice. This what I have done so far. It is working well, but I am really doubting if this is the right way to do it. Models.py class Invoice(models.Model): invoice_status_choices = [ ('1', 'Pending'), ('2', 'Paid'), ('3', 'Cancelled') ] invoice_number = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True) description = models.CharField(max_length=100, blank=True) customer = models.ForeignKey(User, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) paid_amount = models.DecimalField(max_digits=15, decimal_places=2, default=0) invoice_status = models.IntegerField(choices=invoice_status_choices, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.invoice_number) class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) listing = models.ForeignKey('listings.Listing', on_delete=models.CASCADE) payment_type = models.ForeignKey('SubscriptionType', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(default=1) def __str__(self): return f'{self.invoice.invoice_number} Items' class SubscriptionType(models.Model): subscription_type = models.CharField(max_length=20) frequency = models.PositiveIntegerField() period = models.ForeignKey(PeriodNames, on_delete=models.CASCADE) rate = models.DecimalField(max_digits=6, decimal_places=2, default=0) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subscription_type Here is the view that I need help with. The point … -
Django ImportError: No module named 'webapp_credentials'
I am running this code: https://github.com/cndreisbach/call-for-service/blob/master/docs/src/development.md When im running this part of code in my Vagrant shell : python3 ./cfs/manage.py migrate --settings=cfs.settings.local It's returning me that there is no "ImportError: No module named 'webapp_credentials'" This is the error : Traceback (most recent call last): File "./cfs/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/vagrant/cfs/cfs/settings/local.py", line 1, in <module> from .base import * File "/vagrant/cfs/cfs/settings/base.py", line 15, in <module> from webapp_credentials import creds ImportError: No module named 'webapp_credentials' Is webapp_credentials supposed to be a module of Django how do i fix this? -
Django REST Framework - Limit for Nested Serializer
I have the following models.py: class Category(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) class Movie(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) category = models.ForeignKey(Category,related_name='movies', on_delete=models.CASCADE, blank=True, null=True) As you can see, there is a ForeignKey relationship between the two classes. A Category can have multiple movies, but a Movie belongs to only one Category. My serializers.py looks like the following: class CategorySerializer(serializers.HyperlinkedModelSerializer): movies = MoviesSerializer(many=True, read_only=True) class Meta: model = Category fields = ('url','id','created','name', 'movies') class MovieSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Movie fields = ('url','id','created','name', 'category') So, I have nested serializers. When I deserialize the content of the categories, then it shows me also the nested movies in the JSON output as I expected. But it shows me ALL movies belonging to a particular category in the JSON output. How can I limit this number ? I tried this solution but it did not worked for me because I use serializers.HyperlinkedModelSerializer. In that provided solution they used serializers.ModelSerializer. I got this error when I tried that solution: AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. -
Use Vue for loop with Django Variable
I use vue together with django. To simplify code, I like to iterate over vue data and use the data as variable for a getattr on a python object. What I tried is the following. <div v-for="field in fields" class="col-md-3"> {% lookup myobject <%field.name%> %} </div> But this doesn't work as django tells me: Could not parse the remainder: '<%field.name%>' from '<%field.name%>' my delimiters are "<%","%>"