Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django application mod_wsgi error with apache
I'm hosting Django app on AWS ec2 with ubuntu 20.04 lts. I can run the app with venv on various ports. I want to bind the app with apache so that my users can visit my app with just the public DNS no ports, only on the default port. So I have installed apache2, mod_wsgi. My virtual host configuration. <VirtualHost *:80> ServerAdmin test@example.com DocumentRoot /var/www/html/app_folder ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/html/app_folder/static <Directory /var/www/html/app_folder/static> Require all granted </Directory> Alias /static /var/www/html/app_folder/media <Directory /var/www/html/app_folder/media> Require all granted </Directory> <Directory /var/www/html/app_folder/main_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess app_folder python-path=/var/www/html/app_folder python-home=/home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py WSGIProcessGroup app_folder WSGIScriptAlias / /var/www/html/app_folder/main_app/wsgi.py </VirtualHost> So after configuring this vhost i restart my apache2 but I get nothing on the public dns. Instead I get the following error logs on my /var/log/apache2/error.log [Wed Dec 02 08:50:05.967958 2020] [wsgi:warn] [pid 121300] (13)Permission denied: mod_wsgi (pid=121300): Unable to stat Python home /home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site … -
how to add category to blog project django
i developed a blog project by watching many open-source courses and create my own django custom admin dashboard where i want to add a category option to my blog project, i have watched some tutorial on as well but couldn't find them helpful models.py from django.db import models from django.forms import ModelForm from farmingwave.models import BaseHeader,Submenu class Category(models.Model): mainmenu=models.ForeignKey(BaseHeader,null=True,on_delete=models.SET_NULL) submenu=models.ForeignKey(Submenu,on_delete=models.CASCADE) class AdSideMenu(models.Model): title_id = models.AutoField(primary_key=True) title_name = models.TextField() url = models.TextField() priority = models.IntegerField() submenu_status = models.TextField() class Meta: db_table = 'admin_side' class CreateBlog(models.Model): id = models.AutoField(primary_key=True) blog_Title = models.TextField(max_length=100) content = models.TextField(max_length=5000) category = models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) class Meta: db_table = 'create_blog' they are inhereting data from another app models.py `class BaseHeader(models.Model): main_id = models.AutoField(primary_key=True) title_name = models.TextField() url = models.TextField() priority = models.IntegerField() submenu_status = models.TextField("false") class Meta: db_table = 'base_header' class Submenu(models.Model): sub_id = models.AutoField(primary_key=True) main_id = models.IntegerField() sub_name = models.TextField() url = models.TextField() priority = models.IntegerField() mainmenu=models.ForeignKey(BaseHeader,on_delete=models.CASCADE) class meta: db_table = 'base_subheader'` and the view function: def create_blog(request): if request.method =='POST': form = CreateBlogForm(request.POST) if form.is_valid(): form.save() form = CreateBlogForm() else: form = CreateBlogForm() base = BaseHeader.objects.all() sub = Submenu.objects.all() create = CreateBlog.objects.all() category = Category.objects.all() context = { 'form' : form, 'createblog' : create, 'category' : category, … -
Bootstrap popover does not work with downloaded js and css
I am having some weird problem with using popover in my django app. When using the css and js of a latest version of bootstrap it simply does not work. When I use link to 3.4.1 version I found in some tutorial everything works just fine. I'm attaching code that doesn't work and the one that does. Did popover function got removed in latest bootstrap? Works (3.5.1): <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <a href="#" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Toggle popover</a> <script> $(document).ready(function(){ $('[data-toggle="popover"]').popover(); }); </script> Does not work (4.5.x): <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <a href="#" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Toggle popover</a> <script> $(document).ready(function(){ $('[data-toggle="popover"]').popover(); }); </script> -
Translating code from Django version 1.9 to version 2.0
I am currently trying to get started with Django. But the book am using is using Django version <1.9 while the current version is >2.0 The problem am facing right now is this code: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('learning_logs.urls', namespace = learning_logs')) ] I have looked around and this is what I have written from django.contrib import admin from django.urls import include, path app_name = 'learning_logs' urlpatterns = [ path('admin/', admin.site.urls), path('learning_logs/', include('learning_logs.urls', namespace = 'learning_logs')), ] but when I run the server I get the error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Any help with this. Thanks in advance -
Reverse for 'staff_info_update' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/staff/info/edit/(?P<pk>[0-9]+)/$']
I want to update additional information of staff class from update view of user class, where staff class has one to one relation with user class. These are my codes models class StaffInfo(models.Model): user = models.OneToOneField(User, related_name='staff_information', on_delete=models.CASCADE) views class StaffUpdateView(UpdateView): model = User form_class = StaffEditForm template_name = 'forms/staff_edit_form.html' context_object_name = 'staff' templates <a href="{% url 'staff_info_update' staff.staff_information.pk %}"> Additional Information </a> url path('admin/staff/info/edit/<int:pk>/', StaffAddInfoUpdateView.as_view(), name='staff_info_update'), -
How to use Django and angular together?
I've a django backend and angular frontend, on my local machine to use both together, I've to run both server's using ng serve and python manage.py runserver but now I'm planning to deploy it to heroku and I've no idea how will it work, also is there any official guide for using django and angular together. P.S. - I'm using django-rest-framework for making api calls from frontend to backend. -
How to decrypt django pbkdf2_sha256 algorthim password?
I need user_password plaintext using Django. I tried many ways to get plaintext in user_password. but It's not working. So, I analyzed how the Django user password is generated. it's using the make_password method in the Django core model. In this method generating the hashed code using( pbkdf2_sha256) algorthm. If any possible to decrypt the password. Example: pbkdf2_sha256$150000$O9hNDLwzBc7r$RzJPG76Vki36xEflUPKn37jYI3xRbbf6MTPrWbjFrgQ= -
How to redirect http://www.example.com to https://example.com with middleware
I got lost in deployment of my first django-application. The task I'm standing in front of is to redirect http://www to bare https://. The following is already working: https://www » bare https:// bare http:// » bare https:// But if I just type in www. I land on the standard Ubuntu/Apache site. middleware.py from django.http import HttpResponsePermanentRedirect class WwwRedirectMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): host = request.get_host().partition(':')[0] if host == "www.example.com": return HttpResponsePermanentRedirect( "https://example.com" + request.path ) else: return self.get_response(request) example.conf 1 <VirtualHost *:80> 10 ServerName example.com 11 ServerAdmin marcel@example.com 12 DocumentRoot /var/www/html 31 RewriteEngine on 32 RewriteCond %{SERVER_NAME} =example.com 33 RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] 34 </VirtualHost> example-le-ssl.conf 1 <IfModule mod_ssl.c> 2 <VirtualHost *:443> 11 ServerName example.com 12 ServerAdmin marcel@example.com 13 DocumentRoot /var/www/html 60 SSLCertificateFile /etc/letsencrypt/live/example.com-0001/fullchain.pem 61 SSLCertificateKeyFile /etc/letsencrypt/live/example.com-0001/privkey.pem 62 Include /etc/letsencrypt/options-ssl-apache.conf 63 </VirtualHost> 64 </IfModule> This is what I get with curl ~$ curl -I http://example.com HTTP/1.1 301 Moved Permanently Date: Wed, 02 Dec 2020 08:03:02 GMT Server: Apache/2.4.46 (Ubuntu) Location: https://example.com/ Content-Type: text/html; charset=iso-8859-1 ~$ curl -I http://www.example.com HTTP/1.1 200 OK Date: Wed, 02 Dec 2020 08:03:21 GMT Server: Apache/2.4.46 (Ubuntu) Last-Modified: Wed, 11 Nov 2020 22:26:44 GMT ETag: "2aa6-5b3dc4a55bcd4" Accept-Ranges: bytes Content-Length: 10918 Vary: … -
Django-Save form's Toggle Switch Values as 0's or 1's(as int) in the database
class postspage(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL,models.CASCADE, default=1 Spot_Light_Button_Hall=models.IntegerField(blank=True, null=True) Tube_Light_Button_Hall=models.IntegerField(blank=True, null=True) Fan_Slide_Hall=models.IntegerField(blank=True, null=True) Outside_Light_Button_Hall=models.IntegerField(blank=True, null=True) Tube_Light_Button_Kitchen=models.IntegerField(blank=True, null=True) Small_Light_Button_Kitchen=models.IntegerField(blank=True, null=True) Fan_Slide_Kitchen=models.IntegerField(blank=True, null=True) Exhaust_Fan_Slide_Kitchen=models.IntegerField(blank=True, null=True) Tube_Light_Button_Bedroom=models.IntegerField(blank=True, null=True) Small_Light_Button_Bedroom=models.IntegerField(blank=True, null=True) Fan_Slide_Bedroom=models.IntegerField(blank=True, null=True) Bathroom_Light_Button_Bedroom=models.IntegerField(blank=True, null=True) Tube_Light_Button_Admin_Room=models.IntegerField(blank=True, null=True) Small_Light_Button_Admin_Room=models.IntegerField(blank=True, null=True) Fan_Slide_Admin_Room=models.IntegerField(blank=True, null=True) Bathroom_Light_Button_Admin_Room=models.IntegerField(blank=True, null=True) Socket1_Button_Admin_Room=models.IntegerField(blank=True, null=True) Socket2_Button_Admin_Room=models.IntegerField(blank=True, null=True) class postform(forms.ModelForm): class Meta: model=postspage fields=['Spot_Light_Button_Hall', 'Tube_Light_Button_Hall', 'Fan_Slide_Hall', 'Outside_Light_Button_Hall', 'Tube_Light_Button_Kitchen', 'Small_Light_Button_Kitchen', 'Fan_Slide_Kitchen', 'Exhaust_Fan_Slide_Kitchen', 'Tube_Light_Button_Bedroom', 'Small_Light_Button_Bedroom', 'Fan_Slide_Bedroom', 'Bathroom_Light_Button_Bedroom', 'Tube_Light_Button_Admin_Room', 'Small_Light_Button_Admin_Room', 'Fan_Slide_Admin_Room', 'Bathroom_Light_Button_Admin_Room', 'Socket1_Button_Admin_Room', 'Socket2_Button_Admin_Room', ] widgets = { 'Fan_Slide_Hall': RangeInput(attrs={'type':'range', 'step': '1', 'min': '0', 'max': '4'}), 'Fan_Slide_Kitchen': RangeInput(attrs={'type':'range', 'step': '1', 'min': '0', 'max': '4'}), 'Fan_Slide_Bedroom': RangeInput(attrs={'type':'range', 'step': '1', 'min': '0', 'max':'4'}),} def posts_update(request,id): instance=get_object_or_404(postspage,id) form=postform(request.POST or None,request.FILES or None,instance=instance) if(form.is_valid()): instance=form.save(commit=False) instance.save() messages.success(request,"Successfully Edited") return HttpResponseRedirect(instance.get_absolute_url()) context ={ "instance":instance, "form":form, } return render(request,'update.html',context) Update.html: <form method='GET' action='' enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <input type="checkbox" id="xxx" value="{{ field.value }}" name="{{ field }}" onclick="calc();"/> <script> function calc() { if (document.getElementById('xxx').checked) { var s = document.getElementById(xxx); s.value = 1; } else { s.value = 0; } } </script> <!-- {% endfor %} </form> I want to display a django model form with toggle switches. If the user pushes the toggle button i.e.. true then 1 must be saved as the field value to the database else 0. The user … -
How to change variable in html template DJANGO
I wrote this variable(refactor) in my context dict. @login_required(login_url='/login') def lessont(request, id): if request.method == 'POST': form = ChapterForm(request.POST, request.FILES) if form.is_valid(): new_chapter = Chapter.objects.create(lesson_id=id) new_chapter.name = form.cleaned_data['name'] new_chapter.description = form.cleaned_data['description'] new_chapter.document = form.cleaned_data['document'] new_chapter.save() return redirect('/lessont/lesson/<int:id>') get_lessons = Lesson.objects.get(id=id) get_chapter = Chapter.objects.all().filter(lesson=id) get_group = StudentsGroup.objects.all().filter(lessons=id) form = ChapterForm() refactor = False refactor_id = 0 context = { 'get_lesson': get_lessons, 'get_chapter': get_chapter, 'get_group': get_group, 'form': form, 'refactor': refactor, <----- HERE 'refactor_id': refactor_id, } template = 'core/lessont.html' return render(request, template, context) <----- pass it here Then in my HTML template, I have an access to "refactor" variable and I want to change by clicking the button <button type="submit" name="button">Add</button> I want to make something like: <button type="submit" name="button" onClick={set "refactor" to True}>Add</button> -
Extracting data from the database table and display in view
I want to fetch the data from a table which is in database and then display it in tabular format in my webpage. Only the html column name is being shown but not the data from the database table. Can anyone please help me out with this? My codes: views.py: def display_majorheads(request): outputs = ProcessedOutputs.objects.all() be_year = 0 context = { 'processed_outputs':outputs, 'be_year':be_year, } return render(request, 'website/mhead.html', context ) mhead.html: <table class="table table-striped"> <tr> <th>MajorHead</th> <th>BeSalary</th> <th>BeGiaSalary</th> <th>BeOther</th> <th>BeTotal</th> <th>BeNextyrSalary</th> <th>BeNextyrGiaSalary</th> <th>BeNextyrOthrs</th> <th>BeNextyrTotal</th> </tr> {% for processed_outputs in outputs %} <tr> <td>{{ processed_outputs.major_cd }}</td> <td>{{ processed_outputs.be_salary }}</td> <td>{{ processed_outputs.be_gia_salary }}</td> <td>{{ processed_outputs.be_other }}</td> <td>{{ processed_outputs.be_total }}</td> <td>{{ processed_outputs.be_nextyr_salary }}</td> <td>{{ processed_outputs.be_nextyr_gia_salary }}</td> <td>{{ processed_outputs.be_nextyr_others }}</td> <td>{{ processed_outputs.be_nextyr_total }}</td> </tr> {% endfor %} </table> -
Django migrate/makemigrations does not work when postgres server is running
When the server is up and I give python manage.py makemigrations, it does nothing. It looks like it is waiting for something indefinitely. When I shutdown my pgAdmin4 server, it works fine. What could be the problem here? -
DJango model -Exception on crate :TypeError(\"save() got an unexpected keyword argument
I was building my api in DJango and rest framework . Please see my model file class StaffUser(models.Model): staff_id=models.CharField(max_length=100,null=True,) name=models.CharField(max_length=100,null=True) user=models.OneToOneField(User, on_delete=models.CASCADE,related_name='staffs') roles=models.ManyToManyField(BranchRole,related_name='holding_staffs') published_date = models.DateTimeField(blank=True, null=True) class Meta: db_table = 'staff_details' def save(self,*args,**kwargs): email =kwargs['email'] password=kwargs['password'] del kwargs['email'] del kwargs['password'] self.published_date = timezone.now() self.user=User.objects.create_user( email=email, password=password, is_staff=True, is_active=1 ) super(StaffUser,self).save(**kwargs) return self def __str__(self): return self.name When I am trying to call this save function in viewset , I am getting following exception. "Exception on crate :TypeError("save() got an unexpected keyword argument 'name'" Please help me to resolve this error. Please see my code in viewset class StaffUserViewSet(viewsets.ModelViewSet): """ This api deals all operations related with module management You will have `list`, `create`, `retrieve`, update` and `destroy` actions. Additionally we also provide an action to update status. """ serializer_class = StaffUserSerializer permission_classes = [permissions.AllowAny] queryset = StaffUser.objects.all() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ARG={ 'staff_id':str, 'phone_number':str, 'email':str, 'name':str, 'password':str, 'address':str, 'id':int, 'roles':dict, } self.REPLACING_VALUES={ 'model_name':'content_type__model_name', 'content_type_id':'content_type__id', 'app_name':'content_type__app_label' , 'app_label':'content_type__app_label' } self.DEFAULT_PARAMETERS={ 'content_type__status__active':True } self.VIEW_PARAMETERS_LIST=[ ] self.detailed_view=False # if any user argument having another label that model relation # will replace the smame with replacement values""" self.api_model=StaffUser() def create(self, request): #over ride create method in view set status='Sucess' # set … -
Django - Pass a dictionary to template through the get_queryset function of a class based view
Is there a way to return a dictionary through the get_queryset function of a class based view in Django? I want to pass the array tickets and the string email to my template, but I am only able to pass tickets right now. Content of views.py: class UserTicketListView(ListView): model = Ticket template_name = 'ticket_system/user_tickets.html' context_object_name = 'tickets' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) email = User.objects.get(username=user).email return Ticket.objects.filter(author=user).order_by('-date_posted') -
Outputting two colums of dataframe into Django template using For Loop
I am trying to parse 2 columns of my dataframe(my_tweet_df) from views to Django. The dataframe is off Tweets data which I fetched from Tweepy. I hope for my output to look like this: USERNAME TWEET username1 tweet of username1 username2 tweet of username2 ..... ..... In my HTML page, code looks like this: <table class="table table-hover"> <tr> <th><h4>Username</h4></th> <th><h4>Tweet</h4></th> </tr> {% for key in my_tweet_df %} <tr> <td>{{key.author}}</td> <td>{{key.text}}</td> </tr> {% endfor %} </table> I do not know how to do so using for loop. I have tried passing dataframe: {% for key in dataframe %} with {{key.user}} and {{key.text}}. I know this approach is not correctenter code here as it is looping through range of dataframe not values of one column. I have tried converting to single columns and back to dataframe and passing like: my_tweet_df = pd.DataFrame(list(zip(my_tweet_df.user, my_tweet_df.text)), columns=['username', 'status']) But that again doesn't work because it is a 2D arary now and has a range of 2 only. Even if I try to pass them separately, I don't know how to do so using 2 for loops, like: {% for key in text %} <tr> <td>{{key}}</td> <td>{{key}}</td> </tr> {% endfor %} But in the above approach … -
How to use wildcards for key/object to generate aws pre-signed url in django
My requirement is to upload multiple webm files(which are captured using webrtc) to s3 using one time generated pre-signed url. I have tried below code to generate pre-signed url and using postman to upload files def create_presigned_url(method_name,s3object,expiration=36000): try: response = s3_client.generate_presigned_post(S3Bucket, Key = "", Fields=None, Conditions = [ ["content-length-range", 100, 1000000000], ["starts-with", "$key", "/path-to-file/] ], ExpiresIn=expiration) except Exception as e: logging.error(e) return None return response Getting the below error when i tried from postman -
Image is not saving in folder. ( Also added :- " <form method="post" enctype="multipart/form-data"> " in templates )
new_blog.html {% block content %} <p>Add a New Blog:</p> <div class="container"> <form method="post" enctype="multipart/form-data"> <form action="{% url 'mains:new_blog' %}" method='post'> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Save Changes</button> </form> </div> {% endblock content %} models.py class Blog(models.Model): blog_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) blog_title = models.CharField(max_length=500,default='') image = models.ImageField(upload_to='blogs',blank=True,null=True) forms.py class BlogForm(forms.ModelForm): class Meta: model = Post fields = ('blog_title','image',) I have tried everything but the image is not saving in the folder and not showing in the Local Host page. Please help me in this. I will really appreciate your Help. -
Python json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I'm trying to make a web api that accepts image and return location of faces in it. i copied the tutorial from https://www.pyimagesearch.com/2015/05/11/creating-a-face-detection-api-with-python-and-opencv-in-just-5-minutes/ at first it worked just fine, i was able to send image url from python project to django. However today, it no longer works, and giving me json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) error. I've deleted the code and re-copy it from the article, did not change anything, and it still giving me the exact same error. heres the django views.py code : FACE_DETECTOR_PATH = "{base_path}/cascades/haarcascade_frontalface_default.xml".format( base_path=os.path.abspath(os.path.dirname(__file__))) @csrf_exempt def detect(request): # initialize the data dictionary to be returned by the request data = {"success": "dipshit"} # check to see if this is a post request if request.method == "POST": # check to see if an image was uploaded if request.FILES.get("image", None) is not None: # grab the uploaded image image = _grab_image(stream=request.FILES["image"]) # otherwise, assume that a URL was passed in else: # grab the URL from the request url = request.POST.get("url", None) # if the URL is None, then return an error if url is None: data["error"] = "No URL provided." return JsonResponse(data) # load the image and convert image = _grab_image(url=url) # … -
Adding mysql database credentials to environment variable results in operational error
I'm deploying a django web app with Heroku. I have a MySql database. When my settings.py file contains hardcoded password and username for the mysql database, everything works. I decided to store my username and password in environment variables, and rewrote the settings.py file as shown below. DB_USER = os.environ.get('DB_USER') DB_PASS = os.environ.get('DB_PASSWORD') DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pahlisch', 'USER': DB_USER, 'PASSWORD': DB_PASS, 'HOST': '123.mysql.database.azure.com', 'PORT': '3306', 'OPTIONS': {'sql_mode': 'STRICT_ALL_TABLES'} } } Next, I added my local environment variables to Heroku. When I attempt to load the site, I get the following message. (1045, "Access denied for user ''mattrw2'@'44.167.157.221' (using password: NO)") I don't understand what is wrong. -
Django: File upload and save using Ajax
I'm not sure if somehow the directory is wrong or there's just some kind of common mistake in my code, but I just am not able to save my uploaded file to a folder, or more specifically, the media folder as demonstrated in a lot of examples. I'm just taking a text field and the file and saving it in the DB using Ajax, and it works too, except that whatever file I'm selecting, it's not getting saved in the media folder even if I create one manually nor is it creating one on its own either. I can get this to work without Ajax but not with it. Maybe it's something related to how I'm sending and handling data over Ajax, but I've gone through tons of forums to try and fix it but no results so far. I've double checked everything else such as the settings.py config and the libraries that I've imported, everything looks to be in order. I'm sharing the code below. index.html <body> <div class="container-fluid"> <div class="col-md-4"> <form id="data" enctype="multipart/form-data"> <label for="docn"> <input type="text" id="docn" placeholder="Please enter document name"> </label> <label for="docc"> <input type="file" id="doc" name="docu"> </label> <button type="button" onclick="enterdata()">Submit</button> </form> </div> </div> <script> function … -
django, detail: Authentication credentials were not provided. (CSRFToken)
] ------ react ------ csrftoken.js import axios from 'axios'; import React from 'react'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; 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].replace(' ', ''); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export const CSRFToken = () => { const csrftoken = getCookie('csrftoken'); console.log('token : ' + csrftoken); return( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken}/> ) }; export default CSRFToken; module.js const getplayerEpic = (action$, state$) => { return action$.pipe( ofType(GET_player), withLatestFrom(state$), mergeMap(([action, state]) => { console.log(state.CSRFToken.props.value) return ajax.get('/api/player/', {headers: {'X-CSRFToken': state.CSRFToken.props.value }} ).pipe( map(response => { const player = response.response; return getplayerSuccess({player}); }), catchError(error => of({ type: GET_player_FAILURE, payload: error, error: true, }) ) ); }) ); }; ------ django(python) ------ view.py class Listplayer(generics.ListCreateAPIView): permission_classes = [djangomodelpermissions, ] queryset = playerList.objects.all() serializer_class = playerListSerializer I can not speak English very well. hope you understand. I want to use csrftoken, but details: no authentication credentials were provided. An error occurs. What is the reason? If you know, let me … -
Django Search Implementation, conditional routing
I am trying to implement basic search functionality with Django. If exact search query page exists, display that page If there is a page title that contains what was queried, show results of all If neither, display a message stating no results found I'm just learning, so I tried functional views and class based views. I've spent a really long time on documentation/videos/textbooks and don't see how to get the intended behavior out of class-based view. I understand collecting object_list and getting query_set, but how do you then route to those three different conditions. I tried overriding dispatch() and as_views() method to no avail. Tried with a Django form class and without. For some reason, the functional view keeps executing the first try statement instead of throwing a DoesNotExist exception when the exact match isn't found. So it shows the entry page instead of the search results page. It seems like the request.GET is None type no matter what, as when I try to print nothing shows up. urls.py from re import search from django.urls import path from . import views from .views import IndexPageView, SearchView app_name = "wiki" urlpatterns = [ # ex: /wiki/ path("", views.index, name="index"), # path("", … -
How to customized this [Authentication credentials were not provided] error message in django rest framework
When I don't pass the header in postman then DRF give me this msg. {"detail": "Authentication credentials were not provided."} But I want custom message like. { "status": False, "message": "Authentication credentials were not provided.", "data": {} } -
Post matching query does not exist
urls.py path('posts/',views.posts,name='posts'), path('<id>',views.detail_view,name='detail_view'), views.py def detail_view(request,id): context = {} context["data"] = Post.objects.get(id=id) return render(request, 'mains/show_more.html', context ) def posts(request): posts = Post.objects.all().order_by('-date_added') context = {'posts':posts} return render(request, 'mains/post.html', context) post.html {% block content %} {% for topic in posts %} <a>{{ topic.description}}</a> <a href="{% url 'mains:detail_view' topic.post_owner.id %}">Show More</a><br> <br> {% empty %} No yet.</li> {% endfor %} </ul> <a href="{% url 'mains:new_post' %}">Add a New Diary</a> {% endblock content %} show_more.html {% block content %} {{ data.post_title }} {% endblock content %} Post matching query does not exist. This error is raising when i click on show_more in posts page. Please Help me in this. I will really appreciate your Help. -
Best way for creating websocket in django
I want to implement a WebSocket. I use the Django rest framework. I tried the channels. Does the socket keep alive for a long time in the channel? What is the best way to do this in Django?