Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Renew and set JWTs as HttpOnly cookie using a middleware. Response() returning django.template.response.ContentNotRenderedError
I have a custom middleware where I am adding SimpleJWR HTTP_AUTHORIZATION to every authorized requests as I am using HttpOnly cookies. Also here I have added code to check whether an access token is valid or not. If not, then a request is sent using requests which fetches the new access token and set's it as HttpOnly cookie. So far, I'm able to get the new access token after it expires. But, the url from where I dispatched the request returns this error: raise ContentNotRenderedError( django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed. At the first request it works. It returns the response and saves the tokens as HttpOnly cookies but after the token expires and if I again make the request, instead of (what I want to happen) saving the tokens as HttpOnly cookies and returning the same response again, it is returning the error. I think the issue is in the response statements. My middleware: import jwt import datetime import requests import json from rest_framework.response import Response from django.conf import settings class AuthorizationHeaderMiddleware: def __init__(self, get_response=None): self.get_response = get_response def __call__(self, request): access_token = request.COOKIES.get('access') refesh_token = request.COOKIES.get('refresh') print(refesh_token) # check if the access … -
ModuleNotFoundError: No module named 'mysite.wsgi' error comes up during deployment
I was making a Django web app using pipenv, the Application error window pops up whenever i try running 'heroku open', please help i am stuck in deploying this for over one month and have tried almost every possible solution that was available online but the error still persists. please help. Running'heroku logs --tail' shows: $ heroku logs --tail 2021-02-17T17:50:51.188410+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2021-02-17T17:50:51.297606+00:00 heroku[web.1]: Process exited with status 1 2021-02-17T17:50:51.389796+00:00 heroku[web.1]: State changed from starting to crashed 2021-02-17T17:50:53.000000+00:00 app[api]: Build succeeded 2021-02-17T17:51:39.619675+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=bloggero.herokuapp.com request_id=ecbd78a2-5542-4d08-87f7-e7d12404ae9b fwd="223.239.61.176" dyno= connect= service= status=503 bytes= protocol=https 2021-02-17T17:51:41.855171+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=bloggero.herokuapp.com request_id=42dd37d3-ad4b-43dc-956d-41d34bf03ffd fwd="223.239.61.176" dyno= connect= service= status=503 bytes= protocol=https 2021-02-17T18:04:58.000000+00:00 app[api]: Build started by user ad******@gmail.com 2021-02-17T18:05:29.716771+00:00 app[api]: Deploy 879be0de by user a******@gmail.com 2021-02-17T18:05:29.716771+00:00 app[api]: Release v19 created by user a*******@gmail.com 2021-02-17T18:05:30.074089+00:00 heroku[web.1]: State changed from crashed to starting 2021-02-17T18:05:35.396728+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi` 2021-02-17T18:05:37.756029+00:00 app[web.1]: [2021-02-17 18:05:37 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-02-17T18:05:37.756584+00:00 app[web.1]: [2021-02-17 18:05:37 +0000] [4] [INFO] Listening at: http://0.0.0.0:17786 (4) 2021-02-17T18:05:37.756675+00:00 app[web.1]: [2021-02-17 18:05:37 +0000] [4] [INFO] Using worker: sync 2021-02-17T18:05:37.761624+00:00 app[web.1]: [2021-02-17 18:05:37 +0000] [9] [INFO] Booting worker with … -
could someone explain why we return super().form_valid(form) in form_valid method in CreateView in django?
I am trying to link the Item associated with a user class createItem(CreateView): model=Item fields = ['x','y','image'] def form_valid(self,form): form.instance.user_name=self.request.user return super().form_valid(form) this is the snippet,i dont get why we use super().form_valid(form) ,and i also have doubt regarding using self in self.request.user ,i am new to django ,it will really helpful if someone assisted me. -
How do I access only first element in nested dictionary in Django template?
I'm trying to print only first key and value of nested dictionary in django. I am able to do this with python but in django template language my logic isn't working. Here is my code in DTL {% for key, value in data.items %} <h1>Dictionary: {{ key }}</h1> {% for key, value2 in value.items %} <h3>Nested Dictionary-> {{ key }}: {{ value2 }}</h3> <!-- Its printing complete nested Dictionary--> {% endfor %} Here is my view.py which takes data from api then converts json to dictionary def home(request): res = requests.get('https://covid19.mathdro.id/api/countries/india') data = (res.json()) print(type(data)) return render(request, 'Caraousel/home.html', {'data':data}) Here is my output screen. As you see I want to print only value: number -
Any suggestions for a Django Rest Framework JWT package that sets and supports HttpOnly cookies?
I've been using djangorestframework-simplejwt for a while but now I want to store the JWT token in the cookies (instead of localstorage or front-end states) so that every request that the client makes, contains the token. So did some research on it and the most relevant result I found was this stackoverflow question, in which the author is using djangorestframework-jwt which has a pre-configured setting for cookies called JWT_AUTH_COOKIE. So figured switching to that package but then ended up finding out that the package is pretty much dead. Although there is a fork for the djangorestframework-jwt that is recommended to use instead, I was wondering if anyone has any better suggestions of packages or anyways for setting the JWT token in an HttpOnly cookie in the response even in djangorestframework-simplejwt package or something. -
DJANGO: Cannot Filter My Sales List According to the Customer Which is Connected to the User
I have a system where a user can create multiple Customers(Musteri in Turkish) and assign them certain sales. I am trying to use filter() to get the results of my sales(satis in Turkish) list. However, I cannot figure out how to do this. OneToOneField doesn't work in this case and I can't find a way to display my sales and I'd love your help. Thank you in advance. models.py from django.db import models from datetime import datetime, date from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model User = get_user_model() class musteri(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) ad = models.CharField(max_length=100,blank=True) soyad = models.CharField(max_length=100, blank=True) eposta = models.EmailField(max_length=100, blank=True) adres = models.TextField(max_length=200, blank=True) tc = models.CharField(max_length=12, blank=True) telefon = models.CharField(max_length=15, blank=True) def __str__(self): return self.ad + ' ' + self.soyad class Meta: verbose_name = _("musteriler") verbose_name_plural = _("musteriler") TITLE_CHOICES = [ ('Optik', 'Optik'), ('Güneş', 'Güneş'), ('Lens', 'Lens'), ] SATIS_CHOICES = [ ('Nakit', 'Nakit'), ('Kredi Kartı', 'Kredi Kartı') ] class satis(models.Model): musteri = models.ForeignKey(musteri,blank=True, null=True, on_delete= models.SET_NULL) tarih = models.DateField(null=True,blank=True) tur = models.CharField(max_length=5, choices=TITLE_CHOICES, null=True, default='Optik') satici = models.CharField(max_length=100, blank=True) uzak_cerv = models.CharField(max_length=300, blank=True) yakin_cerv = models.CharField(max_length=300, blank=True) uzak_cam = models.CharField(max_length=200, blank=True) yakin_cam = models.CharField(max_length=200, blank=True) saguz_sph = models.CharField(max_length=6, blank=True, null=True) … -
Django models: Name "undefined" is not defined
Hello there I'm trying to make an eBay-like commerce site with Django, and I'm using the Django models to do it. I have a create page with this form: <form method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" placeholder="Item title" name="title" required> </div> <div class="form-group"> <textarea class="form-control" rows="5" placeholder="Description..." name="description" required></textarea> </div> <div class="form-group"> Category <select class="form-control" name="category" required> <option>Fashion</option> <option>Tools</option> <option>Toys</option> <option>Electronics</option> <option>Home accessories</option> <option>Books</option> </select> </div> <div class="form-group"> <label for="exampleFormControlInput1">Initial Bid</label> <input type="number" class="form-control" id="exampleFormControlInput1" placeholder="Starting bid..." name="price" required> </div> <div class="form-group"> <label for="exampleFormControlInput1">Image link (optional)</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="https://example.com/image.jpg..." name="link"> </div> <button class="btn btn-outline-info" type="submit">Submit</button> </form> And this as my views function: def create(request): if request.method == "POST": if Item.objects.last() == undefined: newid = 1 else: newid = lastitem = Item.objects.last().itemid+1 newitem = Item() newitem.owner = request.user.username newitem.name = request.POST.get('title') newitem.about = request.POST.get('description') newitem.price = request.POST.get('price') newitem.category = request.POST.get('category') newitem.itemid = newid if request.POST.get('link'): newitem.link = request.POST.get('link') else : newitem.link = "https://picsum.photos/400" newitem.save() return HttpResponseRedirect(reverse("index")) if request.user.is_authenticated: return render(request, "auctions/create.html") else: return HttpResponseRedirect(reverse("login")) . I have imported my models like from .models import User, Item and my model's file is the following: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser, models.Model): pass class … -
django the following data would have been submitted to the server
I'm trying to create a question and answer survey with django, but the data is not saved in the database django the following data would have been submitted to the server def add_questions(request): form = QuestionForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('users:question')) form = QuestionForm() context = { 'form': form } return render(request, 'pages/data-entry-tool/add-question.html', context) ``` -
Celery container crashes when using django cache_page (InvalidCacheBackendError)
I am facing an issue with my Django webapp project. I am running a containerized environment using Django, Postgres, Redis and Celery. Mainly, I want to use Redis for caching and Celery to set up live updates. So far, I have been able to connect to redis and celery and store celery task results in the redis cache. Things get messy when I try to cache pages in django using Redis. For some reason, using django's caching system (cache_page decorator) breaks my celery container. The Error My Celery container encounters this error: django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis' Here is the full traceback: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/cache/__init__.py", line 50, in _create_cache backend_cls = import_string(backend) File "/usr/local/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_redis' During handling of the above exception, … -
Django creating dependent dropdown menus using pyodbc queries
I'm trying to create a dependent dropdown menu in django. Basically, I have 3 menus, which are Division, District and Store. What I need is that depending on the value selected on Division, Disitrict will be filtered, and depending on the district, store will be filtered. I've seen some methods of doing here in stackoverflow but all of them are using models, and I'm using pyodbc. I haven't been able to implement any sort of filtering succesfully since I'm new to html/javascript/ajax, but here is how my files look like. views.py def homeView(request): conn = privatestuff cursor = conn.cursor() cursor.execute('''SELECT DISTINCT division FROM DimStore WHERE NOT division IN ('NULL', 'Closed') ''' ) divisions = [x[0] for x in cursor.fetchall()] cursor.execute('''SELECT DISTINCT district FROM DimStore WHERE NOT district IN ('NULL', 'Closed') ''' ) districts = [x[0] for x in cursor.fetchall()] cursor.execute('''SELECT DISTINCT SAP4Digits FROM DimStore ''' ) sap = [x[0] for x in cursor.fetchall()] context = { 'divisions' : divisions, 'districts' : districts, 'sap' : sap } return render(request, 'dashboard/home.html', context) home.html <form> <div class="row"> <div class="form-group"> <label for="example-date">Start Date</label> <input class="form-control" id="example-date" type="date" name="date"> </div> <div class="form-group"> <label for="example-date">End Date</label> <input class="form-control" id="example-date" type="date" name="date"> </div> <div class="form-group mb-3"> <legend>Division</legend> … -
django not loading .js static file in production
I have a hard time setting up my static files for Django to load. My UWSGI connection is on point, and i receive http 200 OK with index.html, but <scipt type="application/javascript" src="{% static "frontend/main.js" %}"></scipt> gives me nothing. It'strange, because 127.0.0.1:8000/static/main.js actually return main.js. I think there is a problem with loading this file into this template. Any ideas whats wrong? (I run the whole app in docker container) My index.html template to load: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Label It</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </head> <body style="margin: 0"> <div id="main"> <div id="app"> </div> </div> <scipt type="application/javascript" src="{% static "frontend/main.js" %}"></scipt> </body> </html> part from settings.py: STATIC_URL = '/static/' MEDIA_URL = '/static/media/' STATIC_ROOT = '/vol/web/static' MEDIA_ROOT = '/vol/web/media' STATICFILES_DIRS = [ '/vol/web/static/frontend' ] -
Django __str()__ method for model based on other instances
In Django, assuming a model that has a date and a description as attributes: 2021 Feb 04 Description A 2021 Feb 02 Description B 2021 Jan 31 Description C 2021 Jan 30 Description D 2020 Dec 24 Description E Is there an easy way to not print the year/month if there is an older record with that year/month? 04 Description A Feb 02 Description B 31 Description C 2021 Jan 30 Description D 24 Description E Can I write a __str()__ or another method for that model that considers others instances of the model? I have been through Meta options for models in Django but I'm not sure to which extent I can customize those. -
'IntegerField' object has no attribute 'value_from_datadict' error
I am having a problem with my IntigerField in Django forms: Getting error:IntegerField' object has no attribute 'value_from_datadict' This is mine forms.py: from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('task_title','task_discription','task_category','recommended_tools','budget') widgets = { 'task_title': forms.TextInput(attrs={'class':'form-control'}), 'task_discription': forms.Textarea(attrs={'class':'form-control'}), 'task_category': forms.Select(attrs={'class':'form-control'}), 'recommended_tools': forms.TextInput(attrs={'class':'form-control'}), 'budget': forms.IntegerField(min_value=10, max_value=10000000), } Views.py: from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from django.views.generic import ListView,DetailView, CreateView from .models import Post, TaskCategory from .forms import PostForm class AddPost(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' urls.py: from django.urls import path from .views import AddPost urlpatterns = [ path('AddPost/', AddPost.as_view(), name = 'add_post') ] -
Django static files protect access
Can i use login_required to get access to static files? For example if someone know url to static file, still can open this url even logged out. How can i resolve it? Could You give me any solutions how to protect my static files from not logged users. static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I would like to protect my media files -
Django Model with composite primary key didn't update
I have a model with composite primary key class ChatUserModel(CModelMixin): user = models.OneToOneField(Users, models.DO_NOTHING, primary_key=True) chat = models.ForeignKey(ChatModel, models.DO_NOTHING) chat_permissions = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'tbl_chat_users' unique_together = (('user', 'chat'),) And service, which use this model def connect_to_chat(self, serializer: ChatInfoSerializer) -> ChatUserModel: chat_id = serializer.validated_data.get('chat') if ChatUserModel.objects.filter(user_id=self.user.id, chat_id=chat_id).exists(): raise exceptions.ValidationError('User is already member of this chat') bundle = ChatUserModel.objects.create(user=self.user, chat_id=chat_id) if self.user.status == enum_status_of_user.confirmed_email: bundle.chat_permissions = ChatPermissions.canWrite.value bundle.save() return bundle when running, I get an error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "pk_tbl_chat_user_user_id" DETAIL: Key (user_id, chat_id)=(26b01213-b9c3-4abc-b1d2-f7213781a2c6, 3054495f-8a92-49fc-8dd7-7c0700319d87) already exists. I think Django instead update model does create, but i don't know why. Parameter force_update=True didn't help me. -
how to show my post only to my friends in django
I want to show my post only to my friends, How can I filter my post only to my friends? I have tried to filter in html code but as my friends get more, it repeats my post more (I mean repeat one post few times ) My models.py class PostUser(models.Model): posttype = models.CharField(max_length=3000, default='postuser') content = models.TextField(null = True, blank= True) media_image = models.FileField(null = True, blank= True) media_video = models.FileField(null = True, blank= True) per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone') status = models.CharField(max_length=3000, default='active') date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) datetime = models.DateTimeField(auto_now_add=True) like = models.IntegerField(null=True, blank=True) comment = models.IntegerField(null=True, blank=True) share = models.IntegerField(null=True, blank=True) user_pk = models.IntegerField() class Friends(models.Model): # Sender friend_one = models.IntegerField() # Reciver friend_two = models.IntegerField() per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone') status = models.CharField(max_length=3000, default='active') datetime = models.DateTimeField(auto_now_add=True) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) and this is my views.py allmyfriends = Friends.objects.filter(Q(friend_one = request.user.pk) | Q(friend_two = request.user.pk)) -
How to auto-update the slug field in Django admin site?
I know how to auto-populate the slug field of my Blog application from post's title, and it works fine. But if I edit the title the slug field is not changing. Is there any way to have it updated automatically? I use Django's admin site. Thanks. -
Django define update_fields when creating objects in model
I am using a SQL Server table with period columns, and my model in Django is defined as class Client(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=40) sys_start_time = models.DateTimeField(db_column="SysStartTime") sys_end_time = models.DateTimeField(db_column="SysEndTime") class Meta: managed = False db_table = "client" where sys_start_time and sys_end_time are period columns. Due to sql server rules, any query defining values for these columns are invalid, which means that the sql query django generated when creating or updating this model won't work. I managed to exclude them in update_fields when performing update so that django will generate queries without period columns, but I can't use the same update_fields parameter when creating an object, otherwise I get an error saying Cannot force both insert and updating in model saving. Is there a way to let django ignore certain fields when creating an object? OR Is there a way to tell Django to send DEFAULT (sql server keyword, not string) as the value for these period columns? -
How to submit two forms in one Update View
I'm searching how to submit two forms with two different submit buttons in one view class EditAvatarForm(forms.ModelForm): class Meta: model = Person fields = ('avatar',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user_created = None avatar = forms.ImageField(required=True, ) self.fields = OrderedDict( [ ("avatar", avatar), ] ) def clean_avatar(self): image = self.files.get('avatar') if image: try: creator = None if self.instance: creator = self.instance # ?That simple? Yes!: return ImageFile.objects.create( image_file=image, creator=creator ) except IOError: self.add_error('avatar', _("Unknown image type")) return None def clean(self): return super().clean() class EditProfileForm(forms.ModelForm): class Meta: model = User fields = ("username", "first_name", "last_name", "email",) this is the forms.py I would like to be able to change the avatar and the user informations in a single view. Person is a model related to User with user = models.OneToOneField( User, blank=True, null=True, on_delete=models.CASCADE ) and related to imageFile with avatar = models.ForeignKey( ImageFile, default=None, blank=True, null=True, related_name="persons", on_delete=models.SET_NULL, ) -
Two model fields and one form field
I have two fields in Model and one form field. The widget AutocompleteInput is attached to form input. If the user selects an element from the autocompleteinput list in the widget, I want the data to be save to one field model. If the user enters their own string, I want the data to save to another field in the model. So i need to clean the user input, check if the inputs matches any autocomplete option, if so, need to save to the first model, otherwise save to other, but i dont know how to save custom string to db. models.py class Something(models.Model): name = models.CharField("name", max_length=50, default='', blank=True) title = models.CharField("title", max_length=50, default='', blank=True) forms.py class SomethingtForm(DisableModelForm): name = forms.CharField(label='Name', widget=AutocompleteInput( id_key='name', display='name', field_name='something_name', url='/api/something?search=', ), required=False) title = forms.CharField(required=False, max_length=32) def __init__(self, *args, **kwargs): if kwargs.get('instance', None): instance = kwargs['instance'] kwargs['initial'].update({ 'name': instance.name, 'title': instance.title, }) def clean_name(self): if self.instance and hasattr(self.instance, 'blabla'): return self.initial['name'] return self.cleaned_data['name'] def clean_title(self): if self.instance and hasattr(self.instance, 'blabla'): return self.initial['title'] return self.cleaned_data['title'] def clean(self): cleaned_data = super().clean() name = cleaned_data.get('name') title = cleaned_data.get('title') if title not in Blabla.queryset.all(): #autocomplete options ........... # if input doesnt match autocomplete options i want to … -
SMTPServerDisconnected at /password-reset/
Connection unexpectedly closed: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') Less secure app access are allowed on my gmail account -
TypeError: connect() argument 4 must be str, not WindowsPath . /*The Error that i m getting in my simple login django project*/
System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. February 17, 2021 - 19:52:27 Django version 3.1.6, using settings 'felix.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. C:\Users\FELIX\OneDrive\Desktop\Projects\django login2\felix\felix\settings.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 459, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 53, in init self.build_graph() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 216, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 235, in cursor self.ensure_connection() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, … -
How do you implement CSRF tokens in django rest framework?
I have noticed that when using django and you make a post request, using a form for example, django asks you to add the csrf token, but when I was fetching data from an api created with django rest framework with react I realized that when I didn't send the csrf token there wasn't any error with the application. In this app I am using token authentication with knox and I have seen some posts about how to use csrf token with session authentication. My question is if token authentication does not need the csrf tokens or are they passed automaticaly by react? Thanks in advance. -
JavaScript cloning an element with a loop inside
I'm new to coding/web development, I'm using JavaScript function to clone an Element which has a loop inside it. But the function is not working. Following is my HTML code: <table> <tr> <td id="add"> <Select class="selectpicker form-control" name="audience"> <option value="all">All</option> <option value="teachers">Teachers</option> <option value="parents">Parents</option> <option value="students">Students</option> {% for i in range(1,14) %} <option>{{i}}</option> {% endfor %} </Select> </td> <td><button type=button onclick="newfield()" class="btn btn-outline-success"> + </button> <button type=button onclick="remove()" class="btn btn-outline-danger"> - </button> </td> </tr> </table> And following is my JavaScript function: function newfield(){ var newselection =document.getElementById("add").firstChild; var newfield = newselection.cloneNode(true); var x = document.getElementById("add") x.insertBefore(newfield, x.firstChild); } function remove(){ var x = document.getElementById("add"); x.removeChild(x.lastChild); } but when I manually insert the numbers from 1 to 13 in attribute. the function works perfectly. As I'm new to coding space I'd like to know whether there's a way to overcome this problem. Thank you. -
Python requests in CRON job getting called twice
I'm not really sure why but each request I make with the Python requests library is getting called twice. I am sure that the CRON job is not called twice as I'm logging a message to a logfile every time it runs. What might be the possible issue for this? Here is a screenshot of the calls: If you take a look at their times, they're very close to each other.