Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
in pyecharts, how to bring line to front of bar when using bar.overlap(line)?
unfortunatly there is no tag for pyecharts in stackoverflow site , I'm not sure if I will get a helpful answer , hopefully I will get I have the following chart that consists of two bars and one line, I need 2 things : I need to bring the line to front of bar , its under the bar by default I need to shorten the value number to the nearest thousand (e.g 80,000 = 80K) code :- from pyecharts.charts import Bar, Gauge, Line from pyecharts import options as opts from pyecharts.globals import ThemeType bar = ( Bar(init_opts=opts.InitOpts(width='100%', theme=ThemeType.VINTAGE)) .add_xaxis(["Category-1" , "Category-2", "Category-3", "Category-4", "Category-5"]) .add_yaxis('No. Of Investments', [100,700,900,500,400,50], label_opts=opts.LabelOpts(is_show=False),) .add_yaxis('No. Of Investors', [24,65,30,41,88], label_opts=opts.LabelOpts(is_show=False),) .extend_axis( yaxis=opts.AxisOpts( name="Value", type_="value", name_textstyle_opts=opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') ) ) .set_global_opts(legend_opts=opts.LegendOpts(is_show=True , pos_right = 0, textstyle_opts = opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') ), yaxis_opts=opts.AxisOpts( name='Count', name_location='middle', name_gap=50, type_="value", axistick_opts=opts.AxisTickOpts(is_show=True), splitline_opts=opts.SplitLineOpts(is_show=True), axispointer_opts=opts.AxisPointerOpts(is_show=False), name_textstyle_opts=opts.TextStyleOpts( font_size=14, font_weight='bold', font_family='Dubai') ), xaxis_opts=opts.AxisOpts( type_="category", axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"), name_textstyle_opts=opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') , axislabel_opts = opts.LabelOpts(font_family='Dubai' , rotate = 30, font_size= 11, ) ), tooltip_opts=opts.TooltipOpts( is_show=True, trigger="axis", textstyle_opts = opts.TextStyleOpts( font_family='Dubai') ) , toolbox_opts = opts.ToolboxOpts(is_show=True , pos_left= '5%', feature=opts.ToolBoxFeatureOpts( data_zoom = opts.ToolBoxFeatureDataZoomOpts(is_show=False) , data_view = opts.ToolBoxFeatureDataViewOpts(is_show=False) , brush=None ) ) ) ) line = ( Line() … -
Django - How to iterate queryset object in template
I am trying to developed quiz app in django class base view. here i am get all question in questions and render to template. i want access one by one questions using html next button. so suggest me any backend code required or by using javascript we can iterate? View.py -
The function get_form_kwargs doesn't work, it doesn't return anything
I have a CreateView and i want to save as a kwarg the user, and i don't understand what is wrong with my code. I wrote my get_form_kwargs in my create view(this is from my view.py): class ItemCreateView(CreateView): template_name = 'menus/form.html' form_class = ItemForm def form_valid(self, form): instance = form.save(commit=False) instance.user = self.request.user return super(ItemCreateView, self).form_valid(form) def get_form_kwargs(self): kwargs=super(ItemCreateView, self).get_form_kwargs() kwargs['user']=self.request.user return kwargs def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) context = { 'form' : form, 'var' : 'Add an Item' } return render(request, self.template_name, context) I introduced the init function in my form(this is my form.py): class ItemForm(forms.ModelForm): class Meta: model = Item fields = [ 'name', 'article', 'description', 'exceptions', 'bl', ] def __init__(self,*args, **kwargs): print(kwargs.pop('user', None)) super(ItemForm, self).__init__(*args, **kwargs) The problem is that the print from the init function returned None value. It should returned the user. I'm mentioning that I am logged in. I don't understand what is wrong here. Thanks in advance for your help !!! -
Django- get "parameters" from HTML form in views
I have a template which has this form: template.html <form action="{% url addcart %}" method="POST" class="btn-block"> {% csrf_token %} <input type="number" name="quantity" min="1" max="100"> <input type="submit" class="float-right btn btn-success form-control" value="Add To Cart"> </form> Now, I want to know how to implement the function "addcart()" in the views. How can I get the form variables? -
What is the best paradigm for django rest framework unit testing?
I have a Django project (drf) and I want to implement some unit tests for it. I found some different scenarios in implementations. Some of them define a class for each django model containing different methods for CRUD APIs: class FooTestCase(TestCase): def setup(self): pass def test_foo_create(self): pass def test_foo_update(self): pass . . . . Some others define a class for each API view: class FooListCreateTestCase(TestCase): def setup(self): pass def test_foo_create(self): pass class FooRetriveUpdateDeleteTestCase(TestCase): def setup(self): pass def test_foo_update(self): pass and so on ... what is the best paradigm among them? -
js function is not defined in django template
I have just started learning Django and I tried to add simple js static file to my Django template. However I am not able to execute function in Django template due to Uncaught ReferenceError: myFunction is not definedat HTMLButtonElement.onclick. My function is very simple and it is within static folder at the project level static/js/script.js function myFunction() { alert("This is result of JS function!"); } At the project level I have the base.html within templates/base.html. Here it is: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% endblock %}</title> <script type="text/javascript" scr="{% static 'js/script.js' %}"></script> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> </head> <body> <div class="nav-bar"> <a href="{% url 'myapp:home' %}">Home</a> | <a href="{% url 'myapp:about' %}">About Us</a> | <a href="{% url 'myapp:services' %}">Our Sevices</a> | <a href="{% url 'myapp:info' %}">Info</a> | </div> <div class="page-content"> {% block content %} {% endblock %} </div> <div class="page-footer"> <a href="#" >Usefull links</a> | <a href="#" >Follow Us</a> | <a href="#" >Address</a> | <p id="copyright">&copy; 2022 Learning Django</p> </div> </body> </html> At the app level I have folder templates and inside several html files like myapp/templates/myapp/services.html. {% extends … -
Why do I get TypeError when running my Django project with Debug off?
So I've been running my Django project with Debug on, I know it's wrong, and now trying to make the change. But then, the project returned TypeError when I turned the Debug off: TypeError: expected str, bytes or os.PathLike object, not NoneType I tried digging into the issue a little more, and found out that the variable absolute_path of admin/js/jquery.js was None, as you can see in the Traceback below. I've got three clues regarding this issue: It happens in the django-cloudinary-storage library. It probably happened after running python manage.py collectstatic. I did not run this command up until now.. The project ran perfectly with Debug = True. It only happened with Debug=False. What do you think is the problem? Below is a part of my settings.py and full Traceback. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] Full Traceback: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 31, in get_handler handler … -
Django how to get object in one query to database
models.py class Post(models.Model): pass @property def views_count(self): return PostViews.objects.filter(post=self).count() class PostViews(models.Model): IPAddres= models.GenericIPAddressField(default="") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_views_count",) date = models.DateTimeField(auto_now_add=True) views.py def get_posts(request, topic=""): posts = Post.objects.filter(status=Post.OPEN).select_related('author').prefetch_related('tags').select_related('category').select_related('post_views_count') posts.hml {% for post in posts %} {{ post.views_count }} {% endfor %} Due to the call of views, the number of sql queries grows by 10 hits.How do I get this data in place with the data received by the model Post? -
Unable to POST with ListCreateAPIView
Thank you very much for all your help. We are currently using Django to create a blog with membership features. I would like to allow only members to post articles, but I can't use POST while logged in. When not logged in, POST is available. What is wrong? models.py class Post(models.Model): title = models.CharField(max_length=100, blank=True, default='') content = models.TextField(blank=True, default='') def __str__(self): return self.title class Category(models.Model): name = models.CharField(max_length=100, blank=False, null=True, default='') posts = models.ManyToManyField(Post, related_name='categories', blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'title','content', 'categories'] class CategorySerializer(serializers.ModelSerializer): name = serializers.CharField(required=False, allow_null=True, allow_blank=True) posts = PostSerializer(many=True, read_only=True) new_posts = serializers.PrimaryKeyRelatedField( queryset=Post.objects.all(), many=True, write_only=True, required=False) class Meta: model = Category fields = ['id', 'name', 'posts', 'new_posts'] def create(self, validated_data): category = Category.objects.create() category.name = validated_data.pop('name', None) new_posts = validated_data.pop('new_posts', None) category.posts.set(new_posts) category.save() return category def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.posts.set(validated_data.get('new_posts', instance.posts)) instance.save() return instance views.py class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = (IsAdmin,) # permission_classes = (AllowAny,) permissions.py class IsAdmin(permissions.IsAdminUser): def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: role_slug = None if not request.user.is_anonymous and request.user.role is not None: role_slug = request.user.role … -
How does distinct parameter work with the Count method in annotate?
I got a problem with annotate method when I was using the Count method to count multiple columns that come from the database which have a relationship with one of the tables. let me give you a quick example: match_session_instance = MatchSessionInstance.objects.filter(match_session=match_session, status="main") match_instances = MatchSessionInstance.objects.filter(match_session=match_session) action_counts = match_instances.values(player_number=F("player_pk__number"), player_name=F("player_pk__player"))\ .annotate(pass_count=Count("live_match_pass__id", distinct=True), corner_count=Count("live_match_corner__id", distinct=True)) in the meantime I'm not facing any problems I caught my issue and I addressed it but that is the problem now. I don't know How could "disticnt=True" parameter helps me to fix that problem! I googled a bit and found this source that has helped me: Count on multiple fields in Django querysets I know what does distinct as a method in ORM but actually, I get no idea how it works in that format special when I used columns that never have duplicated data. Can anyone help me to understand, please? thanks in advance -
Change reason field (django-simple-history) populated in django admin panel
I use django-simple-history in the project. The documentation https://django-simple-history.readthedocs.io/en/2.7.0/historical_model.html is clear as to how to pass changeReason value while updating the object. I wonder if it is possible to populate history_change_field in django admin panel when making changes? -
Appending all for loop dicts into single list
I just learnt django and I am getting data from api and looping through the json and appending the data into the list. but When I use .map() function in react then the data is appending in list (from for loop) like [ { "results": { "id": 544, "name": "User_1", } }, { "results": { "id": 218, "name": "User_2", } }, { "results": { "id": 8948, "name": "User_3", } }, { "results": { "id": 9, "name": "User_4", } }, ] It is not appending like (Like I want) [ results : [ { "id": 544, "name": "User_1" }, { "id": 218, "name": "User_2" }, { "id": 8948, "name": "User_3" }, { "id": 9, "name": "User_4" } ] ] views.py def extract_view(request): results_list = [] // api url for explanation only get_response = "https://api.punkapi.com/v2/beers" if get_response.status_code == 200: for result in get_response.json(): results_list.append({"results": result}) return Response({"data": results_list}) I know, In for loop it is appending every result within it with every iteration but I also want to assign all the responses within results list. I have tried many times but it is still not working. -
Customizing calendar.HTMLCalendar in a Django Project
I am using HTMLCalendar to add a calendar to my project. The calendar is showing perfectly fine but I want to add some customization to it. As a simple example I want to add a legend after the month and I want to add a condition so that if an event is on a specific date to have a button around the number of the month. I have found some very old answers but I am not sure how to actually implement. Similar answers:python calendar.HTMLCalendar Here is the current view: class home(ListView): model = Workout template_name = 'app/home.html' context_object_name = 'workouts' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) year= datetime.now().year month=datetime.now().month cal=HTMLCalendar().formatmonth(year,month) context['cal']=cal print(cal) return context here is the current outcome: Here is the template I am sure there is an easier way that I did not yet find to add padding: <center>{{ cal|safe }}</center> <style> .month{ text-align: center; } .mon{ padding-left:15px; } .tue{ padding-left:15px; } .wed{ padding-left:15px; } .thu{ padding-left:15px; } .fri{ padding-left:15px; } .sat{ padding-left:15px; } .sun{ padding-left:15px; } </style> </div> This is the required outcome or similar to it: My question: How can I customize the HTMLCalendar so that I can reach the image showing and where should … -
TypeError: connect() argument 4 must be str, not WindowsPath
When I run this python manage.py migrate return Connection(*args, **kwargs) File "C:\Users\WyndhamKeitA\AppData\Roaming\Python\Python310\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) **TypeError: connect() argument 4 must be str, not WindowsPath** my DB under settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': BASE_DIR / 'db.crudpy', 'USERNAME': 'root', 'PASSWORD': '1234', 'PORT': '3306', 'HOST': 'localhost' } } How do I get rid of the error? crudpy is the schema I've created on mysql -
Best way to set up Django model for a balance sheet app
I want to create simple app where a user can keep track of their net worth over time. For example, the user could go in at the end of each month and input their balances for all of their assets and liabilities. The app would keep track of the data over time so it could be displayed as a graph. I'm trying to figure out how to set up my models for this. I think I need to have the balances as a separate class otherwise every time you wanted to add a new date you would have to update the model itself. Here's what I came up with. I'm interested if this is a good way to do this or if there is a cleaner way. class Asset(models.Model): name = models.CharField(max_length=30) description = models.TextField() class Liability(models.Model): name = models.CharField(max_length=30) description = models.TextField() linked_account = models.ForeignKey(Asset,null=True,blank=True) class Meta: verbose_name_plural = "Liabilities" class AssetBalance(models.Model): account = models.ForeignKey(Asset) date = models.DateField() balance = models.FloatField() class LiabilityBalance(models.Model): account = models.ForeignKey(Liability) date = models.DateField() balance = models.FloatField() -
How to use Postman to authenticate Google Login with dj_rest_auth
So I am following the official documentation for Google sign in with DjangoRestFramework using DJ Rest Auth (this link) I intend to authenticate with Postman Oauth2 (by following the guide and generating an Access Token) Postman is generating an access token successfully, but I cannot seem to use this authentication in my API calls. Please who knows which step I am missing - I want to handle everything in Postman. urls.py urlpatterns = [ path('', Home.as_view(), name='home'), path('admin/', admin.site.urls), path('accounts/', include(api_urls, namespace='api')), path('accounts/login/', GoogleLogin.as_view(), name='google_login'), path('accounts/', include('rest_framework.urls')), ] views.py class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = 'http://localhost:8080/accounts/google/login/callback/' client_class = OAuth2Client On calling an API endpoint, I get an invalid token error: If I however visit the Google Login view in my RestFramework UI (in my case http://localhost:8080/accounts/login), I get an endpoint to make a POST, and on making a POST request, a key is generated. Only this key (if used as a Bearer token) works in my API calls. How can I authenticate on Google, and make my API calls independent of the DRF UI? Callback URL has been configured on my Google Developer Client. PS: I feel the answer is in step 6 of the documentation, but I am … -
How to prevent methods of being imported in an outside package at pycharm?
I would like to prevent imports of private methods outside a specific interface in a big commercial project to improve architecture. I've tried with init.py but maintenance is hard and I had problems with circular imports over time. I've also tried with _method() underline to make private methods, but then I could not use these methods inside my own interface. What I would like to set up or within my pycharm configs or by making a customized use of import machinery from python is something like these: -- interface_foo ---- method_foo.py # here I create a public and a private method ---- method_bar.py # here I can import both methods with no issues, cause it is inside inferface ---- api.py # here i display the public methods for other interfaces to use them --interface_baz ----method_baz.py # here I can import ONLY public method By trying to import private methods from interface_foo inside interface_baz should raise an error (like ImportError) -
djando rest framework AssertionError
mi pregunta es porque me arroja este error estoy tratando de actualizar y me dice que estoy recibiendo un un AssertionError class none type mi problema siempre se ha dado con la imagen al enviarla me da siempre problemas asi estuve con mi metodo post hasta que en el serializer lo convert a url mi view.py class PokemonsViewSets(APIView): parser_classes = (MultiPartParser, FormParser, JSONParser,FileUploadParser) def get(self, request,pk=0,format= None, *args, **kwargs): if (pk>0): pokemon = list(PokemonsBBDD.objects.filter(id=pk).values()) if len(pokemon)>0: pokemons = pokemon[0] datos ={'message':"Succes","pokemones": pokemons} else: datos = {"message":"list pokemons not found"} return Response(datos,status=status.HTTP_200_OK) else: queryset = PokemonsBBDD.objects.all() # pokemonId = PokemonsBBDD.objects.get() serializer = ProjectSerializer(queryset, many=True) if len(queryset)>0: datos = {'message':"Succes","pokemones":serializer.data} else: datos = {"message":"list pokemons not found"} return Response(datos,status=status.HTTP_200_OK) def post(self, request, format= None): serialize = ProjectSerializer(data=request.data) if serialize.is_valid(): serialize.save() return Response(serialize.data, status=status.HTTP_201_CREATED) return Response(serialize.errors,status=status.HTTP_400_BAD_REQUEST) def put(self,request,pk,*args,**kwargs): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: serialize = updateSerializer(pokemon, data = request.data) if serialize.is_valid(): return Response(serialize.data) else: print(serialize.error_messages) return Response(serialize.errors) @action(detail=True) def patch(self,request,pk,format= None,*args,**kwargs): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: serialize = updateSerializer(pokemon,data= request.data) if serialize.is_valid(): serialize.save() return Response({'succes':'exitosa'}) else: print(serialize.error_messages) return Response({'error','bad reques'}) def delete(self,request,pk=0,format= None,*args,**kwargsl): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: pokemon.delete() return Response({'message':'dato ELiminado'},status=status.HTTP_200_OK) else: return Response({'messageToFailed':'no se encontro … -
Is it possible to upload an app to a vps server with back in django and front in react.js?
I developed a website that uses react.js and django, and my question is if it is possible to upload it to a vps server. -
REST related/nested objects URL standard
if /wallet returns a list a wallets and each wallet has a list of transactions. What is the standard OpenAPI/REST standard? For example, http://localhost:8000/api/wallets/ gives me { "count": 1, "next": null, "previous": null, "results": [ { "user": 1, "address": "3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd", "balance": "2627199.00000000" } ] } http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/ gives me { "user": 1, "address": "3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd", "balance": "2627199.00000000" } If I wanted to add a transactions list, what is the standard way to form this? http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/transactions ? http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/transactions?offset=100 for pagination -
Set and not let modify foreign key value (user)
I have 2 models that I want to preset the value and ideally have it hidden from the Django admin when creating new record, this way the user don't amend this value. This are the created and modified by that are foreign keys to users. I found this link https://pypi.org/project/django-currentuser/, that i thought it might do the job, however it reverted my django from the latest version to version 3, so I dont want to use it, and also, it doesnt work if i set either created or last modified but not both, if i set it in the 2 models i get 4 errors. I am wondering if there is an easy way to set this default value? from django.db import models from email.policy import default from django.contrib.auth.models import User from django.utils import timezone # from django.contrib import admin # https://pypi.org/project/django-currentuser/ from django_currentuser.middleware import (get_current_user, get_current_authenticated_user) from django_currentuser.db.models import CurrentUserField class Company(models.Model): modified_by = models.ForeignKey(User, related_name='company_modified_by', unique = False, on_delete=models.CASCADE) created_by = CurrentUserField() created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=150, unique = True) class Meta: verbose_name = "Company" verbose_name_plural = "Companies" def __str__(self): return self.name class UserProfile(models.Model): modified_by = models.ForeignKey(User, related_name='user_profile_modified_by', unique = False, on_delete=models.CASCADE)#CurrentUserField(on_update=True) created_by = … -
Deleted the migrations folder accidently so I dropped all my tables in database but still not working
I deleted my migrations folder accidently so to make things work again I dropped all tables in my database as well. But now even tho python manage.py makemigrations is working, python manage.py migrate still says 'No migrations to apply' why? -
Django Rest / React NextJS - pass username in html form back to DB in a post request
How can you pass username in html form back to Django DB, when making a post request? I get the following error when I submit the form null value in column "owner_id" of relation "contracts_contract" How can I adjust it, so that post request is saved and owner (username) is correctly captured in post request in django db nextjs file: const PostRequest = () => { const [name, setName] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); let body = { owner_id: 1, name: name, } axios.post("http://127.0.0.1:8000/contract/contract-create/", body).then(response => { console.log(response) }) }; return ( <form className='form' onSubmit={handleSubmit}> <input type='text' className='form-input' id='name' value={name} onChange={(e) => setName(e.target.value)} /> <button type='submit'> submit </button> </form> ); }; #Models.py class Contract(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) name = models.CharField(max_length=30) #serializers.py class ContractSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Contract fields = '__all__' @api_view(['POST']) def contractCreate(request): serializer = ContractSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: print("data is invalid") return Response(serializer.data) -
I coud not run server
I'm learning django,but i stuck in something, i cant run server(manage.py) from django.urls import path from . import views urlpattern = [ path('hello/',views.say_hello) ] in my django project folder is a urls.py but i created another one for somthing else; this is main urls.py : """storefront URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')) ] -
django, X-CSRFToken is set incorrectly in request header
basically, i got this to actually send a csrf token to the frontend and set it there in cookie section in application tab in dev window in the browser: @method_decorator(ensure_csrf_cookie) def get(self, request, format=None): return JsonResponse({'csrftoken':get_token(request)}) in react side: useEffect(()=>{ axios.get('http://127.0.0.1:8000/csrf/').then((res)=>{ console.log(res.data) Cookies.set('csrftoken',res.data.csrftoken) }) },[]) let handleSubmit = (e) => { e.preventDefault(); axios .post("http://127.0.0.1:8000/signup/", signup, { withCredentials: true, headers: { "X-CSRFToken": Cookies.get("csrftoken") }, }) .then((res) => { setDisabled(true) setIsUp(true) setTimeout(()=>{setIsUp(false) redirect('/')},3000) }) .catch((e) => { console.log(e.response.data) let err = e.response.data setError(err); }); }; on my local machine (on the local hosts): i get these values to match: as you can see both Cookie and X-CSRFToken are matching in request header, however, in production: and the weirder part is that in request header the name of the key in local host is Cookie, but in production it is cookie (c and C difference) and of course I get an error when i make a post request in production server: <p>CSRF verification failed. Request aborted.</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF token from the &#x27;X-Csrftoken&#x27; HTTP header incorrect. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/4.0/ref/csrf/">Django’s help …