Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extend the settings file in Django?
I'm using Constance - Dynamic Django settings to configure some values in my project. according to Constance, I should add all the configurations in the settings.py file. but I need to separate this configuration in another file. I tried to extend the settings file by doing the code below, but it didn't work it is not reading the value from that new file. from .settings import * CONSTANCE_ADDITIONAL_FIELDS = { 'corres_format_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': (("xx - xx", "xx - xx"), ("xx/xx", "xx/xx"), ("xx : xx", "xx : xx"))}], 'date_format_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': (("dd/mm/yyyy", "dd/mm/yyyy"), ("mm/dd/yyyy", "mm/dd/yyyy"), ("dd-mm-yyyy", "dd-mm-yyyy"))}], } CONSTANCE_CONFIG = { 'Correspondence_format': ("xx - xx", 'Choose the correspondce format', 'corres_format_select'), 'Date_format': ("dd/mm/yyyy", 'Choose the date format', 'date_format_select'), } -
Django coverage missing at line 262 despite only having 77 lines in file?
So I have these outputs as the coverage report story_6/tests.py 60 21 65% 269-580 story_6/urls.py 5 1 80% 262 story_6/views.py 35 6 83% 262-300 I do not understand how these 3 have missing coverage despite each file only having around 70 lines, when I open the coverage HTML, it just shows 6 missing (for views.py) but I see no red backgrounds or lines. -
search on site django2.2
# my models.py class Post(models.Model): image = models.ImageField(upload_to=get_timestamp_path, verbose_name='Изображение') author = models.ForeignKey(AdvUser, on_delete=models.CASCADE, verbose_name='Автор') created_at = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Опубликовано') tags = models.ManyToManyField( 'main.Tag' ) @property def tags_list(self): return ', '.join(self.tags.values_list('name', flat=True).all()) def __str__(self): return f"{self.image}: {self.tags_list}" class Meta: verbose_name_plural = 'Посты' verbose_name = 'Пост' ordering = ['-created_at'] class Tag(models.Model): name = models.CharField(max_length=15, verbose_name='Тег') created_at = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Опубликовано') def __str__(self): return self.name class Meta: verbose_name_plural = 'Теги' verbose_name = 'Тег' ordering = ['-created_at'] # my views.py from django.db.models import Q def get_filter(q): filter_ = Q() if q is not None: # this is an invalid logic: filter_ = Q(tags__in=Tag.objects.filter(name__in=q.split(','))) # return filter_ def index(request): q = request.GET.get('q') if q: posts = Post.objects.filter(get_filter(q)).distinct() else: posts = Post.objects.all() paginator = Paginator(posts, 10) page_number = request.GET.get('page') posts = paginator.get_page(page_number) return render(request, 'main/home.html', {'q': q, 'posts': posts}) if q = car, red I get a post with tags car, red. It's good. But when q = red, car I get a post with the tags car, red and post with the tags airplane, red, instead of a post with the tags car, red. It is not right. I am trying to do an exact search. Could you share your experience and tell me what … -
Django model not loading(opening) in django-admin asgi app, Django 3.0.3
I am using the asgi application, means i have switch code from wsgi to asgi, Problem occured was when I visited to see model status if entry added or not my subscription app not loaded. This is my asgi.py file import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "helios.settings") django.setup() application = get_default_application() This is django-admin home page ========================================================================================= When I clicked on subscription model I get Programming error, rest all models I can view Environment: Request Method: GET Request URL: http://localhost:8000/admin/subscriptions/subscription/ Django Version: 3.0.3 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'django_extensions', 'django_crontab', 'crispy_forms', 'catalog', 'users', 'blog', 'products', 'subscriptions', 'webpush', 'channels', 'worker'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception (column subscriptions_subscription.payment_id does not exist LINE 1: ... "subscriptions_subscription"."subscription_end", "subscript... ^ HINT: Perhaps you meant to reference the column "subscriptions_subscription.payment_id_id". ) was the direct cause of the following exception: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, … -
websocket routing is not working by using nginx, docker, django-channel
now i am using Django 2.2 for my project and i also use Django-channel. This project is containerized by docker and use nginx as web server. The current problem i encountered is that the websocket is not working for Django-channel which the error is : reconnecting-websocket.js:209 WebSocket connection to 'ws://0.0.0.0/private/message/notifications/' failed: Error during WebSocket handshake: Unexpected response code: 404 i googled how to solve this problem for long time and i know the problem is because running daphne behind nginx always routes to http instead of websocket, so i tried hard to solve this problem but still no result for me. I won't get this problem by running python manage.py 0.0.0.0:8000, it only happen when i am using nginx, so i think my nginx config got problem, but i dont know which part is wrong. The project architecture is : --- database | User ---> nginx ---> app --- | --- redis where nginx, app, database, redis are containerized by docker. and redis is for django-channel. the following is my docker-compose file: version: '3' services: app: build: # current directory # if for dev, need to have Dockerfile.dev in folder dockerfile: docker/prod/Dockerfile context: . ports: #host to image - "8000:8000" … -
Django receives "FATAL: password authentication failed for user" even though user crendntical are correct
Some background: I'm trying to install the arches project on Windows. After some problems, I've seen it is recommended to run it on Linux, so now I'm running on Ubuntu terminal for Windows. As for the error: The first step is to run the python manage.py setup_db command. It fails with: FATAL: password authentication failed for user "kali" Error connecting to db with these settings: dbname=jerarch user=kali host=localhost port=5432 Have you created the database yet? The quickest way to do so is to supply Postgres superuser credentials in the PG_SUPERUSER and PG_SUPERUSER_PW settings, and then re-run this same command. Also: User "kali" exists, and I've set its password using ALTER USER kali WITH PASSWORD 'xxxxxxxx'; psql -U kali -d jerarch works fine, and only with the password I set before (meaning the ALTER USER worked). PG_SUPERUSER and PG_SUPERUSER_PW are defined as needed. I really don't know what else to do. Thanks -
Jquery code won't modify attributes of html tag
Can someone please tell me why the next jquery code is not working. I already tried it outside the $(document).ready block and that also don't work note: the weird "{{ }}" and "{% %}", is typically django Jquery $(document).ready(function () { $(".post_thumb_up").hover(function () { $(".post_thumb_up").attr("src", "/post_it/static/media/thumb_up_hover.png"); }); $(".post_thumb_up").click(function () { $(".post_thumb_up").attr("src", "/post_it/static/media/thumb_up.png"); }); }); html: <div class="post"> <h3>{{ post.title }}</h3> <img class="post_image" src="{% static post.image_path %}"> <p><i>Door: {{ post.author }}<br>Datum: {{ post.date_posted|date:"l d F, Y, H:i" }}</i></p> <div class="post_line"></div> <div class="post_actions"> <input id="test" type="image" class="post_thumb_up" src="{% static "media/thumb_up.png" %}"> <input type="image" class="post_thumb_down" src="{% static "media/thumb_down.png" %}"> </div> </div> Thanks -
Access page number in Django template
In the change_list_results.html I want to access the current page number in case of pagination is required. How do I achieve this? -
How to make a registration page with extra fields and just one password input in django
I want create custom reg form with fullname is an extra field. The rest fields are set to blank so user can fill it later. and i want user to input just one password. please help been stuck here for a week now. models.py:- from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=30,blank=False,null=False) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10,blank=True) def __str__(self): return self.fullname @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views:- def register(request): if request.method =='POST': form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): variable=form.save(commit=False) variable.set_password(variable.password) variable.save() profile=profile_form.save(commit=False) profile.user =variable profile.save() username = form.cleaned_data.get('username') messages.success(request,f'account created for { username }') return redirect('login') else: form = UserForm() profile_form = ProfileForm() context={'form':form , 'profile_form':profile_form} return render(request, 'users/register.html',context) forms:- class UserForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'})) password= forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'})) email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'})) password2 = None class Meta: model=User fields=['username','password','email'] class ProfileForm(forms.ModelForm): fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'})) class Meta: model=Profile fields=['fullname'] I am using mysql ans a db -
Django Transforming to Raw Query
I am working on a django project and I must not use django's get method for getting data from datbase. I could not understand how can I make this query in sqlite. obj = get_object_or_404(MyModel, pk=1) In general where can I learn this queries SQL equivalents? -
Flutter Frontend and Django API for Backend
Good Day, I develop Django Applications, now, I want to make android application as well. Is it possible to create front-end using Only Flutter and use Django REST API for my logic and processing. I have zero experience in android development, Flutter will be my first entry point. Thank you! -
Load data from CSV to Database tables in Django
I was able to load country and state successfully, but I get error when the city is being loaded Something went wrong saving this city: 0000000698 The QuerySet value for an exact lookup must be limited to one result using slicing. This is my 3 models "country", "state" and "city" class Country(BaseModel): id = models.CharField( primary_key=True, max_length=3, unique=True ) class Meta: db_table = 'country' class State(models.Model): id = models.CharField( primary_key=True, max_length=3, unique=True ) country = models.ForeignKey( Country, on_delete=models.CASCADE, blank=True, null=True ) state_code = models.CharField( max_length=4, null=True, blank=True, unique=True ) capital_city = models.CharField( max_length=10, null=True, blank=True, ) class Meta: db_table = 'state' class City(models.Model): id = models.CharField( primary_key=True, max_length=10, unique=True ) country = models.ForeignKey( Country, on_delete=models.CASCADE, blank=True, null=True ) state = models.ForeignKey( State, on_delete=models.CASCADE, blank=True, null=True ) class Meta: db_table = 'city' This is sample CSV files I want to upload country.csv 10,Antarctica,Antarktika 16,American Samoa,Amerikanisch-Samoa 60,Bermuda,Bermuda 74,Bouvet Island,Bouvetinsel state.csv 1,276,BW,0000000111,Baden-Württemberg,Baden-Württemberg 2,276,BY,0000000165,Bavaria,Bayern 3,276,BE,0000000028,Berlin,Berlin 4,276,BB,0000000019,Brandenburg,Brandenburg 5,276,HB,0000000195,Bremen,Bremen 6,276,HH,0000000255,Hamburg,Hamburg city.csv 0000000001,276,BB,Bernau bei Berlin,Bernau bei Berlin 0000000002,276,BB,Blankenfelde-Mahlow,Blankenfelde-Mahlow 0000000003,276,BB,Brandenburg an der Havel,Brandenburg an der Havel 0000000004,276,BB,Cottbus,Cottbus 0000000005,276,BB,Eberswalde,Eberswalde 0000000029,276,BW,Aalen (Württemberg),Aalen (Württemberg) 0000000030,276,BW,Achern (Baden),Achern (Baden) 0000000031,276,BW,Albstadt (Württemberg),Albstadt (Württemberg) 0000000032,276,BW,Backnang,Backnang 0000000209,276,HE,Dillenburg,Dillenburg 0000000210,276,HE,Dreieich,Dreieich 0000000211,276,HE,Eschborn (Taunus),Eschborn (Taunus) 0000000212,276,HE,Flörsheim am Main,Flörsheim am Main Here is my view/logic for importing "city.csv" def import_city_from_file(self): data_folder … -
PyCharm run configuration for Django management command
From the terminal, I can run a Python script from the Django shell like so: python manage.py shell < myscript.py How can I create this as a Run configuration in PyCharm. Per this SO answer, I've added a new Django server configuration, checked custom run command and set it to shell. Applying and running this shoots me into the Django shell so I know I'm on the right track. The tricky part has been trying to figure out how to pipe the file into this command. Am I doing something wrong or is this not possible? -
Putting django passed variables {{}} inside {% url %}
I am trying to do this <form action="{% url 'add_participant' id={{event.id}} %}" method="POST"> But it seems that django doesn't like having a {{}} variable inside {%%}, how do I work around this? -
TypeError: object of type 'JsonResponse' has no len() when return the json values
TypeError: object of type 'JsonResponse' has no len() when return the json values.But print dicts and print json.dumps(dicts),it shows the values ,but when the return the JsonResponse(json.dumps(dicts), safe=False) shows an error like 'TypeError: object of type 'JsonResponse' has no len()',how to solve this problem. Views.py class UserNewsListingListViewSet(MobileNewsListViewSet): def get_queryset(self): queryset = self.queryset.filter(publish=True) queryset = queryset.exclude(news_summary='') # Filter News Provider if self.request.GET.get('user_id'): queryset = queryset.filter(posted_by__id=self.request.GET.get('user_id')) # Filter News Category if self.request.GET.get('news_type'): queryset = queryset.filter(news_category__slug=self.request.GET.get('news_type')) dicts = [] for query in queryset[:6]: id = query.id newstitle = query.news_title news_summary = query.news_summary slug = query.slug news_image = query.news_image news_provider = query.news_provider news_page_url = query.news_page_url newsdate = query.news_datetime likescount = query.likes_count mobile_news_summary = query.mobile_news_summary for cat in query.news_category.all(): news_category = cat.news_category Data = { "id":id, "newstitle":newstitle, "news_categories":news_category, "news_summary":news_summary, "slug":slug, "news_image":news_image, "news_provider":{ "id":query.news_provider.id, "news_providers": query.news_provider.news_provider, "url":query.news_provider.url, "region":query.news_provider.region, "image":str(query.news_provider.image), "descriptions":query.news_provider.description, "followers":query.news_provider.followers, "slug":query.news_provider.slug, "created_time":query.news_provider.created_time, "publish":query.news_provider.publish }, "news_page_url":news_page_url, "newsdate":newsdate, "likescount":likescount, "mobile_news_summary":mobile_news_summary } # dat=json.dumps(data) dicts.append(data) return JsonResponse(json.dumps(dicts), safe=False) -
adding javascript in html forms [duplicate]
<!DOCTYPE html> <html> <head></head> <body> <form method="POST"> <p>Click the button to create a DIV element with some text, and append it to DIV.</p> <div id="myDIV"> MATHS PAPER </div> <button onclick="myFunction()">Add Question</button> <script> function myFunction() { var para = document.createElement("DIV"); para.innerHTML = "<div style='background-color:lightgreen'>QUESTION<div><input type='text' id='q1' placeholder='enter question'></div><div></input><input type='text' placeholder='enter option1 here'></input></div><div></input><input type='text' placeholder='enter option2 here'></input></div></div>"; document.getElementById("myDIV").appendChild(para); } </script> </form> </body> </html> How to make this code work? I observed on removing form tag, it is working. But I want it to be in form tag, so that I can post those questions and options, and save it in a database. -
request.GET in Django for Search is not working when entering only one search parameters
This is my Search function: When I use this than I cannot search by only placing for example: Keywords only or City only or any other parameters that I have used here. It comes with no Listing Available. But if I remove any search parameters any only work with one parameters like: if I remove all others except #Keywords than my search works out. # search function using request.GET def search(request): # for making search option dynamic as per search of user queryset_list = Listing.objects.order_by('-list_date') #Keywords if 'keywords' in request.GET: keywords = request.GET['keywords'] if 'keywords': queryset_list = queryset_list.filter(description__icontains=keywords) #City if 'city' in request.GET: city = request.GET['city'] if 'city': queryset_list = queryset_list.filter(city__iexact=city) # Bedrooms if 'bedrooms' in request.GET: bedrooms = request.GET['bedrooms'] if 'bedrooms': queryset_list = queryset_list.filter(bedrooms__lte=bedrooms) # Price if 'price' in request.GET: price = request.GET['price'] if 'price': queryset_list = queryset_list.filter(price__lte=price) context = { 'state_choices': state_choices, 'bedroom_choices': bedroom_choices, 'price_choices': price_choices, 'listings': queryset_list, 'values': request.GET } return render(request, 'listings/search.html', context) Here is my Template file..... for the Search.. {%extends 'base.html'%} <!---Import Humanaize----> {%load humanize %} {% block title %} | Search Results {%endblock%} <!---- Start Block Content--> {%block content%} <section id="showcase-inner" class="showcase-search text-white py-5"> <div class="container"> <div class="row text-center"> <div class="col-md-12"> <form action="{%url … -
How to auto-generate value from another entity on the same table. (python, django)
I have a table that has name and amount entity, and I want to happen is: this is the sample of my table on models.py: class Test(models.Model): test_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) amount = models.IntegerField() timestamp = models.DateTimeField() if entered amount is 300, the name will be 'hello', else if the entered amount is 500, the name will be 'world'. please help, been trying to figure this out since yesterday, I'm really newbie on python and django. -
Passing Request to method within Haystack Index class in Django
I am trying to use the user's location information to filter a haystack elasticsearch query. The goal is to only show search results of stores near the user. The problem is I don't know how to pass request into the haystack index, in order to run my function get_or_set_location(request). Is this possible? class StoreIndex(request, indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='/app/templates/search/item_text.txt') # /templates/search/item_text.txt business_name = indexes.EdgeNgramField(model_attr='business_name') description = indexes.EdgeNgramField(model_attr="description", null=True) category = indexes.CharField(model_attr='category') city = indexes.CharField(model_attr='city') updated_at = indexes.DateTimeField(model_attr='updated_at') # for auto complete content_auto = indexes.EdgeNgramField(model_attr='business_name') # Spelling suggestions suggestions = indexes.FacetCharField() def get_model(self): return Store #This is where I need to obtain call request for the users location information. def index_queryset(self, using=None): city_state = get_or_set_location(request) user_location = city_state["user_location"] return self.get_model().objects.annotate(distance = Distance("location", user_location)).order_by("distance").filter(status=2)[0:8] -
How to make a django rest api run a python file in my computer
I am making an API for an android app. As soon as the input is given to the API, I need the API to execute a python file for me which is in my computer. I'm thinking of using my computer as a server on trial basis. I hope you are able to understand my question. Please let me know on how to run a python file from the API -
How to properly register genericAPI view in Django and solve 405 error
I have a view looking like below class UserFpProfileView(generics.GenericAPIView, mixins.CreateModelMixin, mixins.RetrieveModelMixin): serializer_class = UserFpProfileSerializer permission_classes = (permissions.AllowAny,) # authentication_classes = (authentication.TokenAuthentication,) def create(self, request, *args, **kwargs): serializer = self.get_serializer( **request.data ) serializer.is_valid(raise_exception=True) serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) def get_object(self): # Raise error if user type is not fp if self.request.user.type != 'fp': raise exceptions.PermissionDenied(detail='FP 계정만 접근할 수 있습니다.') queryset = self.queryset queryset.filter(user=self.request.user) return queryset and route looking like below path('me/fp-profile/', views.UserFpProfileView.as_view(), name='fp-profile'), When I post or get to 'me/fp-profile' URL I get 405 method not allowed error. What am I doing wrong? -
Python Django Page 404 Error on my first app
I am following this tutorial. https://www.youtube.com/watch?v=a48xeeo5Vnk Here is my code for views: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse('<h1>This is our blog</h1>') def about(request): return HttpResponse('<h1>This is our About Page</h1>') def next(request): return HttpResponse('<h1>This is our next Page</h1>') This is my App urls page code from django.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('about/', views.about, name='blog-about'), path('next/', views.next, name='blog-NEXT'), ] This is my main project URL code from django.contrib import admin from django.urls import path, include urlpatterns = [ path('firstapp', include('firstapp.urls')), path('admin/', admin.site.urls), ] Now when I try this with only single view i.e default page '', it works alone, with no more pages mentioned in code, however when I add more views it gives me a 404 page error. I believe the code is fine and it shoud work, but somehow it chose not to. Tried different browser, tried forums but nothing. Here is the error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/firstapp/ Using the URLconf defined in first.urls, Django tried these URL patterns, in this order: firstapp [name='blog-home'] firstapp about/ [name='blog-about'] firstapp next/ [name='blog-NEXT'] admin/ The current path, firstapp/, … -
I get this error when running migrate command. invalid literal for int() with base 10: 'portraiture'. Below is my code. Django version=1.11
class Category(models.Model): TRAVEL = 'TR' WEDDING = 'WE' PORTRAITURE = 'PR' CATEGORIES = ( ('TRAVEL', 'travel'), ('WEDDING', 'wedding'), ('PORTRAITURE', 'portraiture'), ) category = models.CharField( max_length=32, choices=CATEGORIES, default='PORTRAITURE', ) class Image(models.Model): image = models.ImageField((""), upload_to='images/', height_field=None, width_field=None, max_length=None, blank=True) image_name = models.CharField(max_length=60) image_description = models.TextField() location = models.ForeignKey(Location, null=True) category = models.ForeignKey(Category, default='PORTRAITURE') pub_date = models.DateTimeField(default=datetime.now, blank=True) tags = models.ManyToManyField(tags) -
os.path.expanduser("~") + "/Downloads/" not working
In my django app i have specified download location as Path = os.path.expanduser("~") + "/Downloads/" and it is running in apache2 mod_wsgi server..When i try to download it downloads content inside /var/www/Downloadsinside a server folder but not users Download directory?What is wrong with my download path? -
Cannot post data to mysql from template of django using vue
When i post data, i got the bellow message. CSRF Failed: CSRF token missing or incorrect. However, i am adding CSRF to header of axios like bellow. postArticle: function() { this.loading = true; csrftoken = Cookies.get('csrftoken'); headers = {'X-CSRF-Token': csrftoken}; axios.post('/api/articles/',this.newArticle, {headers: headers}) .then((response) => { this.loading = false; console.log(this.articles) console.log("success") this.getArticles(); }) .catch((err) => { this.loading = false; console.log("failed") console.log(err); }) }, i am including csrf like bellow. <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> On the other hand, I have tried other way like bellow. In html <meta name="csrf-token" content="{{ csrf_token }}"> postArticle: function() { this.loading = true; axios.defaults.headers.common= { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content') }; axios.post('/api/articles/',this.newArticle) .then((response) => { this.loading = false; console.log(this.articles) console.log("success") this.getArticles(); }) .catch((err) => { this.loading = false; console.log("failed") console.log(err); }) }, However, i cannot as well. What is the problem?