Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OperationalError - cursor "_django_curs_<id>" does not exist for edit and add form
On accessing a url to add or edit form, which would render a template to edit the form gives the error - OperationalError at /edf/data_asset_format_edit// I tried running makemigrations and migrate, even after that i get the above error. I tried creating a new object for the same model from shell (python manage.py shell), it works. OperationalError at /edf/data_asset_format_edit/466/ cursor "_django_curs_140026377369344_10" does not exist Request Method: GET Request URL: https:///edf/data_asset_format_edit/466/ Django Version: 1.11 Exception Type: OperationalError Exception Value: cursor "_django_curs_140026377369344_10" does not exist Exception Location: /opt/edfprod/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py in execute_sql, line 880 Python Executable: /opt/edfprod/python/bin/python Python Version: 2.7.11 Traceback: File "/opt/edfprod/python/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/opt/edfprod/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/opt/edfprod/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/edftest/test2/ui/dna_django/edf/views.py" in data_asset_format_edit 726. return render(request, 'edf/data_asset_format_edit.html', {'form': form}) File "/opt/edfprod/python/lib/python2.7/site-packages/django/shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "/opt/edfprod/python/lib/python2.7/site-packages/django/template/loader.py" in render_to_string 68. return template.render(context, request) Views - def data_asset_format_edit(request, edf_data_asset_format_id): ... ... pa = EdfProviderDataAssetVw.objects.get(p_data_asset_id=data_asset_format.data_asset_id) form = EdfDataAssetFormatForm(instance=data_asset_format, data_asset=daf_data_asset, initial={'provider_name': pa.provider_name, 'provider_id': pa.provider_id, 'p_data_asset_name': pa.p_data_asset_name, 'p_data_asset_id': pa.p_data_asset_id, 'updated_by': User.objects.get(username=request.user)}) return render(request, 'edf/data_asset_format_edit.html', {'form': form}) I dont understand what is causing this error. -
How to perform calculation for a model field and display the value in the template?
I have a model called 'Candidate', which has the fields Experience,New Experience,Date_posted. I'm using CreateView form to store the values in the database. When I enter experience and date_posted(set to timezone.now) for the first time, the 'new experience' value should also be set to 'experience' value by default. Now this 'new experience' value should get incremented after every month. For example, experience=2.4 ( 2 years 4 months ), new experience =2.4( set automatically ), So, If I open my template(website page) 1 month from now, the 'experience' and 'date_posted' values must be same, but 'new experience' = 2.5 ( 2 years, 5 months ) Also, I want to use the format, 2.12 ( for 2 years 12 months )and 3.1 ( for 2 years 13 months ) How do I achieve this? -
500 internal error in django slug with unicode in production
I have a problem with str path converter. I have unicodes in blog's article slug. On local host everything works well but I'm getting 500 Internal Error on production. When I change slugs to ASCII characters it works fine and article page loads with no error. models.py: class Post(models.Model): ... slug = models.SlugField( max_length=128, unique=True, allow_unicode=True, ) ... urls.py: urlpatterns = [ ... path('blog/<str:slug>/', views.PostDetailView.as_view(), name='post_detail'), ] views.py: class PostDetailView(DetailView): model = Post template_name = 'post_detail.html' This is the ERROR: Internal Error The server encountered an unexpected condition which prevented it from fulfilling the request. thanks -
importing current_app from celery is gives ValueError: attempted relative import beyond top-level package
Yes I know there are lot's of similar questions on stack-overflow related to this value-error and I tried all the solutions from them but as I am new to Django and python I am not able to solve this issue. I have one project called my_backend which have the following file structure. main_project/ cmb_backend/ __init__.py celery.py urls.py second_app/ __init__.py moduleZ.py my_env/ bin/ include/ lib/ python 3.7/ site-packages/ celery/ django_celery_beat admin.py I have used celery for the periodic task so I have added one celery.py file in my main application my_backend. I have also installed django_celery_beat using pip and inside that, they have imported celery using below code. # admin.py file in the django_celery_beat lib from celery import current_app from celery.utils import cached_property so when I run this command python3 my_backend/setup_database.py it is giving me an error like ImportError: cannot import name 'current_app' from 'celery' (/Users/pankaj/Desktop/Pankaj/MyJangoProjects/My_Project/my_backend/celery.py) so from this error, I found that when I am running above command admin.py is importing current_app from celery but it is looking in the wrong file so to solve this error I am using relative import and adding .. in front of import statement but still, it's not working # admin.py file in the … -
How to get multiple files from a django FileField after model form object has been saved
I have a django ModelForm with an additional field to upload some files. However, I need the saved model before I can do anything with the files, and I'm not sure where or how to do that. I'm following the docs here. I either need to get the saved model in the FormView or I need to handle it in the Form: class MessageForm(forms.ModelForm): class Meta: model = Message file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) def save(self, *args, **kwargs): super().save(*args, **kwargs) files = self.cleaned_data.get('files') # do stuff with files here... # BUT I only get ONE file here, regardless of how many are uploaded with the form. Is there a way for me to get all the files in the Form's save method? Or, I can get all the files through the view, but how can I get the saved model that I need? This form is creating a new object, and I need that object before I can do stuff with the files: class FileFieldView(FormView): form_class = MessageForm template_name = 'upload.html' # Replace with your template. success_url = '...' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if … -
Python : How to determine the maximum threads a Django Project can spawn?
I have a Django application, in which I have implemented kafka to process some orders. Each order is associated with an offering. Now for each offering I create a topic on Kafka and assigns a new consumer to listen to that topic in a new thread. However after a certain extent let's say about 100 offering, my program is not able to spawn a new thread. RuntimeError: can't start new thread # Consumer Assignment @shared_task def init_kafka_consumer(topic): try: if topic is None: raise Exception("Topic is none, unable to initialize kafka consumer") logger.info("Spawning new task to subscribe to topic") params = [] params.append(topic) background_thread = Thread(target=sunscribe_consumer, args=params) background_thread.start() except Exception : logger.exception("An exception occurred while reading message from kafka") def sunscribe_consumer(topic) : try: if topic is None: raise Exception("Topic is none, unable to initialize kafka consumer") conf = {'bootstrap.servers': "localhost:9092", 'group.id': 'test', 'session.timeout.ms': 6000, 'auto.offset.reset': 'earliest'} c = Consumer(conf) logger.info("Subscribing consumer to topic "+str(topic[0])) c.subscribe(topic) # Read messages from Kafka try: while True: msg = c.poll(timeout=1.0) if msg is None: continue if msg.error(): raise KafkaException(msg.error()) else: try: objs = serializers.deserialize("json", msg.value()) for obj in objs: order = obj.object #Fix temporary (2006, 'MySQL server has gone away') from django.db import close_old_connections close_old_connections() … -
Can I use React with Django Framework simultaneously?
I'm learning React at the moment, and I was just wondering if I can use React with Django framework together down the line. Or, what are the recommendations/technology to use with React? -
django datepicker on datatable not working
I want to filter my datatable between two date range. I tried many codes for datepicker but nothing worked for me. When I inspected my console, I found it saying "$.fn.dataTable is undefined". Overall my datepicker is not woking in django. Please help as I'm new to javascipt. I have taken this js code from somewhere. <script> /* Custom filtering function which will search data in column four between two values */ $(document).ready(function () { $.fn.dataTable.ext.search.push( function (settings, data, dataIndex) { var min = $('#min').datepicker("getDate"); var max = $('#max').datepicker("getDate"); var startDate = new Date(data[3]) if (min == null && max == null) { return true; } if (min == null && startDate <= max) { return true;} if(max == null && startDate >= min) {return true;} if (startDate <= max && startDate >= min) { return true; } return false; } ); $("#min").datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true , dateFormat:"m/d/y"}); $("#max").datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true, dateFormat:"m/d/y" }); var table = $('#example').DataTable(); // Event listener to the two range filtering inputs to redraw on input $('#min, #max').change(function () { table.draw(); }); }); </script> <table border="0" cellspacing="5" cellpadding="5"> <tbody> <tr> <td>Minimum … -
How can we get data from multiple data base in django orm?
I want to get data from multiple databases in Django ORM Select em.EMPLOYEEID_N, tran.TRANSFERID_N,dep.HRDEPT_ID_V as HRDEPT_ID_V, dep.ACCOUNTSDEPT_ID_V as ACCOUNTSDEPT_ID_V, dep.ADMINDEPT_ID_V as ADMINDEPT_ID_V, dep.ITDEPT_ID_V as ITDEPT_ID_V,NVL(chk.HR_DPT,'N') HR_DPT, NVL(chk.ACCOUNTS_DPT,'N') ACCOUNTS_DPT , NVL(chk.ADMIN_DPT,'N') ADMIN_DPT , NVL(chk.IT_DPT,'N') IT_DPT, dep.RECIEVINGACCOUNTSDEPT_ID_V, NVL(dep.RECIEVINGACCOUNTSCHECK,'N') RECACCOUNTS_DPT, hr.UNITID_N USRUNITID,DEP.UNITID_N TFRUNITID From PYR_EMM_EMPLOYEEMASTER em,PYR_EMM_TRANSFERINOUTSTATUS tran,PYR_EMM_TRANSFERADV_CHECKLIST chk,PYR_EMM_TA_DEPTALERT dep, PYR_EMM_EMPLOYEEMASTER hr Where em.EMPLOYEEID_N = tran.EMPLOYEEID_N and tran.TRANSFERID_N = chk.TRANSFERID_N and tran.EMPLOYEEID_N = chk.EMPLOYEEID_N and tran.TRANSFERID_N = dep.TRANSFERID_N and tran.EMPLOYEEID_N = dep.EMPLOYEEID_N and hr.ACTDIRUSERNAME_V = 'ithd.ggn' and chk.UNITID_N = dep.UNITID_N and (dep.HRDEPT_ID_V = 'ithd.ggn'||'@bilt.com' or dep.ACCOUNTSDEPT_ID_V = 'ithd.ggn'||'@bilt.com' or dep.ADMINDEPT_ID_V = 'ithd.ggn'||'@bilt.com' or dep.ITDEPT_ID_V = 'ithd.ggn'||'@bilt.com' or dep.RECIEVINGACCOUNTSDEPT_ID_V = 'ithd.ggn'||'@bilt.com') -
Is it reliable to use oauth and rest framework in main web application?
I just started designing the new web application , in my old design i used sessions, web page rendered in back end, now we thought to design using REST and oauth , normally i found that oauth and REST and using to integrate with third party services/application, so my question is can i do it in my main web front end in building in angular, and api services in rest and oauth? , is it reliable ? -
Unable to compare xls data from a cell with unicode string
I am importing a .xls file and want to perform some checks on data written in specific cells. I did this: wb = xlrd.open_workbook('foobar.xls') sheet = wb.sheet_by_index(0) if sheet.cell_value(0, 3) != u'special' or sheet.cell_value(0, 3) != u'Special': error_msg = 'The fourth column head should say "special"' This throws error all the time even if the cell does say 'special' I even did print(sheet.cell_value(0, 3)) to double check. And type(sheet.cell_value(0, 3)) shows its unicode, which is why im doing u'special'. Why is the if statement always true? please help. -
Why my menus are not showing in internal pages?
I am new to Django and I created category, Subcategory in my Django app, but the main issue is this my all category and subcategory are showing on home page view, but when i click on any subcategory it's open new page, then nothing is showing in menus. All category and subcategory are hiding from navigation. Please let me know what is this issue, I am unable to solve this issue. -
How can I install MySQLClient?
This is for a starter Django project. I've installed the virtual enviroment and run the server. Now the tutorial I'm using recommends that I install mysqlclient instead of the pre-installed sqllite3 and I want to follow allong exactly. I run the command pip install mysqlclient and get the following output: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/4d/38/c5f8bac9c50f3042c8f05615f84206f77f03db79781db841898fde1bb284/mysqlclient-1.4.4.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\alex\envs\py1\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Alex\\AppData\\Local\\Temp\\pip-install-7u7ymyig\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\Alex\\AppData\\Local\\Temp\\pip-install-7u7ymyig\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Alex\AppData\Local\Temp\pip-wheel-ya5ndkrz' --python-tag cp37 cwd: C:\Users\Alex\AppData\Local\Temp\pip-install-7u7ymyig\mysqlclient\ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb E:\Programs\VisualStudio\VC\Tools\MSVC\14.22.27905\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Dversion_info=(1,4,4,'final',0) -D__version__=1.4.4 "-IC:\Program Files (x86)\MySQL\MySQL Connector C … -
Permission classess decorator is ignored. "Authentication credentials were not provided" response
I am using Django Rest Framework for my API service. In my settings.py I've got following REST_FRAMEWORK setting: REST_FRAMEWORK = { ... 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ) ... } Now I want to change permission classes to allow anyone to use one view. I had used @permission_classes decorator. class UserViewSet(viewsets.ModelViewSet): serializer_class = RegisterSerializer queryset = User.objects.all() @permission_classes([permissions.AllowAny,]) def create(self, request, *args, **kwargs): data = request.data ... I should be able to perform create action without any permissions. Instead I receive Authentication error when try to access the API. "detail": "Authentication credentials were not provided." According to docs @permission_classes decorator is correct way for such permission overriding. This is Django 2.2.4 and DRF 3.10.2. -
Python3 Django: Getting Invalid Salt Error Bcrypt
I'm making a miniter. I'm making an api by encrypting password, and I'm testing it with httpie. In bcrypt.checkpw(password.encode('UTF-8'), account_exists_id.get().password.encode("UTF-8") is There is an invalid salt error. How do you approach it? Actually, I encrypted my password and put it in db, but I don't know how to test it yet. class login_post(View): def post(self, request): data = json.loads(request.body) user_id = data['user_id'] password = data['password'] account_exists_id = Account.objects.filter(user_id = data['user_id']) if account_exists_id.exists() and bcrypt.checkpw(password.encode('UTF-8'), account_exists_id.get().password.encode("UTF-8")): user_id = account_exists_id.get().user_id payload = { 'user_id': user_id, 'exp' : datetime.utcnow() + timedelta(seconds = 60 * 60 * 24) } token = jwt.encode(payload, 'SECRET_KEY') return JsonResponse({"access_token" : token.decode('UTF-8')}) else: return JsonResponse(status = 401) Traceback (most recent call last): File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/gapgit/miniconda3/tweet_copy/tweet_project/login/views.py", line 25, in post if account_exists_id.exists() and bcrypt.checkpw(password.encode('UTF-8'), account_exists_id.get().password.encode("UTF-8")): File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/bcrypt/init.py", line 107, in checkpw ret = hashpw(password, hashed_password) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/bcrypt/init.py", line 86, in hashpw raise ValueError("Invalid salt") -
Toggle Image On-click Using JavaScript/Jquery in list of divs
I am new to web language and need help with toggling image. So I have a list of divs displaying images, and the source of the image is from a database. I want the image to toggle in a way to replace the url from the database with another url from the same database table (e.g. switch before_url to after_url). I have tried a few ways and the closest I got is click on one image, but it updates for all elements.. The code below is something I've tried (yes I'm trying to toggle by clicking button) some CSS: .card { box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); padding: 16px; } .card:hover { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2); } HTML: <div class="row"> {% for c in card_list %} <div class="column"> <div class="card"> <img class="myCard_before" src="{{ c.img_url_before }}" style="width:100%;" /> <img class="myCard_after" src="{{ c.img_url_after }}" style="width:100%;display:none" /> <div class="container"> <h4>{{ c.card_title }}</h4> <input class="button" type="button" onclick="changeImg1() "value="before" /> <input class="button" type="button" value="after" /> </div> </div> </div> {% endfor %} </div> JS: <script> var elements = document.getElementsByClassName("card"); console.log(elements); for(var i = 0; i < elements.length; i++) { elements[i].onclick = function(event) { this.classList.toggle('red'); this.classList.toggle('myCard_afterEvol'); } } function changeImg1() { for (var i = … -
How to convert "127.0.0.1:8080" to www.projectname.com" on local?
How can i change URL django running server from 127.0.0.1:8080 to http://www.projectname.com ? -
AJAX Django Delete Function is Not Deleting the Object
I am trying to delete an object with a close button and it was working without using AJAX but I had to reload the page in order to reflect some changes in my methods. When I applied AJAX, it was no longer deleting. views.py elif request.method == 'DELETE': id = json.loads(request.body)['id'] project = get_object_or_404(Project,id=id) project.delete() return JsonResponse('') profile.html <a onclick="deleteProject(this)" data-id="{{project.id}}" class="close col-sm-2" aria-label="Close"> <span class="card-block float-right" aria-hidden="true">&times</span> </a> ... <script> $(document).on('.close',function(e){ e.preventDefault(); $.ajax({ type:'DELETE' url:'user/profile' data: { 'id' : id } success: function deleteProject(e) { let id = e.dataset.id e.closest('li').remove() fetch('',{ method: 'DELETE', headers: { 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'id': id }), credentials: 'same-origin', }) } }); }); </script> Is there something wrong with the way I am using AJAX with Django? It works when I just keep everything from "function deleteProject(e)..." but I don't want to have to reload the page to show how the number of projects and total budget changes. Is there a way I can fix this or maybe an alternative to using AJAX? -
How to perform CRUD operations in mysql django project?
Please post a code for performing the crud operations in django with mysql database ... Add Upadate Delete Create -
How can I reload python code in dockerized django?
I am using docker-compose to run 3 containers: django + gunicorn, nginx, and postgresQL. Every time I change my python .py code, I will run docker-compose restart web but it takes a long time to restart. I try to restart gunicorn with docker-compose exec web ps aux |grep gunicorn | awk '{ print $2 }' |xargs kill -HUP . But it didn't work. How can I reload .py code in a shorter time? I know that gunicorn can be set to hot reload python code. Can I do it manually with a command? -
Is it able to build models like this by using django rest framework?
I want to builds some models like these: tbl_Book: ID Title Author Category 1 Lazy Ant Tom Story 2 Python3 for beginner Sam IT 3 Knowledge about Cat & Dog Kay Animal tbl_Story: ID BookID AgeRangeID 1 1 3 2 1 4 tbl_IT: ID BookID Language 1 2 Python tbl_Animal: ID BookID AnimalType 1 3 Cat 2 3 Dog will have more categories…. And when I make a post call, the content will be something like: {"Title":"Lazy Ant","Author":"Tom","Category":"Story","story_content":[{"AgeRangeID":3},{"AgeRangeID":4}]} I have checked some about foreignkey, relation and join but seems not match with what I want. Currently I have in models.py: class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) author = models.CharField(max_length=50) Category= models.CharField(max_length=20) class Meta: db_table = "tbl_Book" def __str__(self): return str(self.id) class Story(models.Model): id = models.AutoField(primary_key=True) book_id = models.ForeignKey(Node,related_name='story_content',on_delete=models.CASCADE,db_column='book_id') AgeRangeID = models.IntegerField(db_column=AgeRangeID') class Meta: db_table = "tbl_Story" in serializer.py: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id','Title','Author','Category') class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = ('id','book_id','AgeRangeID') Please let me know what I should add or correct. -
How to make authentication token available to web based client on future requests? Server is running Django + Django Rest Framework
I've got a nice REST API that I made using django-rest-framework, and interacting with it from a local client is simple - just request a token from the API endpoint and then add that token to the HTTP headers when you make requests using curl or httpie or something. I've written some wrappers that look like so: token = getAPIToken(username, password) data = getDataFromEndpoint(resourceID, token) postDataToEndpoint(resourceID, data, token) My problem is that I can't figure out how to consume this API from the browser or the server. For example, I want the user to be able to POST a form to someView and then have that view conditionally call call one of the aforementioned wrappers. The problem is that the server can't get a token without prompting the user for a password every time - all it knows is the request.user field that Django gave it, and even that only if I have SessionAuthentication enabled. Somehow I need to tell the client to include the "Authorization: Token XXXX" header on every future HTTP request after they log in. One option I've considered: Django's default login view uses sessions, so I suppose I could hack up that view to call my … -
Is there any method which can help me in domain rendering for php to django (python)?
i have a website which is in django(python) excatly like https://www.byond.travel/ now i have another website which is in php https://blog.byond.travel/ now i want to change this php website into (https://www.byond.travel/blog) so what can i do. do i need to config server again or i can render domain in django any suggestions ? -
How to validate and serialize recursive many to many relationship using Django REST framework in a most optimal way?
I have a model CitizenInfo that contains a field 'relatives' with many to many relationship on itself. When i do a POST request what i want is to validate and deserialize the raw data from JSON using the optimal way. What i found so far is a library for recursive model fields. https://github.com/heywbj/django-rest-framework-recursive and this not super informative topic https://github.com/encode/django-rest-framework/issues/4183 This is my POST request: [ { "citizen_id": 1, "name": "Dave", "relatives": [2] }, { "citizen_id": 2, "name": "Jack", "relatives": [1, 3] }, { "citizen_id": 3, "name": "Alex", "relatives": [2] } ] model.py: class CitizenInfo(models.Model): citizen_id = models.PositiveIntegerField(primal_key=True) name = models.CharField(max_length=255) relatives = models.ManyToManyField('self', blank=True) views.py class CitizenInfoImportView(APIView): def post(self, request): # Because of many=True we will use BulkCitizensSerializer serializer = CitizenListSerializer(data=request.data, many=True) if serializer.is_valid(): serializer_response = serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py # Using this function for bulk_save operation def save_citizens(citizen_data): new_citizen = CitizenInfo(citizen_id=citizen_data.get('citizen_id'), name=citizen_data.get('name')) # Looping through relative list and do some custom serialization for relative in citizen_data.get('relatives'): pass return new_citizen class BulkCitizensSerializer(serializers.ListSerializer): def create(self, validated_data): new_citizens = [save_citizens(citizen_data) for citizen_data in validated_data] return CitizenInfo.objects.bulk_create(new_citizens) class CitizenListSerializer(serializers.ModelSerializer): class Meta: model = CitizenInfo field = '__all__' list_serializer_class = BulkCitizensSerializer Also i had a limit that for one request … -
Obtaining number of errors in template with template tags
I'd like to use a template tag to only show certain html if the form doesn't load with errors. I've got this in def clean(): forms.py home_zipcode = cleaned_data.get('home_zipcode') if ' ' in home_zipcode: self.add_error('home_zipcode', "Please remove all spaces from the Zip Code.") raise forms.ValidationError('Please review the errors below.') template {% if no errors %} some html {% endif %} Do you know what template tag I would use to do this?