Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How i can manage Chat system between my React(front-end) and Django (back-end)
I am working on a chat application, in which I'm gonna use React for the Front-end and Django as the back-end. Note: Both are on different servers. Everything will work through the APIs. I want to know how I can establish a connection between React and Django so I can get real-time messages and display them to the user. Should I use socket.io-client in my React app and Django-channels in my Django app.??? or is there any other way to do this?? And Instagram and other Companies that are using these both stack, how they are doing this stuff??? Please answer ... Kind Regards, Huzaifa -
Error while changing a Char field to Array Field in Django
I am trying to change a existing CharField in a django model (it also allows null and contains null values in db currently) now I am trying to change it to an Array Char Field, but it throws the below error "django.db.utils.IntegrityError: column "tags" contains null values" From tags= models.CharField(max_length=255, blank=True, null=True) To tags = ArrayField(models.CharField(max_length=255, blank=True, null=True)) I have selected option 2 while before running migrate -
Django Redirect: No errors, but no redirect
I POST some data via an HTML form using AJAX to modify data in my database. The data is successfully modified by executing stored procedures on the DB. Final line of the view.py function call is return redirect('Home'). The redirect is successfully executing, but I am not being redirected. I can overcome this by adding window.location.href = 'http://127.0.0.1:8000/ in the success function of the AJAX call. The problem is, I want to use messages.success(request, 'Data Successfully Updated'), which only appears after refreshing the AJAX-originating redirect. Is there a reason why return redirect('Home') is not working here, and is there a way to overcome this? Home is the name of my path in urls.py [06/May/2021 17:23:52] "POST /search/ HTTP/1.1" 302 0 // submitting changes to database [06/May/2021 17:23:55] "GET / HTTP/1.1" 200 4750 // The page I am intending to redirect to Ajax Call function updateCards(){ ajaxUpdCard().done() function ajaxUpdCard() { return $.ajax({ type: 'POST', url: '', data: {csrfmiddlewaretoken: window.CSRF_TOKEN, Action: 'Card', CardID: $('#currentCardID').val(), BCard: $('#sr-bad_card').val(), CNum: $('#sr-card_number').val(), CPin: $('#sr-pin_number').val(), Bal: $('#sr-balance').val()} }) } } views.py if request.method == 'POST' and request.POST['Action'] == 'Card': cardID = request.POST['CardID'] Bcard = int(request.POST['BCard']) CNum = int(request.POST['CNum']) CPin = int(request.POST['CPin']) if request.POST['CPin'] != '' and request.POST['CPin'] … -
string data can't be updated without changing the image in vue js
I have a problem with updating data using vue js as the frontend and django as the backend when updating the data with the data image is changed successfully. but when updating data without an image with an error. i've fire test using postman and managed to update data without changing image. please find a solution this is the method for updating the data ubah() { let datapengajarstaf = new FormData(); datapengajarstaf.append("nama", this.datapengajarstaf.nama); datapengajarstaf.append("nip", this.datapengajarstaf.nip); datapengajarstaf.append("jobs", this.datapengajarstaf.jobs); datapengajarstaf.append("picture", this.gambar); _.each(this.datapengajarstaf, (value, key) => { datapengajarstaf.append(key, value); }); axios .put("http://127.0.0.1:8000/api/Detailpengajarstaff/"+this.id, datapengajarstaf, { headers: { "Content-Type":"multipart/form-data" } } ) .then(response => { this.$router.push("/indexpengajarstaff"); this.$q.notify({ type: "positive", message: `Data berhasil ditambah.` }); }) .catch(err => { if (err.response.status === 422) { this.errors = []; _.each(err.response.data.errors, error => { _.each(error, e => { this.errors.push(e); }); }); } }); } this is for form-data when the data is updated -
Conditionally authenticate users to DRF view
I have a DRF view as such: class DocumentsView(generics.ListCreateAPIView): permission_classes = () authentication_classes = () # I typically enforce authentication with # authentication_classes = (JWTCookieAuthentication,) def list(self, request): pagination_class = None if request.user.is_authenticated: ... return protected data ... else: ... return generic data ... I want to allow both users sending a valid token and those not sending a valid token to both get a response from this endpoint. However, request.user.is_authenticated returns False, even when a valid token is sent (I understand why). How can I try to authenticate the user, but still allow them to proceed even if not presenting a token? Or is better practice to not have the same view to authenticated an unauthenticated users? -
Could not parse the remainder: '[loop.index0]' from 'query_results_course_id[loop.index0]'
I have used django to develop a web app. In frontend, I want to access the object through the loop like in the html template. <label class="radio-inline"> {% for course_for_select in query_results_2 %} <input type="checkbox" name="course_select" value="{{course_for_select}}">&nbsp; {{course_for_select}} {{ query_results_course_id[loop.index0] }} <br> {% endfor %} </label> However, error occurs: Could not parse the remainder: '[loop.index0]' from 'query_results_course_id[loop.index0]' -
Django date format by an user
I'm writing a Django application that requered to give the user the ability to create his own time format, over an API (problay GraphQl). I've figure out the following way, but it seems to be really hard solution for relativlly small problem. class Formatter(models.Model): ... class DateLetter(models.Model): formatter = models.ForeignKey(Formatter, related_name="letters", on_delete=models.CASCADE) index = models.IntegerField(db_index=True) letter = models.CharField(max_length=255, unique=True, choices=LetterChoices.CHOICES, default=LetterChoices.Y) And after that, just going with some sort of loop to get the instance as a date format (%Y-%m-%d) etc. -
Django multiple user roles using AbstractUser without username field
I am trying to build an electronic information system for one teacher and students. Using the tutorial shown here: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html , in my models.py I have implemented the student and teacher models this way: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) f_name = models.CharField(max_length=20) l_name = models.CharField(max_length=30) parent_tel_numb = models.CharField(max_length=13) parent_f_name = models.CharField(max_length=20) parent_patronimic = models.CharField(max_length=30) parent_l_name = models.CharField(max_length=30) group = models.ForeignKey(Group, to_field='id', on_delete=models.SET_NULL, blank=True, null=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) For my application I would like to exclude the username field both for Teacher and Student models. Instead, I want to use email as username. I have previously tried to do it this way, modifying the User model: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] However, after that, when I tried to create a superuser in the terminal, the username field was omitted during the creation of superuser and after submission of email and password, I got an error, saying the username field is absent. How do I deal with this issue? -
Django findstatic gives no error but templates and static files are not loading
when i run python manage.py findstatic --verbosity 2 vendors/jquery/dist/jquery.min.js it is giving me this output. But still it is not loading static elements and css in server. it was working fine in local host. DEBUG = True for now. Found 'vendors/jquery/dist/jquery.min.js' here: /www/wwwroot/default/pmosync/Dev/pmosinc/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/admin/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/auth/static/vendors/jquery/dist/jquery.min.js Looking in the following locations: /www/wwwroot/default/pmosync/Dev/pmosinc/static/ /www/wwwroot/default/pmosync/Dev/static/ /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/admin/static /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/auth/static -
Add wordlist.txt in exclude query
I am building a BlogApp and I am trying to add wordlist.txt at the place of exclude('wordlist.txt') What i am trying to do :- I build a feature of exclude posts according to words, For Example :- If a post contains word "Bad" then exclude that post like :- from django.db.models import Q posts = Post.objects.exclude(Q(description__contains='bad') & Q(description__contains='bad1')) BUT i am trying to exclude hundreds of words at the same time AND when i add all of them in this way then it will be very lengthy AND i don't want that, So i think I can make a file named wordlist.txt and put all my words that i want to exclude then put the path of wordlist.txt in exclude query so i do not have to write lengthy exlcude words in the query. For example :- posts = Post.objects.exclude(description__contains=wordlist.txt) ( Above example is just to explain, what i am trying to do ) I have no idea how can i do it . Any help would be Appreciated. Thank You in Advance -
Django 'change' can not find existing object
Currentli my django project still using Sqlite as db. I have a model named 'Monitoring'. class Monitoring(models.Model): tebar=models.ForeignKey(Tebar, on_delete=models.CASCADE, related_name='monitoring',) date_created = models.DateTimeField( verbose_name=("Tanggal"), auto_now_add=True, null=True, editable=False,) prevmon=models.ForeignKey('self', on_delete=models.CASCADE, related_name='nextmon', editable=False, blank=True, null=True) dead = models.PositiveIntegerField(verbose_name='Jml. Mati', default=0, null=True) food = models.ForeignKey(Bahan, on_delete=models.CASCADE, related_name='monitoringfood', verbose_name='Pakan', blank=True, null=True) foodqty=models.PositiveIntegerField(null=True, default=0, verbose_name='Berat Pakan',) suplemen=models.ForeignKey(Bahan, on_delete=models.CASCADE, related_name='monitoringsupl', verbose_name='Suplemen', blank=True, null=True) suplqty=models.PositiveIntegerField(null=True, default=0, verbose_name='juml.Supl.',) feedcost = models.DecimalField(max_digits=10, decimal_places=2, default=0.0, blank=True, null=True) ph = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=7, decimal_places=2, verbose_name='gram/ekor', default=0.0, null=True) wateradd= models.PositiveIntegerField(verbose_name='Tambah Air', null=True, blank=True, help_text='Penambahan Tinggi Air dalam Cm') class Meta : verbose_name_plural='7. Perlakuan' def __str__(self): return '{}; {}'.format(self.tebar, self.date_created) I add one record, get success. I try to change the record, the web page go to the /admin and under the site name line I got msg: Monitoring with ID “6” doesn’t exist. Perhaps it was deleted? I try to access the db via django console, and that record is there. bino@rtd:~/catatkolam$ pipenv run ./manage.py shell Python 3.9.2 (default, Mar 13 2021, 18:29:25) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from catatkolam.models import * >>> Monitoring.objects.get(id=6) <Monitoring: kolam 1@2021-05-02; 2021-05-06 07:19:53.288664+00:00> >>> Monitoring.objects.get(id='6') <Monitoring: kolam 1@2021-05-02; 2021-05-06 07:19:53.288664+00:00> >>> I … -
Bulk update with different values in django 1.11
I have been reading the official documentacion of django 1.11 about bulk updating. My problem is that I have only seen how to update the fields for ALL the query objects. What I need is a bulk update but with different values, depending on a condition. Let me write an example. Let's say I have the following model: class A(models.Model): key = models.ForeignKey(SomeOtherModel, db_index=True) value = models.FloatField(blank=True, null=True, default=None) As you can see, the field_definition points to another model. What I want is to mass update the objects of a query of the model A based on that value. Something like this: A.objects.filter(key__id__in=[1,2,3]).update(value_for_id_1="1", ..., value_for_id_n="n") The only thing I have seen so for is this syntax: A.objects.filter(key__id__in=[1,2,3]).update(value="1") Any idea if this is even possible? How can I make this query efficient? -
The best way to get data from another database and refresh it every few seconds in Django
I am wondering what is the best way to get data from another database (on the same server but it is part of different application) and refresh it every few seconds. I want to let user to choose from a select form that contains all the objects with specific status field. I want to use pyodbc (I'm using MySQL for both of databases), run a simple select (E.g. SELECT Index, Name FROM Table WHERE Status = 'OPEN'), create object for every row if it doesn't already exist in Django database: cursor.execute("SELECT Index, Name FROM Table WHERE Status = 'OPEN") for row in cursor: try: order = Order.objects.get(index=row[0]) except Order.DoesNotExist: Order.objects.create(index=row[0], name=row[1]) but my question is- when should i run it? Time it in a loop and do it every few seconds somehow? Or should I just do it every time user requests for a view with select form that contains these objects. What is the correct approach? -
Django / Python : ModuleNotFoundError: No module named 'd'
The project seemed fine till yesterday, but suddenly , when I tried to start the server after some settings changes today, this error pops up everytime: Traceback (most recent call last): File "/PROJECT/manage.py", line 21, in <module> main() File "/PROJECT/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'd' the project manage.py file : #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PROJECT.settings.production') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Please help me solve this and please do ask if you need more information. Thank you … -
Using a Datepicker with Django and chart.js
Good day, please i am new to django. Can i be shown how to use a datepicker to show my chart.js for the specific date selected by a user? Can i be shown how to install a datepicker for this purpose?Below was my attempt and i have not been able to display any data. Model: class Complainer(models.Model): STATES = ( ('Abia', 'Abia'), ('Abuja', 'Abuja'), ('Adamawa', 'Adamawa'), ('Akwa-Ibom', 'Akwa-Ibom'), ('Anambra', 'Anambra'), ('Bauchi', 'Bauchi'), ('Bayelsa', 'Bayelsa'), ('Benue', 'Benue'), ('Borno', 'Borno'), ('Cross-River', 'Cross-River'), ('Delta', 'Delta'), ('Ebonyi', 'Ebonyi'), ('Edo', 'Edo'), ('Ekiti', 'Ekiti'), ('Enugu', 'Enugu'), ('Gombe', 'Gombe'), ('Imo', 'Imo'), ('Jigawa', 'Jigawa'), ('Kaduna', 'Kaduna'), ('Kano', 'Kano'), ('Katsina', 'Katsina'), ('Kebbi', 'Kebbi'), ('Kogi', 'Kogi'), ('Kwara', 'Kwara'), ('Lagos', 'Lagos'), ('Nasarawa', 'Nasarawa'), ('Niger', 'Niger'), ('Ogun', 'Ogun'), ('Ondo', 'Ondo'), ('Osun', 'Osun'), ('Oyo', 'Oyo'), ('Plateau', 'Plateau'), ('Rivers', 'Rivers'), ('Sokoto', 'Sokoto'), ('Taraba', 'Taraba'), ('Yobe', 'Yobe'), ('Zamfara', 'Zamfara') ) SECTOR = ( ('Federal Government', 'Federal Government'), ('State Government', 'State Government'), ('Local Government', 'Local Government'), ('Private Company', 'Private Company'), ('Public Company', 'Public Company'), ('Other', 'Other'), ) NATURE = ( ('Delay of Service', 'Delay of Service'), ('Non compliance with Regulation', 'Non compliance with Regulation'), ('Demand for Bribery', 'Demand for Bribery'), ('Vandalism', 'Vandalism'), ('Unrepaired or damaged infrastructure', 'Unrepaired or damaged infrastructure '), ('Insecurity', 'Insecurity'), ('Non Payment of … -
Target WSGI script cannot be loaded as Python module after Django update
After upgrade django to 3.2 and switching SQLITE to MSSQL with django-mssql-backend (doubt its db fault), App is giving 500 Internal Server Error in browser and following in apache log: [Thu May 06 09:17:58.791944 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] django.setup(set_prefix=False) [Thu May 06 09:17:58.791955 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] File "/opt/xip/REST/venv/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup [Thu May 06 09:17:58.791964 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] apps.populate(settings.INSTALLED_APPS) [Thu May 06 09:17:58.791983 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] File "/opt/xip/REST/venv/lib64/python3.6/site-packages/django/apps/registry.py", line 81, in populate [Thu May 06 09:17:58.792008 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] # Prevent reentrant calls to avoid running AppConfig.ready() [Thu May 06 09:17:58.792038 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] RuntimeError: populate() isn't reentrant [Thu May 06 09:20:58.788482 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] mod_wsgi (pid=126006): Target WSGI script '/opt/xip/REST/cftapi/cftapi/wsgi.py' cannot be loaded as Python module. [Thu May 06 09:20:58.788559 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] mod_wsgi (pid=126006): Exception occurred processing WSGI script '/opt/xip/REST/cftapi/cftapi/wsgi.py'. [Thu May 06 09:20:58.789020 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] Traceback (most recent call last): [Thu May 06 09:20:58.789088 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] File "/opt/xip/REST/cftapi/cftapi/wsgi.py", line 9, in <module> [Thu May 06 09:20:58.789140 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] application = get_wsgi_application() … -
running some Dash-Plotly apps inside a Django app similar to PaaS (platform as a service)
I have a challenge and I would be grateful if you could give me some clue... I want to run some Dash-Plotly (a framework based on Flask) applications inside a Django app. I know Dash has a framework called django-plotly-dash but what I want is a Django app that our developed Dash(aka Flask) apps can easily be imported and run. In other words, I want to make Django app a Paas (Platform as a Service) and other Dash/Flask apps can be imported in Django dashboard/(our developed page) and can be accessible from the Django app. Some idea may be using Docker containers but is also has some challenges and we want to seek the most optimal solution. is there any idea??? -
How to delete a record in django using cloud firestore?
ERROR PICTURE I'm trying to delete a record in my table but this is giving me an error error : Reverse for 'delete_Building' with arguments '('Ep7AzCd3rcUvDjvwhvL5',)' not found. 1 pattern(s) tried: ['delete/(?P[0-9]+)/$'] -> ID is selected but template is not loading because of above error my html file : <div class="row"> <div class="col-lg-12 mb-4"> <!-- Simple Tables --> <div class="card"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <a href="{% url 'building:registerBuilding'%}" class="btn btn-sm btn-primary"><i class="fas fa-plus-circle "></i> Add Building</a> </div> <div class="table-responsive"> <table class="table align-items-center table-flush" id="buildingList"> <thead class="thead-light"> <tr> <th>BUILDING NAME</th> <th>POSTAL CODE</th> <th>STREET</th> <th>HOUSE NO.</th> <th>TOWN</th> <th>ADDITIONAL INFO</th> <th colspan="2">ACTION</th> </tr> </thead> <tbody> {% for building in buildings %} <tr> <td>{{ building.building }}</td> <td>{{ building.postalCode }}</td> <td>{{ building.houseNo }}</td> <td>{{ building.street }}</td> <td>{{ building.town }}</td> <td>{{ building.additionalInfo }}</td> <td><a href="{% url 'building:updateBuilding' %}" class="btn btn-primary btn-xs" data-title="Edit" ><i class="fa fa-pen"></i>Edit</a></td> <td><a href="{% url 'building:delete_Building' building.id %}" class="btn btn-danger btn-xs text-white" data-title="Delete"><i class="fa fa-trash"></i>Delete</a></td> </tr> {% endfor %} </tbody> </table> </div> <div class="card-footer"></div> </div> </div> </div> </div> <!---Container Fluid--> </div> my views.py file def delete_Building(request, id): docId = doc_ref.id; db.collection('Buildings').doc(docId).delete(); return redirect("/") my urls.py file path('delete/<int:id>/',views.delete_Building,name='delete_Building'), -
not able to post images through rest framework django but says status code 200
i have everything set up but when i starts posting into DRF through post function with image it shows status code 200 but does not return dynamic id of object and there is no new object in database, but when i remove imagefield from models and try to post it does not give me error and returns id of posted object.. models.py class Accounts(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(default='default.png') def __str__(self): return f'Account object' serializers.py from rest_framework import serializers from .models import Accounts class Accountserializers(serializers.ModelSerializer): class Meta: model = Accounts fields = '__all__' views.py @api_view(['POST']) def post_data(request): serializer = Accountserializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) this is the code as i said when i post something it says status code 200 and does not return dynamic id.. pls help me find the solution -
ValueError at /createPost Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser
Hello Guys I'm trying to post an image file using Django. I don't know what is happening and I got another error while trying to fix one so please see the code and I got ValueError at /createPost Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x0000020C1B569F40>>": "Post.author" must be a "User" instance this error I don't know what's going on, Im beginner so. Views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .models import Post from .forms import PostForm # Create your views here. def index(request): post = Post.objects.order_by("-pub_date") context = { "posts": post } return render(request, "index.html", context) def post_create(request): form = PostForm(request.POST,request.FILES or None) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] img = form.cleaned_data["img"] username = request.user post = Post.objects.create(title = title, content = content, img = img, author = username) post.save return redirect("posts:home") else: form = PostForm() context = { "form": form } return render(request, "postcreate.html", context) Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length = 200) content = models.TextField(null = True, blank = True) img = models.ImageField(upload_to = "static/my_post_pic", null = True, blank = True) pub_date = models.DateTimeField(default = timezone.now) … -
Exclude post if post contains "good" word
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to implement a feature that, If post description contains "good" word then exclude it from all the posts. views.py def posts(request): posts = Post.objects.all() if 'good' in posts.description: printing = 'CONTAINS' context = {'posts':posts} return render(request, 'mains/posts.html', context) From this view, I am just trying to print the contains word in template ( just for test and It's working fine ) BUT I am trying to exclude that post ( which contains good word ) from all the posts. Any help would be Appreciated. Thank You in Advance. -
How to return back just queryset objects from middleware?
I'm not sure being I understand what does Middleware will help me in Django do. but if it will help me to make some help for request/response to appear globally so that, I really need it. based on that, I read a little bit more explanations and tutorials about Middleware also, I read some docs in Django middleware hence, wanted to use a request which will return an object from query set based on this request something like you will see underneath: Order.objects.get(user=request.user, in_progress=True) I confused between the two next function names which handle the response in Middleware of Django: process_template_response and process_response the problem is I need to return back the objects which will be handled in the views.py file in Django by one of these response function. I read an old doc that supports Django 1.8 and see the difference between that two functions in response as following: the process_template_response as the documentation mentioned: is called just after the view has finished executing, if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent. but when I read about process_response despite is called it before request as I understand, I figured out that … -
stacked url when using jquery ajax post
i want to use ajax to send post data to views,i'm tryin to implement pagination,when i click page button and send jquery.Post() data. But the url got stacked what should i do? .html <div class="clearfix "> <ul class="pagination pagination-sm m-0 float-right" id="submits" > <li class="page-item" id="1" ><a class="page-link" href="{% url 'postNewRA2' RAid 1 %}" id="1">1</a></li> </ul> </div> .scripts $(document).ready(function () { $('#submits li').click(function () { var a = $(this).attr('id'); linkUrl = 'library/postNewRA2/71/' + a + '' alert(linkUrl); $.ajax({ type: 'POST', url: linkUrl, data: { 'pages': 'panji', csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: "json", contentType : "application/json", success: function (result) { window.console.log('Successful'); }, error: function () { window.console.log('Error!'); } }); }); }); I expected the urlS just http://127.0.0.1:8000/library/postNewRA2/71/1 -
Como ejecutar scripts de JAVA en PYTHON [closed]
estoy creando un sitio web con django python. Mas ahora necesito una herramienta de google dev y resulta que los codigos que me entrega google están para java, necesito saber como ejecutar ese codigo de java con todo lo que tengo de python ya que necesito captar unos datos que me retorna el script y procesarlo. -
Problem in post http request django restfamework
I have this ViewSet in my project: class UserCreditCardsViewSet(UserDataModelViewSet): queryset = UserCreditCard.objects.none() http_method_names = ['post', 'get', 'delete', 'option'] def get_queryset(self): return UserCreditCard.objects.filter(user=self.request.user) serializers = { 'default': UserCreditCardsSerializer, } permission_classes_by_action = { 'default': [IsAuthenticated], } And its the URL routing: router.register(r'accounting/credit_card', UserCreditCardsViewSet, basename='UserCreditCard') Everything else working well in my project. But when I want to do a post request to this ViewSet Its shows this error: { "detail": "Method \"POST\" not allowed." } What is the problem?