Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Click a button and run a python function from views.py with JS/ajax in django
I've been reading this days about how can I call a python function when I press a button and I'm very confused. One of the things that I saw is that I have to use ajax and most of the people use jquery to do it. If I understood correctly the structure has to be similar to this, $(document).ready(function() { $.ajax({ url: '', type: '', data: {'A':0}, datatype:'', success: function(resp){ console.log(resp); } }); }); With this information, my final code is, views.py def vista_sumar(request): if request.method == 'POST': a = request.POST['a'] b = request.POST['b'] c = a + b ctx = {'Result':c} return render(request,'main.html',ctx) urls.py from project.views import vista_sumar urlpatterns = [ path('prueba/',vista_sumar), ] main.html <input type="button" value="PRUEBA" class="boton"> <script src="{% static '/js/jquery-3.4.1.min.js' %}"></script> <script type="text/javascript" src="{% static '/js/filters.js' %}"></script> filters.js (the big fail) $('#prueba').click(function() { alert('boton is working') a =1; b =3; $.ajax({ method: 'POST', url: '/../../prueba/', data: { 'a': a, 'b': b, }, dataType: "json", success: function(response) { alert(response.Result); } }); }); I know the button is working because the first alert is working. The problem is when I use ajax. The code error is 403=Forbbiden and is failing in the ajax.send() Can somebody help me? Thank you … -
Renamed Django directory root - ImportError: cannot import name 'python_implementation' from 'platform'
I renamed my project and my directory using Pycharm refactor functions, and now it's broken. I changed all the dependencies I could find, however there seems to be some funky stuff going on with the error and I absolutely cannot figure it out. The error message: Traceback (most recent call last): File "C:/Users/user1/Projects/platform_back/manage.py", line 21, in <module> main() File "C:/Users/user1/Projects/platform_back/manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\__init__.py", line 37, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\user1\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 3, in <module> from django.core.management.commands.runserver import ( File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\commands\runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\servers\basehttp.py", line 14, in <module> from wsgiref import simple_server File "C:\Users\user1\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 17, in <module> from platform import python_implementation ImportError: cannot import name 'python_implementation' from 'platform' … -
How to use slug in django-rest-framework?
I am very new to django rest framework.I was using slug instead of pk in the django application.Now in DRF I also want to use the slug.Before I was using autoslug from django-autoslug package and which was working fine but I am just wondering is django-autoslug can be used in Django Rest Framework also? models.py class A(models.Model): field = models.CharField(max_length=255) slug = AutoSlugField(populate_from='field') Can I implement slug like this in my DRF also? -
How to return data in custom json format?
Models class Transaction(models.Model): created_at = models.DateTimeField() transaction_type = models.ForeignKey( TransactionType, on_delete=models.CASCADE ) class TransferSerializer(serializers.ModelSerializer): class Meta: model = Transfer fields = ('transfer_type', 'debit', 'credit', 'amount', 'currency_code') Serializers class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = '__all__' class Transfer(models.Model): transaction_id = models.ForeignKey( Transaction, on_delete=models.CASCADE ) debit = models.ForeignKey( Account, on_delete=models.CASCADE, related_name='debit' ) Views class TransactionViewSet(viewsets.ModelViewSet): queryset = Transaction.objects.all() serializer_class = TransactionSerializer pagination_class = LimitOffsetPagination How to return data with following json format? What is the best approach? { "created_at": "2019-08-18", "transaction_type_id": "1", "transfers": {"debit": "100"}, } -
There is e-government system is open source?
I need open source in GitHub , written in modern language like #python , please give me best systems ^__^; -
How to normalize and load pandas DataFrame into Django backend
I have found a lot of code samples looking to load a pandas DataFrame into a Django backend as a whole table ( not breaking up the table and normalizing the data into separate tables with foreign key relationships ). I am not sure that this is the most efficient way to store pandas DataFrame tables in a db. I believe it should be broken down into separate tables and connected via a ForeignKey. Is there any python library that will do this for you ? What would be a good approach to achieve this ? -
I have problems installing Django
I installed everything that was needed for installing Django with these commands: sudo apt-get install python3 python3-pip pip install Django pip --version pip 19.1.1 from /home/ion/anaconda3/lib/python3.7/site-packages/pip (python 3.7) And I tried to install with pip3 install Django pip3 --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6) But when I run django-admin --version Cannot find installed version of python-django or python3-django. I tried again to install django: pip install Django==2.2.7 Requirement already satisfied: Django==2.2.7 in /home/ion/anaconda3/lib/python3.7/site-packages (2.2.7) Requirement already satisfied: sqlparse in /home/ion/anaconda3/lib/python3.7/site-packages (from Django==2.2.7) (0.3.0) Requirement already satisfied: pytz in /home/ion/anaconda3/lib/python3.7/site-packages (from Django==2.2.7) (2019.1) What can be the problem? -
Django: Relational view in template [many-to-one relationship]
I have a many-to-one relationship in my models. And I want to view the data of my child table in html table related to the parent table. Here's my models.py: class DataCollection(models.Model): default_name = models.CharField(max_length=100) class NameHistory(models.Model): old_name = models.CharField(max_length=100) collection_data = models.ForeignKey(DataCollection, on_delete=models.CASCADE, null=True) And here's my views.py: def dashboard(request): foo = ( DataCollection.objects .annotate( first_old_name=Window( expression=FirstValue('namehistory__old_name'), partition_by=[F('id'), ], order_by=F('namehistory__id').desc() ) ) .values_list('first_old_name', flat=True) .distinct() ) context = { 'sample': foo, 'dashboard': DataCollection.objects.all(), 'title':'Dashboard' } return render(request, 'dashboard/dashboard_form.html', context) My problem is, how can I view the data of this key sample in the template which is related to id of DataCollection table. Here's a sample data in my models, DataCollection: Here's a sample data for NameHistory: So in my html table it should be something like this: I tried this kind of code but I don't know why is it always returning the No Name: <tbody> {% for data in dashboard %} <tr> <td>{{ data.default_name }}</td> {% for item in sample.namehistory_set.all %} <td>{{ item.old_name }}</td> {% empty %} <td> No Name </td> {% endfor %} </tr> {% endfor %} </tbody> -
Django recive incomming GET request
i need to create simple callback function for incoming GET data from sms Api in Django. The incoming data is comma separated. The example php callback looks like below: <?php if($_GET['MsgId'] && $_GET['status'] ) { mysqli_select_db('database_name',mysqli_connect('localhost','login','password')); $arIds = explode(',',$_GET['MsgId']); $arStatus = explode(',',$_GET['status']); $arIdx = explode(',',$_GET['idx']); if($arIds){ foreach($arIds as $k => $v){ mysqli_query("UPDATE sms SET sms_status = '".mysqli_real_escape_string($arStatus[$k])."', sms_index = '".mysqli_real_escape_string($arIdx[$k])."' WHERE sms_id ='".mysqli_real_escape_string($v)."' LIMIT 1"); } mysqli_close(); echo"OK"; } ?> For now i try to setup proper function to collect response data. My attempt: from django.views.decorators.http import require_GET from django.http import HttpResponse @require_GET def callback(request): raw_data = request.body return HttpResponse(status=200) Questions: The receiving function need to by in views.py file, and specified in urls.py? Is the above function properly created for receiving this data? Thank You for all suggestions. -
Django edit table row by clicking button
I can create table with modal form. Now i want to edit and delete the row. Here i found how to update records. But i'm new in django and didn't understand how to release it in view and template. P.S Users must be logged in to see own table. view.py: @login_required(login_url='/accounts/login/') def viewpost(request): person_list = Persona.objects.filter(user_id=request.user) user_filter = UserFilter(request.GET, queryset=person_list) if request.method == 'POST': if request.POST.get('name') and request.POST.get('surname') and request.POST.get('address'): person = Persona() person.name = request.POST.get('name') person.surname = request.POST.get('surname') person.address = request.POST.get('address') person.age = request.POST.get('age') person.payDate = request.POST.get('payDate') person.cover = request.FILES['cover'] person.user = request.user person.save() return HttpResponseRedirect('/viewpost') else: return render(request, 'mysite/viewpost.html', {'persons': person_list, 'filter': user_filter}) -
How to make Custom Serializer from different models without relationships.?
I have 3 different models. I need to build a custom serializer with these 3 models. I tried using some code, but it didn't reach what I expected. There is structure, but I was not able to get the data I was expecting # Serializer This my Serializer and ModelOne, ModelTwo, ModelThree these are my models. class ModelOneSerializer(serializers.ModelSerializer): class Meta: model = ModelOne fields = ['id', 'obj_1', 'obj_2'] class ModelTwoSerializer(serializers.ModelSerializer): class Meta: model = ModelTwo fields = ['id', 'obj_1', 'obj_2'] class ModelThreeSerializer(WritableNestedModelSerializer): class Meta: model = ModelThree fields = ['id', 'obj_1', 'obj_2'] class CustomSerializer(serializers.Serializer): model_1 = ModelOneSerializer(many=True) model_2 = ModelTwoSerializer(many=True) model_3 = ModelThreeSerializer(many=True) # View class CustomView(APIView): def get(self, request, *args, **kwargs): serializer = CustomSerializer(context={'request': request}) return Response({'response': 'ok', 'result': serializer.data}) # Expected Output { "response": "ok", "result": { "model_1": [ { "id":"1", "obj_1":"test", "obj_2":"test", "obj_3":"test" }, { "id":"1", "obj_1":"test", "obj_2":"test", "obj_3":"test" } ], "model_2": [ { "id":"1", "obj_1":"test", "obj_2":"test", "obj_3":"test" } ], "model_3": [ { "id":"1", "obj_1":"test", "obj_2":"test", "obj_3":"test" } ] } } The results may have multiple data in the model_2 and model_3 as in the model_1 structure -
'NoneType' object has no attribute 'name' django
I have three model CustomUser, Profile and artist. what i want to achieve that when i create customuser it should create userprofile and artist also when i update userprofile field it should also update artist field. CustomUser Model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) last_login=models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD='email' REQUIRED_FIELDS=[] objects=UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) Artist model: class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) #userprofile = models.ForeignKey(UserProfile,null=True,on_delete = models.CASCADE) user = models.OneToOneField(CustomUser,null = True, on_delete = models.CASCADE) name = models.CharField(max_length=100,null= True) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return str(self.name) UserProfile Model: class UserProfile(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete= models.CASCADE) artist = models.ForeignKey(Artist,related_name='userprofile', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, null=True) artist_category = models.IntegerField(choices= CHOICES, null=True) mobile_number = PhoneNumberField(null=True) country = CountryField(default = 'IN') city = models.CharField(blank=True, max_length=100) bio = models.TextField(blank=True) def __str__(self): return str(self.user) creating User Profile: def create_profile(sender,instance, created,**kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_profile,sender=CustomUser) @receiver(post_save, sender= CustomUser) def … -
Django authentication with custome model
I have custome login authentication with mysql table , while login how can i compare hash password with plain-password in backends.py(Working fine with plain password) class MyBackEnd(object): def authenticate(self, request, email=None, password=None): existing_user = RegAuth.objects.get(email=email,password=password) if not existing_user: # Checking the user Regauth Custom DB. user_data = RegAuth.objects.get(email=email,password=password) if email == user_data.email: user = RegAuth.objects.create_user(email=email, password=password) user.save() return user else: return None else: return existing_user def get_user(self, email): try: return RegAuth.objects.get(email=email) except Exception as e: return False Login view def logauth(request): if request.method == "POST": email = request.POST['username'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: messages.error(request, 'if part : user is not None') login(request, user) return redirect('emp') else: messages.error(request, 'else part : user is None') return redirect('login_url') else: messages.error(request, 'Please provide valid credentials') return render(request, 'registration/login.html') -
How to set up Nginx to unify Django and Reactjs server?
I've done Django + React application. The backend and frontend servers will run on their own ports. I want to set up Nginx to unify both development servers. How can combine this two server using ngnix? -
How to check two models ID whitout nested loop?
My problem is the nested loop of my template... i use it to check if my model sitio.id_sitio have a equivalent ID with other model comprobante.id_sitio with a Foreign Key and then print A if one result is found and B if none The conditional if work fine but i dont want the nested loop print multiple times. If one result is found i want to break the cycle and print the html only one time, like <a href=""> Checkouts </a> Else if result dont exist in the records at the end of the for i want to print <p>No payments</p> I dont know if i have to write a query in the views.py or if i have to do something else in the templates... Is there a correct way to do this? This is my code: Models.py class Comprobante(models.Model): id_sitio = models.ForeignKey('Sitio', models.DO_NOTHING, db_column='id_sitio', blank=True, null=True) class Sitio(models.Model): id_sitio = models.IntegerField(primary_key=True) sitio = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.sitio Views.py def topsitios(request): sitio = Sitio.objects.all()[0:100] comprobante = Comprobante.objects.all()[0:100] context = {'sitio': sitio, 'comprobante': comprobante} return render(request, "sitio_ptc/topsitios.html", context) Template.html {% block content %} {% for s in sitio %} <tr> <th scope="row"> {{ forloop.counter }}</th> <td> {{ s.sitio … -
Why can't the seeking attribute work on the chrome browser..?? it works on IE however
my model code is like this content_type = models.ForeignKey(contentType, on_delete = models.CASCADE) content_subject = models.ForeignKey(Subject, on_delete = models.CASCADE) content_title = models.CharField(max_length=200) upload_content = models.FileField(upload_to=user_directory_path) this is what i have on my view but bk = Content.objects.get(id=id) how i acquired my video content from database to site then to template list_of_subjects = Subject.objects.filter(grade=grade_id) subject_video = contentType.objects.filter(content_types = 'SubjectVideos') subject_video_list = Content.objects.filter(content_type__in=subject_video) bk = Content.objects.get(id=id) context={ 'list_of_subjects':list_of_subjects, 'subject_video_list':subject_video_list, 'bk': bk } return render(request,'bgcse/bgcse_subject_video_list.html',context) then i have used this video tag on my html template the class video-fluid and etc only takes care of the video sizes and margins etc the video plays and works just fine, the only problem is seeking on chrome <video class="video-fluid z-depth-1" autoplay controlsList="nodownload" controlsList="seeking"> <source src="{{bk.upload_content.url}}"> </video> {% endblock %} ``` -
Using @swagger_auto_schema with recursive serializer in Django
I have a recursive serializer (data is a tree) which is the format of the response of an API. I tried to use it in @swagger_auto_schema like a bunch of other APIs I have implemented but the app collapsed. Can anyone tell me the solution for this, I really need this serializer to be shown on swagger for documenting for my colleagues. Here's my code: class CategoryExtendedSerializer(SkipBlankFieldsSerializer): children = serializers.ListField(source='get_children', child=RecursiveField(allow_null=True)) class Meta: model = Category exclude = ('lft', 'rght', 'tree_id', 'mptt_level') class CategoryListView(APIView): @swagger_auto_schema( operation_description="Get categories list", responses={200: base_page_response(CategoryExtendedSerializer)} ) def get(self, request): # some irrelevant code here pass -
How to mock a method inside another module during unit testing
In one of my test case the flow requires that a customer provision process wherein the call goes to the api.py file where in the response is saved from the function create_t_customer like following: In api.py file it is using the method create_t_customer imported from file customer.py response = create_t_customer(**data) In customer.py file the code for function is def create_t_customer(**kwargs): t_customer_response = Customer().create(**kwargs) return t_customer_response I want to mock the function create_t_customer inside the unittest. Current I have tried the following but it doesn't seem to be working class CustomerTest(APITestCase): @mock.patch("apps.dine.customer.create_t_customer") def setUp(self,mock_customer_id): mock_customer_id.return_value = {"customer":1} But this is not able to mock the function. -
How could I make the modal show up after clicking the Update(submit) button?
This is the footer code: <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button id="employee_update_btn" type="submit" class="btn btn-success btn-round ">Update</button> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> {% if success %} <script> $('#employee.employee_id_{{ employee.employee_id }}').show(); </script> {% endif %} </script> </form> I wanted to open the modal after clicking the Update button. views.py return render(request, 'index.html', context={'success': True}) the Modal i wanted to open: <div class="modal fade" id="employee.employee_id_{{ employee.employee_id }}" tabindex="-1" role="dialog" style="display: none; overflow: auto;" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="card"> <div class="modal-content"> <div class="modal-header"> <div class="card-header-success" > <h4 align="center" class="card-title">EMPLOYEE PROFILE</h4> </div> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> -
Django: Inconsistent test that depends on other test
I am getting inconsistent tests. For visualization, Let me use examples: tests/test_animals.py tests/test_plants.py I have 2 tests. When I run individual test like: python manage.py test apps.living_things.tests.test_plants it would have no errors. However when I run python manage.py test apps.living_things.tests, to test everything, it would affect the second test: tests/test_plants.py I am using fixtures for them, one is initial and the other is just a test fixtures: fixtures/initial.json # general models fixtures/test_living_things.json # sample input for animals and plants I have been debugging. One class of test in tests/test_animals.py includes the 2 fixtures: class TestAnimals(TestCase): fixtures = ['fixtures/initial', 'fixtures/test_living_things'] def setUp(self): pass def tearDown(self): pass When I commented out the block code above in test/test_animals.py everything works fine. So I am suspecting it has to do with the 2nd fixture: fixtures/test_living_things.json since I also have a Test Class without that fixture but works fine. The error I get when messed up is that Client.get does not respond well in tests/test_plants.py class TestPlants(TestCase): fixtures = ['fixtures/initial', 'fixtures/test_living_things'] def setUp(self): pass def tearDown(self): pass def test_plants(self): c = Client() response = c.post('/admin/login/', {'username': 'admin', 'password': 'animalplants'}) response = c.get("/living_things/plants/1/") # Gets Error here, returns 404 -
Django search query feature like Django admin or Django rest framework
I am trying to figure out a proper way to make a search functionality for my model fields like Django's admin or Django rest framework's search feature. Suppose I have this model, I would like to search through all the fields.: class User(models.Model): email = models.EmailField( unique=True, max_length=254, ) first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) mobile = models.BigIntegerField(unique=True) First, I tried this way: user_list = User.objects.filter( Q(id=int(search_input)) | Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | Q(mobile=int(search_input)) ) This works fine if I am filtering with only the integer search terms. However, if I pass a string value, this breaks and it gives me an error: ValueError: invalid literal for int() with base 10 So now what I came up is something like this, to catch any Value errors and exclude integer searches from the filter: try: user_list = User.objects.filter( Q(id=int(search_input)) | Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | Q(mobile=int(search_input)) ) except ValueError as e: user_list = User.objects.filter( Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | ) I am hoping there's a better way then this. Or maybe a field look up feature that I am not aware of? -
How to make a django/vuejs website available offline?
I am working on a online_test application which tests users on mcq, mcc, blanks and code questions. The basic flow of website is: It has courses. Student enrolls in the course watches video lessons Solves questions based on those videos. The first version of the website is live and built entirely in django. The second version I want is the offline version of the course available to the user in which he is enrolled, so that he can study or solve problems without worrying about the internet. Once he completes the test, his responses should be stored in some localstorage (I was thinking IndexedDB) and submitted only when the user comes online. For the second version I am using API written in DRF and for frontend Vue. Vue has helped me reduce number of hits to server and also improved the performance of the website. So I was thinking if there is any way in which I can have a simple Download Course button somewhere inside the course. And when the user click that button, a offline version of the course is available to user. The problem here is even if it is possible to make the course offline, I … -
Lost previous values on overriding change_list.html of django admin
I wanted to add a row in the django admin and for that I customized the django's change_list.html but after doing all the stuff I lost my previous fields. I had this previously: Previous fields image Not I wanted to add total in the footer of the page and I got this: Image after customizing I want the image 1 and image 2 in the same page. @admin.register(Section4, site=admin_site) class Section4Admin(ReadOnlyParamsMixin, admin.ModelAdmin): list_display = ['__str__', 'count_review', 'changelist_view'] def count_review(self, obj): ...... ...... return mark_safe( render_to_string( "section4/count_review.html", {'id': obj.resident.id, 'counts': counts, 'completed': review_completed, 'to_add': review_not_added, }) ) change_list_template = 'section4/total_review_count.html' def get_total(self, user): ........ ....... return total_review_upto_date, total_review_tobe_updated, total_review_tobe_added def changelist_view(self, request, extra_context=None): total_review_upto_date, total_review_tobe_updated, total_review_tobe_added = self.get_total(request.user) my_context = { 'total_review_upto_date': total_review_upto_date, 'total_review_tobe_updated': total_review_tobe_updated, 'total_review_tobe_added': total_review_tobe_added } return super(Section4Admin, self).changelist_view(request, extra_context=my_context) I have templates/admin/section4/section4/change_list.html In section4/templates/section4/total_review_count {% extends "admin/change_list.html" %} {% load i18n admin_urls %} {% block result_list %} <footer> <p>The total review upto date: {{ total_review_upto_date}}<br> </p> <p>The total review to be updated: {{ total_review_tobe_updated}}<br></p> <p>Total review to be added : {{ total_review_tobe_added }}</p> </footer> {% endblock %} -
Advantages of django rest_framework over AJAX and JsonResponce
I can get data in JSON format, using a view and url by calling an AJAX function from JQuery. Which only needs to create a view and a url to access it. But is rest_framework to do the same thing I need to create serializer, views and a url to do the same. So is it good to use AJAXX in these cases or I need to use rest_framework every time. Thanks. -
connect() to unix:///tmp/uwsgi_dev.sock failed (111: Connection refused) while connecting to upstream
I'm running django application with uwsgi + Nginx with crontab command given below /usr/local/bin/lockrun --lockfile /path/to/lock_file -- uwsgi --close-on-exec -s /path/to/socket_file --chdir /path/to/project/settings/folder/ --pp .. -w project_name.wsgi -C666 -p 3 -H /path/to/virtualenv/folder/ 1>> /path/to/log_file 2>> /path/to/error_log but nginx error log file shows the error *83 connect() to unix:///path/to/socket_file failed (111: Connection refused) while connecting to upstream, client: xxx.xxx.xx.xxx, server: localhost, request: "GET /auth/status/ HTTP/1.1", upstream: "uwsgi://unix:///path/to/socket_file:", host: "xx.xxx.xx.xxx", referrer: "http://xx.xxx.xx.xxx/"