Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SESSION_EXPIRE_AT_BROWSER_CLOSE where we need to write in our project in django?
In django for expire a session after closing a browser where we need to type SESSION_EXPIRE_AT_BROWSER_CLOSE this in which file?? -
django rest_framework with React
I am trying to build an application with django as backend using REST API and front end with React. I have a model named User which contains attributes like firstname, lastname, email,password,description etc, now from front end I want to create a new user and save it to my Database, I can do this using axios and calling out put method, but before saving it to my Database I want to the profile to be verified by admin panel, like whenever user tries to signUp a new_request profile is triggered and the profile goes to admins, if they accept the profile the user is successfully added to the database, I am not getting how to do this stuff! -
How to display the old of the post in django using python?
Help me guys i am new to django and here too,, how can i display the old of the post in django so that the post time will be shown as posted 0 minute ago,, 3 weeks ago and so on to years?? -
Error during template rendering (NoReverseMatch) in Django 3.0.3
Error : Reverse for 'lesson-detail' with keyword arguments '{'course_slug': 'django-101', 'lesson-slug': 'first'}' not found. 1 pattern(s) tried: ['(?P < course_slug>[^/]+)/(?P< lesson_slug>[^/]+)$'] urls.py from django.urls import path from .views import CourseListView, CourseDetailView, LessonDetailView app_name = 'courses' urlpatterns = [ path('', CourseListView.as_view(), name='list'), path('<slug>', CourseDetailView.as_view(), name='detail'), path('<course_slug>/<lesson_slug>', LessonDetailView.as_view(), name='lesson-detail') ] course_detail.html <!DOCTYPE html> <html> <head> <title>Detail view</title> </head> <body> {{ object.title }} {% for lesson in object.lessons %} <a href="{{ lesson.get_absolute_url }}">{{ lesson.title }}</a> {% endfor %} </body> </html> -
im not able to makemigrations to my already built model after extending user model to it in django
im just stuck with error while making migrations to my django project. in my project which is already 50% dveloped i use owner model to represent owner of shop and then i used user model for login and for registration purpose. so i tried to use user model in my owner model so i could utilise both model effectively with additional fields. i tried to extend user model in owner model using onetoone field. after doing that i was not able to do migrations so i deleted all migrations files but after that it was start giving this error while doing migrations:- py manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Mayur\PycharmProjects\StartUp\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\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 87, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", … -
Django-Insert Drop Down Value to postgresql
I'm very new to Django and I would like to Insert a drop down box value to database: Created two django-apps named 'Projects' and 'Clients'.After add the relevant client data ,I am trying to add the corresponding project through drop down ,the values comes from project app's corresponding table. But something went wrong , clients model Create your models here. class clients(models.Model): cname=models.CharField(max_length=20) cadd=models.TextField(max_length=50) cmob=models.BigIntegerField() cemail=models.EmailField(max_length=100) cproject=models.CharField(max_length=50,default=None) class Meta: db_table="client" project model class projects(models.Model): pname=models.CharField(max_length=100) pcode=models.CharField(max_length=100) loc=models.CharField(max_length=50) class Meta: db_table="projects" corresponding Views for add drop down value clients app def add(request): # show projects details from DB if projects.objects.count()>0: data=projects.objects.all() return render(request,'add.html',{'data':data}) else: return render(request,'add.html') def addpro(request): if request.method=="POST": temp.cproject=request.POST['sel'] temp.save() return redirect(addpro) else: return render(request,'add.html') html for dropdown list and selection <div class="container"> <form method="POST"> {% csrf_token %} <select name="sel"> <option selected disabled="true"> -- Select -- </option> {% for var in data %} <option >{{var.pname}}</option> {% endfor %} </select> <a class="btn btn-info" type="submit" href="{% url 'addpro'%}"><i class="fas fa-list-alt"></i>Add</a> </form> </div> -
HTTP Error 401: Unauthorized SendGrid django
I'm trying to do mail subscription on my django website I was following instructions online on how to achieve this. I went through it carefully but whenever I enter and email is say HTTP Error 401: Unauthorized. I went ovewr the instructions and couldn't find were i went wrong. Settings code FROM_EMAIL = 'newsletter@example.com' # replace with your address SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY') Models code: class Subscriber(models.Model): email = models.EmailField(unique=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" class Newsletter(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subject = models.CharField(max_length=150) contents = models.FileField(upload_to='uploaded_newsletters/') def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") def send(self, request): contents = self.contents.read().decode('utf-8') subscribers = Subscriber.objects.filter(confirmed=True) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) for sub in subscribers: message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject=self.subject, html_content=contents + ( '<br><a href="{}/delete/?email={}&conf_num={}">Unsubscribe</a>.').format( request.build_absolute_uri('/delete/'), sub.email, sub.conf_num)) sg.send(message) Views.py def random_digits(): return "%0.12d" % random.randint(0, 999999999999) @csrf_exempt def subscribe(request): if request.method == 'POST': sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject='Newsletter Confirmation', html_content='Thank you for signing up for my email newsletter! \ Please complete the process by \ <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \ confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'), … -
Django adding placeholder text for PasswordChangeView?
A user can change their password on my change password page: <form class="password-change-form" method="POST"> {% csrf_token %} <div> {{ form }} </div> <input class="submit-button" type="submit" value="Change password"> </form> My urls.py: path( 'accounts/password_change/', auth_views.PasswordChangeView.as_view(template_name='account/password_change_form.html'), name='password_change' ), The problem PasswordChangeView uses PasswordChangeForm by default. I would like to add placeholder text to this form i.e. Old password placeholder text: 'Enter your old password'. How can I best do this? -
Facing xome issue while running a docker build contains a django project code
I am working on a project, Generating a pdf file after rendering a HTML template with dynamic data using pdfkit which requires wkhtmltopdf that needs to b e installed on root or any directory, i installed it on root and everything is working fine locally but when i am making a docker build to push on a server then its returning an error because of wkhtmltopdf package not found, can anyone guide to solve the error. -
how to use FilterSet in django with DateTimeFromToRangeFilter
I'm trying to filter a Model using Filterset (django-filter) and render from/to select form field in my Template. Unfortunately I cannot figure out how to get it working. While my "code" and "power_category" fields render fine, only a text field gets displayed when trying to render the "reported" field, unless I set type="date", then the datepicker pops up when clicking the date field, however only one shows up (need two, "to" and "from" to select the range). I'm using django 3.0.5, django_filters and widget_tweaks are included in settings and I see no errors. Thank you for your time... Filters.py import django_filters from django_filters import DateRangeFilter, DateFilter from django_filters import DateTimeFromToRangeFilter from django_filters.widgets import RangeWidget from reports.models import Report from django import forms class PostFilter(django_filters.FilterSet): reported = django_filters.DateTimeFromToRangeFilter( widget=django_filters.widgets.RangeWidget( attrs={'class': 'datepicker'} ) ) class Meta: model = Report first_name = django_filters.CharFilter(lookup_expr='icontains') fields = ['reported', 'fixed', 'code', 'power_category'] ] Template {% load widget_tweaks %} <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.code.label_tag }}<br /> {% render_field filter.form.code class="form-control" %} </div><br /><br /> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.power_category.label_tag }}<br /> {% render_field filter.form.power_category class="form-control" %} </div> <div>Date_Time {{ filter.form.reported.label_tag }} {% render_field filter.form.reported %} </div> … -
ModuleNotFoundError while importing a class from different app
In my django project LibraryManagement I have two apps 'book' and 'authors'. I am trying to establish relationship between two apps using foreign key. While I try to import class Authors in the book I got error ModuleNotFound:No module named 'LibraryManagement.authors' Below is my project structure LMS -LibraryManagement -authors -book -LibraryManagement -venv Code of models.py from authors app from django.db import models class Authors(models.Model): author_name = models.CharField(max_length=100) description = models.TextField(max_length=300) Code of models.py from book app from django.db import models from LibraryManagement.authors.models import Authors class Book(models.Model): book_name = models.CharField(max_length=100) author = models.ForeignKey(Authors) remarks = models.TextField(max_length=300) -
Default HyperlinkedModelSerializer not finding the endpoints
I am trying to simply change my ModelSerializer to HyperlinkedModelSerializer to include the url to each of the objects listed in the ListView of the default Browsable API. According to the docs, since I am using default 'pk' for the lookup, I just change the class I inherit the serializer from: # class SeasonSerializer(serializers.ModelSerializer): class SeasonSerializer(serializers.HyperlinkedModelSerializer): # url = serializers.HyperlinkedIdentityField( # view_name='season', lookup_field='pk') ---> Not needed according to docs but have also tried with this class Meta: model = Season fields = ('id', 'url', 'years', 'active') And add the context when instantiating it in the view: class SeasonListView(APIView): def get(self, request, *args, **kwargs): queryset = Season.objects.all().order_by('years') serializer = SeasonSerializer( queryset, many=True, context={'request': request}) print('INFO: ', serializer) permission_classes = [ ] authentication_classes = [ ] return Response({"Seasons": serializer.data}) class SeasonDetailView(APIView): def get(self, request, *args, **kwargs): pk = kwargs['pk'] season = get_object_or_404(Season, pk=pk) serializer = SeasonSerializer(season, context={'request': request}) # print('Data: ', serializer.data) --> this breaks return Response(serializer.data) And my endpoints are the same as when using ModelSerializer: urlpatterns = [ path(r'seasons/', SeasonListView.as_view(), name='season-list'), path(r'seasons/<int:pk>/', SeasonDetailView.as_view(), name='season-detail'), ] The error is the following: For http://localhost:8000/api/seasons/1/ Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "season-detail". You may … -
How to ensure all custom values from settings.py are avaibalable in Django project?
I defined a few custom values in my Django project "settings.py" file. I need to load those values into my views ans other project files, but not all values defined in settings.py seem to be available. settings.py # My custom settings API_URL = 'http://10.0.0.1' EMAIL_DEFAULT_RECIPIENT = 'foo@bar.tld' I load the whole settings.py file content using the following in my view: views.py my_view(request,foo_id): from django.conf import settings as project_settings # First log output logger.debug('API_URL: ' + project_settings.API_URL) # Second log output logger.debug('EMAIL_DEFAULT_RECIPIENT: ' + project_settings.EMAIL_DEFAULT_RECIPIENT) The first log output (API_URL value) is correct: [2020-00-00 00:00:00 +0000] [16381] [DEBUG] (my_app.views) API_URL : http://10.0.0.1 Strangely the second log output (EMAIL_DEFAULT_RECIPIENT value) throws an exception: AttributeError: 'Settings' object has no attribute 'EMAIL_DEFAULT_RECIPIENT' Django project layout my_project ├── my_app │ ├── migrations │ ├── __pycache__ │ └── templates ├── my_project │ ├── __pycache__ │ ├── static │ └── templates ├── __pycache__ └── venv ├── bin ├── include ├── lib └── lib64 -> lib My Django project is served through NGINX/Gunicorn started by a systemd service unit within a venv. It worth mentionning that I restarted this service after changing settings.py content. I also cleared __pycache__ project directory content manually but this has no effect on … -
Get group name of the user in Django keycloak
I am using keycloak and django for authentication of users via django-keycloak package. I want to get the group name of a user belonging to in keycloak in django. Also I am new to keycloak authorization service -
Axios post request with nested object
I need help with axios post with multiple student objects in one single class. Class form has various fields with an option to add dynamically multiple students. Add only student names for the objects but be able to edit the student details to give full details.Backend is Django. { "students": [ { "stud_fname": "First Name", "inter_lname": "Last Name", "class_section": "class", }, { "stud_fname": "First dsfdsfName", "inter_lname": "Last sdfName", "class_section": "cladsfdfss", } ], "ClassName": "eqwe", "TeacherName": "eqw", "SchoolNAme": "eqw", } -
Setting up router with APIView and viewset in Django Rest Framework
It's my first question on Stackoverflow ! I'm new to Django and following some tutorials. I'm trying to understand if there is a way to set up the routing of an API from different view classes like APIView and viewsets.ModelViewSet (please tell me if I do not use the good wording) In views I have : from rest_framework import viewsets from post.models import UniquePost from .serializers import UniquePostSerializers from rest_framework.views import APIView class UniquePostViewSet(viewsets.ModelViewSet): serializer_class = UniquePostSerializers queryset = UniquePost.objects.all() class FileUploadView(APIView): some code here but no queryset nor serialized data...and no model In urls I have : from post.api.views import UniquePostViewSet from django.urls import path, include from rest_framework.routers import DefaultRouter from post.api.views import FileUploadView router = DefaultRouter() router.register('UniquePost', UniquePostViewSet, base_name='uniquepostitem') router.register('demo', FileUploadView, base_name='file-upload-demo') urlpatterns = router.urls But it seems that I can register FileUploadView this way. Because I don't have a queryset to render. I have : AttributeError: type object 'FileUploadView' has no attribute 'get_extra_actions' I realized that (well I think) that I can use APIView for FileUploadView (and add ".as_view()) but I think I have to rewrite UniquePostViewSet using APIView as well and defining exactly what I want to see in details like POST, PUT etc... My question … -
How do I build a voice message app in Django? I am a beginner in Django and only know the basics. Where do I start?
I want to buid a voice message app, plan to build on Django, but I am a beginner in Django, how do I start the project? Django is suitable for this project? -
How do I fetch the row associated with the currently logged in user in django and display specific fields in template?
I have a table account that is tied up to the User model by a One to One relationship in django, this account table is meant to store additional information related to the users in the User model. I want to fetch the row in account table of the current user that is logged in/active and display specific data of the user like "designation" or "ac_type" in my template. models.py class account(models.Model): username=models.ForeignKey(User, on_delete=models.CASCADE) first_name=models.CharField(max_length=100) ac_type=models.CharField(max_length=100) designation=models.CharField(max_length=100) drone_id=models.ForeignKey(asset,null= True, on_delete=models.CASCADE) def __str__(self): return self.first_name views.py def dashboard(request): as_data = asset.objects.filter(status=True) #where context = {'as_data':as_data} return render (request, 'dashboard.html',context) def dash_2(self): u=self.request.user ac_data = account.objects.filter(id__in=u).values() context2 = {'ac_data':ac_data} return render (self, 'dashboard.html',context2) dashboard.html <html> <body> My designation is: <br> <p>{{ac_data.designation}}</p> </body> </html> I am a newbie in django so any help would be really helpful. Thanks in advance ! -
Django search form, disambiguation page
Hello everybody I keep having this problem with my search form in my website. The thing is that, based on the user input, i check if in the database there're some results. But if the input is both in band column and album colum I'd like the user to be redirected to a 'disambiguation' html page. This is my views.py but it doesn't work. Hope someone could help me, thanks! Views.py class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: sr = Info.objects.filter(Q(band__icontains=srch)) sd = Info.objects.filter(Q(disco__icontains=srch)) if sr is sd: return render(self.request, 'search/disambigua.html') else: paginator = Paginator(sr, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(self.request, 'search/searches.html', {'sr':sr, 'sd': sd, 'page_obj': page_obj }) else: return render(self.request, 'search/searches.html') -
the value inside the class modal-body is showing only the first object of the Django model 'hostels'
the value inside the class modal-body is showing only the first object of the Django model 'hostels' , but when 'edit' in this code is replaced with {{hostel.hostel_name}} its working fine. what's the issue {% for hostel in hostels %} <div class="container" style="width: 48%;margin: 10px;height: 140px;background-color: white;display: inline-block;position: relative;"> <a href="{{hostel.pk}}/deletehostel/" style="color: white;position: absolute;top: 0px;right: 0px;margin: 0px;padding: 0px;padding-right: 5px;padding-left: 5px;background-color: red"> X </a> <a href="{{hostel.pk}}" style="text-decoration: none"> <h1 style="text-align: center;">{{hostel.hostel_name}}</h1> <p style="text-align: center;">total beds: {{hostel.capacity}}</p> </a> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter" style="display: block;margin: auto">edit</button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Edit details here</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <input type="text" class="form-control" value="{{hostel.hostel_name}}" name="" placeholder="hostel name"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> {% endfor %} -
How to write a query to get the number of times a choice is selected by users
I want to count the number of times a choice is selected by users. Here is my model models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from multiselectfield import MultiSelectField class MedicalHistory(models.Model): Anxiety = 'Anxiety' Arthritis = 'Arthritis' Asthma = 'Asthma' Anemia = 'Anemia' Cancer = 'Cancer' Corona_virus = 'Corona_virus' Diabetes = 'Diabetes' Ebola = 'Ebola' HIV = 'HIV' ILLNESS_CHOICES = ( (Anxiety, "Anxiety"), (Arthritis, "Arthritis"), (Asthma, "Asthma"), (Anemia, "Anemia"), (Cancer, "Cancer"), (Corona_virus, "Corona_virus"), (Diabetes, "Diabetes"), (Ebola, "Ebola"), (HIV, "HIV"), ) user = models.ForeignKey(User, on_delete=models.CASCADE) illness = MultiSelectField(choices=ILLNESS_CHOICES, max_length=50) symptoms = models.CharField(max_length=100) additional_info = models.CharField(max_length=100) disability = models.BooleanField(default=False) medications = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Medical History' Here I have a number of illnesses I want users to select from. A user can select more tan one illness. I want each illness to have a count, and every time the illness is selected it adds to the count. In my view I have views.py def pie_chart(request): labels = [] data = [] queryset = MedicalHistory.objects.values('illness').annotate(count=Sum('user')).order_by('-count') for entry in queryset: labels.append(entry['illness']) data.append(entry['count']) return JsonResponse(data={ 'labels': labels, 'data': data, }) <QuerySet [{'illness': ['Asthma', 'Diabetes', 'Ebola'], 'count': 3}, {'illness': ['Anemia', 'Covid-19'], 'count': 2}]> The query … -
Django setup elasticsearch client with password auth
My Django application uses elasticsearch to index several ressources. Now I wanted to protect my elasticsearch instance with as password wich is working fine if I use "curl -u" or so. Anyways from the elasticsearch_dsl documentation, found here: https://elasticsearch-dsl.readthedocs.io/en/latest/configuration.html I do not understand what I have to do in order to setup elasticsearch that way that it uses a password for authentication and where do I have to place this code?! Is smb. maybe able to pass show me some snippets of his configuration? My current state looks like this: settingy.py ELASTICSEARCH_DSL = { 'default': { 'hosts': env.str('ELASTICSEARCH_HOST') + str(':') + env.str('ELASTICSEARCH_PORT'), }, } ELASTICSEARCH_DSL_SIGNAL_PROCESSOR = 'django_elasticsearch_dsl.signals.RealTimeSignalProcessor' documents.py from django_elasticsearch_dsl import Document, Index, fields from elasticsearch_dsl import analyzer from App.models import Post # elasticsearch index posts = Index('posts') html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @posts.document class PostDocument(Document): ... more index stuff According to the docs I have to manually setup a default client connection where I can also pass the password and username for authentication wich to me seems not to be possible at settings.py at moment. Kind regards -
image is not showing in django templates am new in django and working on a project...i idid lots of rid of this error but nothing happen
am trying to show pic in django tempate but its not working here is my settings.py where the path of static and media file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR , "media") this is my model.py the image is store under static/img folder class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) image_of_load = models.ImageField(default='',upload_to='static/img') weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) this is my html template for showing user posted data {% extends "post.html" %} {% block content %} {% load static %} {% for loader in Loader %} <h4>Loader Id- {{loader.id}}</h4> Username-{{user.username}} <h3>Sender name-{{loader.sender_name}}</h3> </h4> <p class="card-text"> <h4>pick up station-{{loader.pick_up_station}}</h4> </p> <img src="{{ loader.image.url }}" alt="image"> <p class="card-text">{{loader.destination_station}}</p> <p class="card-text">{{loader.phone_number}}</p> <p class="card-text">{{loader.receiver_name}}</p> <p class="card-text">{{loader.sending_item}}</p> <p class="card-text">{{loader.weight}}</p> <p class="card-text">{{loader.quantity}}</p> <p class="card-text">{{loader.pick_up_time}}</p> <p class="card-text">{{loader.drop_time}}</p> <p class="card-text">{{loader.paid_by}}</p> <p class="card-text">{{loader.created_at}}</p> <a class="btn btn-primary" href="{% url 'Loader:Delete' loader.id %} ">delete</a> <a class="btn btn-primary" href="{% url 'Loader:Update' loader.id %} ">update</a> </div> {% endfor %} {% endblock content %} … -
WebSocket connection to <heroku-app>' failed: Error during WebSocket handshake: Unexpected response code: 500
I deployed django-channels project on heroku. The project works fine locally but on heroku it doesn't function, i-e no websocket connection is established. my consumers.py is: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'quiz_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) my routing.py is: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import quiz_app.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( quiz_app.routing.websocket_urlpatterns ) ), }) my Procfile is : web: daphne quizbackend.asgi:application --port $PORT --bind 0.0.0.0 -v2 And I am using in-memory layer for testing purpose, which is : CHANNEL_LAYERS={ "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } also my heroku logs --tail are : 2020-04-09T11:16:08.616718+00:00 app[web.1]: ^ 2020-04-09T11:16:08.616718+00:00 app[web.1]: 2020-04-09T11:16:08.616903+00:00 app[web.1]: 2020-04-09 11:16:08,616 INFO failing WebSocket opening … -
Django CSRF Token is not getting set
So i am using VueJS and Django. Axios to make a get request. When i try to retrieve the CSRF token and log it, it shows me it is null. here is my serializer: class VehicleSerializer(serializers.ModelSerializer): seller = serializers.SerializerMethodField() class Meta: model = Vehicle fields = ('vehicle_id', 'color', 'model', 'year', 'category', 'manufacturer', 'seller') def get_seller(self, instance): return instance.seller.customer.username My Viewset: class VehicleListCreateAPIView(ListCreateAPIView): serializer_class = VehicleSerializer permission_classes = [IsAuthenticated] queryset = Vehicle.objects.all() def perform_create(self, serializer): request_user = self.request.user try: seller = Seller.objects.get(customer = request_user) except Seller.DoesNotExist: seller = Seller.objects.create(customer = request_user) serializer.save(seller = seller) My urlpattern: path('vehicles/', VehicleListCreateAPIView.as_view()), The code from django documentation to retrieve a token: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); export { csrftoken };