Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to manage a redirect after a Ajax call + django
I'm managing my payments using braintree drop in and i'm using django. when the payment is success it should redirect to the payment success page and when it's unsuccess it should redirect to the payment failed page. I define the redirects in my views.py but i don't know how should i handle the redirect in ajax in this code after payment nothing happens and redirect is not working. what should i add to my ajax to handle the redirect? Braintree drop in Javascript code: <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } }, function (createErr, instance) { button.addEventListener('click', function () { instance.requestPaymentMethod(function (err, payload) { $.ajax({ type: 'POST', url: '{% url "payment:process" %}', data: { 'paymentMethodNonce': payload.nonce, 'csrfmiddlewaretoken': '{{ csrf_token }}' } }).done(function (result) { }); }); }); }); </script> Views.py @login_required def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': # retrive nonce nonce = request.POST.get('paymentMethodNonce', None) # create and submit transaction result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # … -
ProgrammingError: Cursor closed while using Django ORM raw
There is a a repeating error ProgrammingError: Cursor closed when using a raw query using Django ORM MyModel.objects.raw(<raw_sql_query>) The database being used is MySQL, and the cursor object is not being accessed in any application code. All references found online refer to problems when dealing with the cursor object. There are other instances of error: Programming Error (2014, Commands out of sync; you can't run this command now) in some celery tasks, which are running on separate hosts. Can anyone help me with clues to debug this problem ? Or any areas I might have not explored which is leading to this error. Environment: Python 3.6+, Django 2+, Mysql 5.7+ -
Django REST API connecting to existing database MySQL shows empty [] in http://127.0.0.1:8000/api/overview
I want to connect my Django REST API to MYSQL which i have done in my settings sucessfully, however it shows emppty [] in http://127.0.0.1:8000/api/overview/. I would appreciate if you could help to understand how to get my figures to show in http://127.0.0.1:8000/api/overview/. in my app/models.py : from django import forms from .models import Overview class OverviewForm(forms.ModelForm): class Meta: model=Overview fields=["__all__"] in app/forms.py: from django.conf import settings from django.db import models class OverviewQuerySet(models.QuerySet): pass class OverviewManager(models.Manager): def get_queryset(self): return OverviewQuerySet(self.model,using=self._db) class Overview(models.Model): symbol=models.CharField(settings.AUTH_USER_MODEL,max_length=200) typename=models.CharField(max_length=500) sector=models.CharField(max_length=500) objects = OverviewManager() class Meta: managed=False db_table='overviews' def __str__(self): return '{}'.format(self.symbol) class Meta: verbose_name = 'Overview' verbose_name_plural = 'Overviews' in my app/api/serializers.py: from rest_framework import serializers from app.models import Overview class OverviewSerializer(serializers.ModelSerializer): class Meta: model=Overview fields=["__all__"] in my app/api/views.py: from rest_framework import generics, mixins, permissions from rest_framework.views import APIView from rest_framework.response import Response import json from cfs.models import Overview from .serializers import OverviewSerializer class OverviewSearchAPIView(APIView): permission_classes = [] authentication_classes= [] serializer_class = OverviewSerializer def get(self,request,format=None): qs = Overview.objects.all() serializer = OverviewSerializer(qs,many=True) return Response(serializer.data) in my app/api/urls.py: from django.urls import path from .views import OverviewSearchAPIView urlpatterns = [ path('', OverviewSearchAPIView.as_view()), ] in my app/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ … -
Django pagination is not working properly when using POST method in Search form
I am trying to search an item in a form using POST method and I got the results. But when I use Django pagination, I got the results in the first page. When I click the next or 2 button in Django paginator I got an error like this. The view profiles.views.individual_home didn't return an HttpResponse object. It returned None instead. Here search form is in one html page and results shown in another html page. views.py def individual_home(request): if request.method == 'POST': keyword = request.POST.get('keywords') print(keyword) location = request.POST.get('location') print(location) ind = IndividualProfile.objects.get(user_id=request.user.id) details = companyjob.objects.filter( Q(job_title=keyword) | Q(qualification=keyword) | Q(skills_required=keyword) | Q(job_location=location) & Q(closing_date__gte=datetime.date.today())) if details: print(details) count = details.count() paginator = Paginator(details, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "individual_home.html", {'jobs': page_obj,'count': count, 'ind': ind}) else: return redirect("individual_homes") individual_home.html: <div class="container mt-5"> <div class="row mt-5"> <div class="col-lg-10 mx-auto"> <div class="career-search mb-60"> <form method="POST" action="{% url 'individual_home' %}" class="career-form mb-60" style="background-color:#6351ce;"> {% csrf_token %} <div class="row"> <div class="col-md-6 col-lg-4 my-3"> <div class="input-group position-relative"> <input type="text" class="form-control" placeholder="Enter Your Keywords" id="keywords" name="keywords"> </div> </div> <div class="col-md-6 col-lg-4 my-3"> <input type="text" class="form-control" placeholder="Location" id="location" name="location"> <div class="col-md-6 col-lg-4 my-3"> <button type="submit" class="btn btn-lg btn-block btn-light btn-custom" id="contact-submit"> Search … -
How to pass multiple integers to ManyToMany Field present in the list in Django
I want add this product to both category, how to do it class Category(models.Model): name = models.CharField(max_length=500) image = models.ImageField(upload_to='categories', default='default.png') class Products(models.Model): name = models.CharField(max_length=500) category_id = models.ManyToManyField(Category, default='') category_id = [4, 6] product, created = Products.objects.get_or_create(name =data['Casual Red Shirt'], product.category_id.add() -
how to deploy django project on aws?I already tried with nginx,gunicorn but it was not working.Need some help in this
While using aws to deploy django project with nginx,gunicorn but it was not working so how deploy it in properly.need some help. -
How to use django annotate to compare current date with other date in models
I want to get the days between the current time and another date. Here is the command what I used: employees = Employee.objects.annotate( duration=ExpressionWrapper(datetime.now().date() - F('start_working_date'), output_field=DurationField()) ) But the result I got( employee.duration) is 0. for employee in employees: employee.duration And here is my models: class Employee(models.Model): name = models.CharField(max_length=30) start_working_date = models.DateField() -
How to get uploaded file name from django id
I simply wanted the file exact file name which i have been uploaded so that i can read the whole file and show content on HTML page... class newcodes(models.Model): user_id = models.AutoField fullname = models.CharField(max_length=200) codefile = models.FileField(upload_to ='programs/')//her is my codefile location in models Here is my function for reading text but i cant get name of uploaded file so i can't read the file def showcode(request,id): programs=newcodes.objects.filter(id=id) print(programs) # f=open('media/') return render(request,"Codes.html") -
Django Modelviewset Filtering
I have two models Category & Post. In Post model there is foreign key of category. Based on category I want to filter the data to show the post category wise. Here's my code. models.py class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='news', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "Category" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): NEWS_TYPE = (('Images','Images'),('Multi-Images','Multi-Images'),('Image-Text','Image-Text'), ('Audio-Video','Audio-Video'),('Audio-Video-Text','Audio-Video-Text'),('Audio','Audio'), ('Audio-Text','Audio-Text')) POST_STATUS = (('Pending','Pending'),('Verified','Verified'),('Un-Verified','Un-Verified'), ('Published','Published'),('Mint','Mint')) category = models.ForeignKey(Category, related_name='Category', on_delete=models.CASCADE) post_type = models.CharField(max_length=100, verbose_name='Post Type', choices=NEWS_TYPE) title = models.TextField(verbose_name='News Title') content = models.TextField(verbose_name='News Content') hash_tags = models.CharField(max_length=255, verbose_name='Hash Tags') source = models.CharField(max_length=255, verbose_name='News Source') author = models.ForeignKey(User, related_name='Post', on_delete=models.CASCADE) views = models.ManyToManyField(User,related_name='Views', blank=True) likes = models.ManyToManyField(User, related_name='Likes', blank=True) dislikes = models.ManyToManyField(User, related_name='Dislikes', blank=True) status = models.CharField(max_length=20, verbose_name='Status', choices=POST_STATUS, default='Pending') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return (self.post_type)+ '-' +self.title serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() class Meta: model = Post fields = ('category','post_type','title','content','hash_tags','source','author','views', 'likes','dislikes','status') views.py class CategoryAPI(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer class PostAPI(viewsets.ModelViewSet): serializer_class = PostSerializer def get_queryset(self): news_post = Post.objects.all() … -
Why is it going to anaconda how do I fix i
enter image description here I'm new so you have to press on the link. Pls help -
How get selected value in bootstrap V5 select with python
I am using Class Based Views in django... Then my model is: class Survey(Base): description = models.CharField('Description', max_length=50, unique=True) item1 = models.CharField('Item1', max_length=50) item2 = models.CharField('Item2', max_length=50) ... class Meta: verbose_name = 'Survey' def __str__(self): return self.description Now I am reading database data for fill in select and works fine. How I get this select item for fill table fields? info.html <div class="col-12"> <div class="card card-chart"> <div class="card-header "> <div class="row"> <div class="col-sm-4 text-left"> <h2 class="card-title">Informations</h2> <option selected>choose a option</option> {% for s in survey %} <option>{{s.description}}</option> {% endfor %} </select> </div> <!-- of course, in this moment variable [s] not exist --> <div class="col-sm-8 text-right"> <table class="table"> <tbody> <tr> <td>item 1</td> <td>item 2</td> </tr> <tr> <!-- want fill this fields with select item above--> <td>{{s.item1}}</td> <td>{{s.item2}}</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> -
How to send mail to the post author when got new comment in django rest framework through serializer?
I am trying to build an API where students will ask questions and the teacher will answer that question. For asking questions and answering I am using the blog post way. Now, my problem is I am trying to send mail from the serializer. But when I want to detect the post author I am unable to do that. I can send selected users but not from the model. If anyone can help me with that it will be so helpful. Thanks a lot. these are the add_question model and answer the question model --- class add_question(models.Model): title = models.CharField(max_length=250, blank=False) description = models.TextField(blank=True, null=True) is_answered = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) STATUS = ( ('Published', 'Published'), ('Suspended', 'Suspended'), ('Unpublished', 'Unpublished'), ) status = models.CharField(choices=STATUS, default='Published', max_length=100) RESOLUTION = ( ('Resolved', 'Resolved'), ('Unresolved', 'Unresolved'), ) resolution = models.CharField(choices=RESOLUTION, default='Published', max_length=100) def __str__(self): return self.title class add_questionFile(models.Model): question = models.ForeignKey(add_question, on_delete=models.CASCADE, related_name='files') file = models.FileField('files', upload_to=path_and_rename, max_length=500, null=True, blank=True) class submit_answer(models.Model): description = models.TextField(blank=False, null=False) is_deleted = models.BooleanField(default=False) rating = models.FloatField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) question_id = models.ForeignKey(add_question, blank=False, on_delete=models.CASCADE) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) class submit_answerFile(models.Model): answer … -
Django generic create view . Can we add conditions to save data from the form?
This is what my code looks like and I want to add some condition to the Borrower create view like if the stock method of book returns 0 then don't list that book in field while creating a new borrower or if it isn't possible at least throw some error while adding borrower to that book. models.py: class Book(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=100) summary = models.TextField( max_length=1000, help_text="Enter a brief description of the book") isbn = models.CharField('ISBN', max_length=13, help_text='13 Character https://www.isbn-international.org/content/what-isbn') genre = models.ManyToManyField( Genre, help_text="Select a genre for this book") language = models.ForeignKey( 'Language', on_delete=models.SET_NULL, null=True) total_copies = models.IntegerField() pic = models.ImageField(blank=True, null=True, upload_to='books') def stock(self): total_copies = self.total_copies available_copies = total_copies - \ Borrower.objects.filter(book=self).count() if available_copies > 0: return available_copies else: return 0 def __str__(self): return self.title class Borrower(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) student = models.ForeignKey('Account', on_delete=models.CASCADE) book = models.ForeignKey('Book', on_delete=models.CASCADE) issue_date = models.DateField( null=True, blank=True, help_text='YYYY-MM-DD', default=date.today) return_date = models.DateField( null=True, blank=True, help_text='YYYY-MM-DD') def __str__(self): return self.student.name.title()+" borrowed "+self.book.title.title() def fine(self): today = date.today() fine = 0 if self.return_date <= today: fine += 5 * (today - self.return_date).days return fine views.py: class BorrowerView(LoginRequiredMixin, ListView): model=Borrower context_object_name='borrowers' template_name … -
How to insert raw html into form when creating a page using django
I want to include things like hyperlinks, quoting, italicized text, etc. into my pages I post on the site I wrote with django but it seems to escape my code. What can I do to add this feature? Has someone else already done something I could just use? -
Error: Has No Attribute "Getlist" Error When Making Request in Django
When I run the tests to make requests to the webpage on Django, the tests run fine and have expected behavior. However, when the same code is run when I'm making a request outside of the testing environment in Django, running: request.data.getlist("insert_key_here") where "insert_key_here" is a key from a key-value pair where the value is a list, I get this error: 'dict' object has no attribute 'getlist' When I try to run this instead request.data["insert_key_here"] I get an error that a string's indices must be an int. Does this mean that the request.data is somehow a string? If it was just grabbing the first value in the list like how it would if you used .get() instead of .getlist(), I don't know that I'd be getting this error just from trying to fetch the value. To give some context, this is an example of the format of the request: { "insert_key_here" : [ "list_item1", "list_item2" ] } I'm not sure why it would work perfectly in the testing environment, but, then, when I run it outside the testing environment, I get that error on that specific line. -
I couldn't able to save my data in to admin. it just redirect me to Home page
This is my View.py code. hear it redirect me to home page and doesn't save my data in to admin panel. **if i indent back else condition Blockquote else: form = OrderForm() return redirect('home') Blockquote it gives me error - ValueError at /orders/place_order/ The view orders.views.place_order didn't return an HttpResponse object. It returned None instead.** def place_order(request, total=0, quantity=0,): current_user = request.user # if cart count is less then 0 or equel to 0, then redirect to shop cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price*cart_item.quantity) quantity += cart_item.quantity tax = (12 * total)/100 grand_total = total + tax if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # store all the information inside belling table data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.provence = form.cleaned_data['provence'] data.zone = form.cleaned_data['zone'] data.district = form.cleaned_data['district'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.ip = request.META.get('REMOTE_ADDR') data.save() # genarate order no yr = int(datetime.date.today().strftime('%y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr,mt,dt) current_date = … -
Django how to import custom javascript?
I'm having the weirdest issue yet; I can't request a custom javascript (chart.js) the same way I do another one (main.js); This is how I request the scripts; notice how main.js is in the same folder as chart.js Now, the requests received by Django; notice how main.js is ok, while chart.js is 404: I've tried deleting the __pycache__ folders and restart the server but no go. What could be causing this? -
Protected routes using JWT tokens in NextJS + Django
I'm starting this new NextJS application where I'm using Django as an API. I'm using JWT tokens for authentication/authorization and I wanted to create protected routes. After following a bunch of tutorials, videos and other things online, here's what I came up with: I created an axios instance (api.js) (where I was trying to intercept requests to set the Authorization header): import axios from "axios"; import Cookies from "js-cookie"; const api = axios.create({ baseURL: "http://127.0.0.1:8000/api/", headers: { Accept: "application/json", "Content-Type": "application/json", }, }); api.interceptors.request.use((request) => { const token = Cookies.get("accessToken"); if (token) { api.defaults.headers.Authorization = `Bearer ${token.access}`; } return request; }); export default api; And an AuthService.js (where I set a cookie when l log in): import Cookies from "js-cookie"; import api from "./api"; export const AuthService = { login: async (email, password) => { const { data: token } = await api.post("token/", { email, password }); console.log(token); if (token) { console.log("Got token"); Cookies.set("accessToken", token.access, { expires: 60 }); api.defaults.headers.Authorization = `Bearer ${token.access}`; const { data: user } = await api.get("users/current/"); console.log("Got user", user); return user; } }, logout: async () => { Cookies.remove("accessToken"); delete api.defaults.headers.Authorization; }, getUser: async () => { try { const { data: user } = … -
Django Saving Model Method Property to the Database
I have ModelOne that has a model method, lets say method_that_does_stuff, with the @property decorator that calculates a boolean value, based on the value of ModelThree, which is a ForeignKey of ModelTwo, which is a ManyToMany of ModelOne. I'm trying to make it that when the value of method_that_does_stuff changes, due to changes in ModelThree, it saves the boolean value to ModelOne. Below is my implementation: from django.db import models class ModelThree (models.Model): some_input = models.TextField() model_two = models.ForeignKey(ModelTwo, on_delete=models.CASCADE) class ModelTwo (models.Model): name = models.CharField(max_length=200) class ModelOne (models.Model): name = models.CharField(max_length=200) boolean_field_to_change = models.BooleanField(default=False) model_twos = models.ManyToManyField(ModelTwo) @property def method_that_does_stuff(self): # It does some stuff and returns either True or False, but let's assume True # The True or False return depends on ModelThree's some_input field # If the some_input field doesn't change, then it will stay False return True def save(self, *args, **kwargs): self.boolean_field_to_change = self.method_that_does_stuff super(ModelOne, self).save(*args, **kwargs) However, for some reason, when I run in the Django shell and get all of the ModelOne objects, the method_that_does_stuff will be True, but the boolean_field_to_change will still be its default value of False. I found this solution: Django Model Method or Calculation as Field in Database which is … -
from autoslug import AutoSlugField Not working
please I need help with Python Django stuff I have installed pip install pillow and I need to import it in models.py. When I run this code in command prompt, I get this error[At line:1 char:1 from autoslug import AutoSlugField The 'from' keyword is not supported in this version of the language. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordEx ception + FullyQualifiedErrorId : ReservedKeywordNotAllowed]1 I am using Python 3.10 with Django 4.0.1 on Windows 10 64bits I will appreciate your help to solve this -
Query selector sort
Inbox = Messages.objects.filter(Q(sender=request.user) | Q(receiver=request.user)) context['Inbox'] = Inbox Currently I am using this to grab all messages for the currently logged in user. I want to sort it by time and read status. So that the lastest unread message shows up first. models.py class Messages(models.Model): sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE) receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE) subject = models.CharField(default='',max_length=100) text = models.CharField(default='',max_length=4096) time = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) def __str__(self): return '{} to {} :{}'.format(self.sender,self.receiver,self.text) -
I cannot get images to work on my django project(this is my first one and im having trouble)
I have an img folder in the same directory as my html files. I want to put images onto my site but I am doing something wrong. this is the code: {% block a %} <div class="row"> <div class="col-sm-4 center"> <img src="img/img01.jpeg"> </div> </div> {% endblock %} this is what happens when I run the local server. local server this is my file directory file directory -
Difficulty in partial update in DRF
I am learning Django and DRF, I am having issues updating the field expire_on. And there also I have to put the logic to prevent to put the value of expore_on no greater than 7 days from created_on. I am having trouble figuring out how to update the same and write the above logic. I have tried: update function in DRF viewset.Viewset Django Rest Framework not showing form fields for PATCH/PUT request Django REST Framework doesn't display value in PUT form Django form fields not showing up Models class Url_data(models.Model): uri_id = models.AutoField(primary_key=True) actual_url = models.URLField() created_on = models.DateTimeField( auto_now_add=True, editable=False, auto_now=False) expire_on = models.DateTimeField() short_url = models.URLField(max_length=200, editable=False) clicks = models.PositiveBigIntegerField( default=0, editable=True, blank=True) Serializer class Url_dataSerializer(serializers.ModelSerializer): class Meta: model = Url_data fields = '__all__' read_only_fields = ['short_url', 'created_on', 'clicks'] class ExpireDateUpdateSerializer(serializers.ModelSerializer): class Meta: model = Url_data fields = ('expire_on', ) View class UrlList(generics.ListCreateAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = Url_dataSerializer class UrlDetail(generics.RetrieveDestroyAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = Url_dataSerializer class ExpireDateUpdate(generics.UpdateAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = ExpireDateUpdateSerializer Error 405 Undocumented Error: Method Not Allowed **Response body** { "detail": "Method \"PATCH\" not allowed." } **Response headers** access-control-allow-origin: * allow: GET,DELETE,HEAD,OPTIONS content-length: 42 … -
Can't manage to post an object via axios to django - possibly due to AnonymousUser object?
I'm trying to add a button in React which posts an object to django via axios when a user clicks on it. However, it seems like something's wrong backend. Here's the button: <button id="add-rat" type="button" className="btn homeButton" onClick={ (e) => submit(e) } > Add rat </button> And here's the axios, in the same page: const submit = (e) => { const name = "namee"; const eyeColour = "Red"; const bodyColour = "White"; const bio = "hfff"; const image = "lineart.PNG"; const data = { name: name, eye_colour: eyeColour, body_colour: bodyColour, bio: bio, image: image, }; e.preventDefault(); console.log(data); const token = localStorage.getItem("token"); axios .post("http://127.0.0.1:8000/api/addObject", data, { headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, }) .then((res) => { console.log(res.data); }) .catch((err) => console.log(err)); }; This is my console output: {name: 'namee', eye_colour: 'Red', body_colour: 'White', bio: 'hfff', image: 'lineart.PNG'} myRats.js:86 {res: 'Error Accured'} (myRats.js:86 btw, is console.log(res.data); ) Here's my view for the object: class AddRat(APIView): def post(self,request): data = request.data user = request.user print(data) try: user = rat( name = data['name'] , body_colour = data['bodyColour'] , eye_colour = data['eyeColour'],user= user, bio = data['bio'] , image = data['image']) user.save() return Response({'res':"Rat Saved Successfully"}) except: return Response({'res':"Error Accured"}) def get(self,request): user = … -
real time chat app with django workds with channels but not after using redis and deploy to heroku
hello I am working on chatting app with django channels works perfectly in localhost but once I used redis and deployed to heroku I can't send anymessage the websocket always close, my settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } I am using redis and postgresql addons, and my Procfile is like this web: daphne myproject.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker --settings=myproject.settings -v2 why it works perfectly in my localhost because I am using only this CHANNEL_LAYERS = { "default": { "BACKEND": 'channels.layers.InMemoryChannelLayer' } }