Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a asynchronous thread in python that does not return control
I have a django server built for a mobile app i.e. using JSON response. The app has a simple social media feed. The admins of the app have the ability to use push notifications (through firebase) on posting a new post to the feed. At the movement the code is 'synchronous' and goes something like def post(View): # validate post ect... # store it in database # ! Send push notifications ! # return response The issue is if firebase lags or is slow (which it sometimes seems to be) this can slow down the response. What I would like to do is make an asynchronous function that I can call to handle the push notification and forget about it and return the response to the user and the push notification can take as long as it needs. [Meta] Help in wording the title would be appreciated. -
Django Ckeditor works on localhost does not on the server
Error output on browser console: GET http://{ip}/static/ckeditor/ckeditor/ckeditor.js net::ERR_ABORTED 404 (Not Found) GET http://{ip}/static/ckeditor/ckeditor-init.js net::ERR_ABORTED 404 (Not Found) GET http://{ip}/static/ckeditor/ckeditor/ckeditor.js net::ERR_ABORTED 404 (Not Found) I don't understand what would be the problem here. I import ckeditor.RichTextField and use it in my form. I installed: pip install whitenoise pip install django-ckeditor I use it in localhost with toolbars, and without a bug but when i deploy it to the server the toolbar gets removed. Any helpful answer is appreciated. Thanks. -
Djano value has an invalid format. It must be in YYYY-MM-DD HH:MM
for example when I use auto_now_add=True "Jan. 1, 2021, 5:05 a.m." format, but when I want to update the date, I get the error "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']", I don't have a problem when I update it by entering in YYYY-MM-DD HH:MM format, but how can I bring this date automatically in this format? models.py; class problemduyuru(models.Model): olusturulmatarihi = models.DateTimeField(auto_now_add=True, blank=True) duyurutipi = models.TextField(max_length=100, null=True) incidentno = models.TextField(max_length=100, null=True) baslangiczamani = models.TextField(max_length=100, null=True) aciklama = models.TextField(max_length=100, null=True) views.py create and update; update; def problemduyurusuupdate(request, id): problemmember = problemduyuru.objects.get(id=id) problemmember.duyurutipi = request.POST['duyurutipi'] problemmember.incidentno = request.POST['incidentno'] problemmember.baslangiczamani = request.POST['baslangiczamani'] problemmember.aciklama = request.POST['aciklama'] problemmember.olusturulmatarihi = request.POST['olusturulmatarihi'] problemmember.save() messages.success(request, 'Alarmlar was updated successfully!') return redirect('/problemduyurusu') create; def problemduyurusucreate(request): if request.method == 'POST': problemmember = problemduyuru( duyurutipi=request.POST['dduyurutipi'], incidentno=request.POST['dincidentno'], baslangiczamani=request.POST['dbaslangiczamani'], aciklama=request.POST['daciklama'], olusturulmatarihi=request.POST['dolusturulmatarihi'], ) try: problemmember.full_clean() except ValidationError as e: pass problemmember.save() messages.success(request, 'Alarmlar was created successfully!') return redirect('/problemduyurusu') else: return render(request, 'problemduyurusucreate.html') -
How to query jsonb column in PostgreSQL with Python and Django
I've looked at many of the solutions here and elsewhere but I'm not getting my code to work no matter what I try. So I've got a PostgreSQL database with a Django application, and one of the columns in one of my tables, employee_schedules, is a jsonb data type. In the Django model it's of type JSONField: day1_actual_punches = models.JSONField(null=False, default=dict) day2_actual_punches = models.JSONField(null=False, default=dict) day3_actual_punches = models.JSONField(null=False, default=dict) day4_actual_punches = models.JSONField(null=False, default=dict) day5_actual_punches = models.JSONField(null=False, default=dict) day6_actual_punches = models.JSONField(null=False, default=dict) day7_actual_punches = models.JSONField(null=False, default=dict) In the PostgreSQL database the day1_actual_punches is stored like this: "{\"EmpCode\":\"A00X\",\"FullName\":\"ABBY SENSENBAUGH\",\"InPunchTime\":\"2021-09-26 16:57:00\",\"OutPunchTime\":\"2021-09-26 22:48:00\",\"PayRate\":\"6.00\",\"OvertimePayRate\":\"9.00\",\"PayType\":\"HOURLY\",\"ScheduleType\":\"Food and Beverage\",\"EmpPosition\":\"Server PM\",\"DateTimeIn1\":\"2021-09-26 4:57 PM\",\"DayNumber\":1,\"WeekStartDate\":\"2021-09-26 16:57:00\",\"PunchDayIndex\":6,\"HoursWorked\":\"5.85\"}" I'm using the following to test getting a record from the database, using the python console, like this, following the Django documentation for querying jsonb data. results = EmployeeSchedule.objects.filter(day1_actual_punches__EmpCode='A00X') But the Queryset is always returning empty, even though I see the record in the table. Is this because of how I'm saving the python dict to the database, which is causing the slashes or something? Here's a code sample of saving the record to the database: empschedule_new = EmployeeSchedule() if self.day_number == 1: empschedule_new.day1_actual_punches = json.dumps(dict_time_punches, separators=(',', ':')) The data inside dict_time_punches looks like this … -
How to create drag and drop and forward to some function in django?
I have a django website, and I would like to implement drag&drop to my form. This part is looking very old compare to the rest of site. Problem is that I don't know javascript, I have tried to make if from tutorials but did not make any sense. Can you help me to get simple solution for this. Any ideas how to do this with zero knowledge of js? cal.py def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] #pandas calculations response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'cal.html', { 'form': form, 'page_title':page_title }) cal.html {% extends "base.html" %} {% load static %} {% block content %} <form action="{% url "cal" %}" method="post" enctype="multipart/form-data" class="dropzone"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload and Download!"/></p> </form> {% endblock content %} urls.py urlpatterns = [ path('', views.home, name='home'), path('cal/', cal.OnlyCAL, name='cal'), ] -
How to add additional data to form.serialize() in django ajax Call when using a model form?
I have a django view that uses ajax to check if the form is valid and create new object if so, but I would like also some additional data with the form.serialize() to know which fields are complete by the user so I will know what to pass to the create method. Here is the view: def createIssue(request): form = CreateIssueForm(request.POST or None) if request.is_ajax() and form.is_valid(): kwargs = request.POST.get("kwargs") print(kwargs) # if kwargs is present #model.objects.create(**kwargs) context = {""} return JsonResponse({}) return render(request, "tracking/base.html") Here is the ajax call: function CreateIssueAjax(e) { e.preventDefault(); const role = this.getAttribute('role'); const _form = $("#CreateIssueForm"); var formString = _form.serializeArray(); console.log(formString) function sendKwargs(arr) { let kwargs = {} arr.forEach(el => { if (!(el.value === "") | (!el.name === 'csrfmiddlewaretoken')) { kwargs[el.name] = el.value } }); return kwargs; } var myData = _form.serialize(); console.log(myData); myData['kwargs'] = JSON.stringify(sendKwargs(formString)); $.ajax({ url: "/create-issue/", type: "post", data: myData, datatype: 'json', success: function (data) { console.log("success"); // add to ui function after success // alert the user(alertify.js) }, }); } Now as I am using a modelform, adding the kwargs key to form dict will prevent the form from being valid. Is there any other way to pass another key … -
EmptyPage error on final page of paginated Wagtail site
I've searched the site and none of the answers are different from what I've tried: Example | Example | Example | Example My aim is to display 5 posts per paginated page on my Wagtail site. It works except for the fact I am getting a persistent EmptyPage error on the last page. I currently have 25 live posts, so there should be exactly 5 on each of the 5 pages. It's just page 5 (currently last page) that comes up empty. I am pretty sure the problem is with the template and not with the queryset/model itself, but everything I've seen online looks identical to what I have. Here is my model: class BlogIndexPage(Page): body = RichTextField(blank=True) def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) blog_pages = BlogPage.objects.live().public().order_by("-date") page = request.GET.get("page") paginator = Paginator(blog_pages, 5) try: blog_pages = paginator.page(page) except PageNotAnInteger: blog_pages = paginator.page(1) except EmptyPage: blog_pages = paginator.page(paginator.num_pages) context["blog_pages"] = blog_pages return context Here is my template: {% if blog_pages.paginator.num_pages > 1 %} {% if blog_pages.has_previous %} <li class="page-item"> <a href="?page={{ blog_pages.previous_page_number }}" class="page-link"> <span>&laquo;</span> </a> </li> {% endif %} {% for page_num in blog_pages.paginator.page_range %} <li class="page-item {% if page_num == blog_pages.number %} active{% endif … -
Why Django doesn't update an image field
I want to build a view that allows the user to update his profile picture. Now in my view the cleaned data returns the current profile image path which then overwrites the existing one one by one. I'm not sure where the issue is. Also since I use a default image within the model manager, I only want to delete the current imagefield if it isn't the default one. # View @require_POST def update_profile_image(request, username): """ Updates the user profile """ form = ImageUpdateForm(request.POST) if form.is_valid(): image = form.cleaned_data['profile_image'] print('image ' + str(image)) user = Account.objects.get(username=request.user.username) user.profile_image = image user.save() return redirect('pollboard') # Model class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image()) # Custom Manager class MyAccountManager(BaseUserManager): def get_profile_image_filepath(self, filename): return f'profile_image/{self.pk}/{"profile_image.png"}' def get_default_profile_image(): return "profile_image/Logo_large.png" # Form class ImageUpdateForm(forms.ModelForm): class Meta: model = Account fields = ['profile_image'] # Template <div class="profile-image-modal"> <form method="post" action="update_profile_image/"> {% csrf_token %} {{ profile_image_form }} <button type="submit">Save Image</button> </form> </div> -
Django rest framework viewset does it needs locks for multiple requests
I'm new to django and django restful framework and currently learning. Upon reading about viewsets from this link https://www.django-rest-framework.org/api-guide/viewsets/. I wonder for some of the methods like update and destroy that modifies a row in the database. Does one need to put locks or the build in method takes care of it? In addition, if the method takes care of it and one needs to modify or override it then you add locks? Thanks in advance and appreciate any answers. -
Unittest with mock for django login
I am writing Unittests for the Login on Django. And I have serious problems with the get_user(). I just can't figure out how to get through this function in test. I can't make a mock, and I can't substitute values. I think I'm wrong do it. But I don't know how do it right! Please, I need help! def user_login(request): if request.method == 'POST': form = UserLoginForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect('/') I need unittest for this simply function. -
Switching Django languages with flags and urls
I am currently having a language switcher in Django based on flags, but where the URL for all languages are the same. I would now like to change the language switcher so that selecting a flag also redirects the user to a URL prefix (like /en, /es, /fr, etc.) so I easily can send the page in different default languages to different users. Linking to the URL prefix works fine, but how do I easiest redirect the users there when they select flags in the code below? <div class="navbar-btns ml-3"> <div class="navbar-btns-inner"> <div id="language-switcher" class="navbar-btn collapsed"> <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="/" /> <select name="language" onchange="this.form.submit()"> {% for language in request|get_language_info_list_ex %} <option value="{{ language.code }}" {% if language.is_current %} selected="selected"{% endif %}> <span class="flag">{{ language.flag }}</span> {# {{ language.code }} #} </option> {% endfor %} </select> </form> </div> </div> </div> -
Change Date Format in Django Models when retrieving Data from PostgreSQL showing in form
I'm using django to submit data in postgresql database. Submission work fine and datastapm on database is correct and match with timezone. I'm useing bellow code to crate time and use in database. created_at = models.DateTimeField(auto_now_add=True) format of time in database: 2021-10-05 20:18:41.773503+03:30 Issue is here that when getting data from database and show it on table, time zone not correct and data format changing to Oct. 5, 2021, 4:48 p.m. without timezone How can I make this correct on view form and show it like 2021-10-05 20:18:41 -
Why I had error todo.views.signupuser didn't return an HttpResponse object
I write a site in django. And for some reason as a result I get an error The view todo.views.signupuser didn't return an HttpResponse object. It returned None instead.. How can I fix this error? Below I will attach my code. My html code: signupupser.html <h1>Sign Up</h1> <h2>{{ error }}</h2> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Sign Up</button> </form> My urls.py: urls.py from django.contrib import admin from django.urls import path from todo import views urlpatterns = [ path('admin/', admin.site.urls), path('signup/', views.signupuser, name='signupuser') ] My views.py views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.db import IntegrityError def signupuser(request): if request.method == 'GET': return render(request, 'todo/signupuser.html', {'form': UserCreationForm()}) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() except IntegrityError: return render(request, 'todo/signupuser.html', {'form': UserCreationForm(), 'error': 'That Username has already been taken. Please choose a new username'}) else: return render(request, 'todo/signupuser.html', {'form': UserCreationForm(), 'error': 'Passwords did not match'}) -
Pdf format output is scattered in django
Hi I wanted to create invoice using WeasyPrint. I would like get a well formatted print as output for invoice. I'm using following function to create pdf: from weasyprint import CSS, HTML def render_to_pdf(context, file_name): file_data = render_to_string('order_detail.html', context) html = HTML(string=file_data).write_pdf( target='collections/%s' % (file_name), stylesheets = [CSS(string='body { font-size: 7px }')] ) fs = FileSystemStorage("") with fs.open("collections/" + file_name) as pdf: response = HttpResponse(pdf, content_type="application/pdf") response['Content-Disposition'] = '"attachment; filename="%s"'% (file_name) print("pdf working") return response In the latest version I used stringformat but earlier I tried with normal jinja templating and output was same. here is my html: {% 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>Email</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <style> .container { border: 1px solid #585696; padding: 0; } .header { background-color: #585696; padding: 1.5rem; } h1.text-center { color: #fff; text-align: center; } .text-center { text-align: center; color: #585696; } .text-content { padding: 2rem; } .order-header{ color: #585696; margin-top: 1rem; } .table-stripped{ width: 100%; border: 1px solid #585696; } .title-bar { background-color: #585696; color: #fff; } th, td { text-align: center; border-bottom: 1px solid #585696; } tr { border-bottom: 1px solid #585696; } .address-time { margin-top: 0; … -
How to get a list of celery tasks that are queued but not yet started
Django 2.2.13 Celery 5.0.5 Redis = 3.5.3 I would like to know, given a task id how can i see if it's in the queue and not yet in the "STARTED" state ( i do have CELERY_TASK_TRACK_STARTED=True). Is the only way to make a key in Redis and query for that key, and if it's not present then i can enqueue? -
New Django project admin urls are somehow being overridden by prior project Django-Allauth settings
I have a new project, using DRF, and when trying to login to admin panel I get an error stating that the page not exist. The problem is that the url being generated when entering the current url is the same url that I used in my prior project using Django-Allauth. I have checked the current project for any traces of Django-Allauth and there are none. I checked the DB to make sure it was empty upon initiation of the project, and it was. What could be the problem here? current url.py urlpatterns = [ path('admin/', admin.site.urls), ..., ] prior urls.py path("accounts/", include('allauth.urls')), When I try to login to admin on localhost: http://127.0.0.1:8000/admin/ it redirects to old project's path of: http://127.0.0.1:8000/accounts/login/?next=/admin/login/%3Fnext%3D/admin/ resulting in an error stating page not found. I cleared cache by restarting project with Pycharm's Invalidate Cache/Restart but that did not resolve the issue. Any guidance is appreciated. -
Why am I getting no reverse match error in django 3.2?
I am making a simple todo list application but while adding a delete button, I am receiving the error. I tried many things searching on internet but couldn't solve the issue, probably because i am new to django.So, your help will be very important. urls.py(of app): from django.conf.urls import url from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home'), url('delete/<str:id>', views.delete_data,name='deldata'), ] views.py: from django.shortcuts import get_object_or_404, render,redirect from todo.models import value from django.http import HttpResponseRedirect # Create your views here. from .forms import TitleForm from django.urls import reverse def home(request): values=value.objects.all() form=TitleForm if request.method=='POST': form=TitleForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form=TitleForm() return render(request,'home.html',{'values':values,'form':form}) #delete def delete_data(request, id ): ggwp=value.objects.get(id=id) if request.method=="POST": ggwp=value.objects.get(id=id) ggwp.delete() return HttpResponseRedirect(reverse('deldata', kwargs={'id':id})) context={'ggwp':ggwp} return render(request,'/',context) models.py: from django.db import models # Create your models here. class value(models.Model): task=models.CharField(max_length=200) complete=models.BooleanField(default=False) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.task home.html(One and only html page): <h3>TO DO LIST</h3> <form method="POST" action="\"> {% csrf_token %} {{form.task}} <input type='submit' name='add' value="add" > </form> {% for val in values %} {{val}} <form action="{% url 'deldata' val.id %}" method="POST" class="in-line"> {% csrf_token %} <input type="submit" value="Delete" > </form> {% endfor %} traceback: raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'deldata' with arguments '(15,)' not found. … -
Django doesn't see static files (404 error)
I faced with problem when django can't see static files and i'm getting 404 error every time visiting page. [05/Oct/2021 19:25:07] "GET /static/main/css/index.css HTTP/1.1" 404 1813 Here is my setting.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join('static'), ) # Default primary key field type Another part was cut HTML file {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello World</title> <link rel="stylesheet" href="{% static 'main/css/index.css' %}" /> </head> Another part was cut too My files (png) -
Inaccessible class via "manage.py"
Class used to create pickled object in another module is inaccessible via running "python manage.py runserver". How do I point "manage.py" to that class (Classify)? Here's my stack trace below: Internal Server Error: /api/digits/ Traceback (most recent call last): File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\mixins.py", line 19, in create self.perform_create(serializer) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create serializer.save() File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\serializers.py", line 205, in save self.instance = self.create(validated_data) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\serializers.py", line 939, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) File "C:\Users\DELL\Desktop\mnist-env\MNIST_API\digits\models.py", line 62, in save pred = pickle.load(f) AttributeError: Can't get attribute 'Classify' on <module '__main__' from 'C:\\Users\\DELL\\Desktop\\mnist-env\\MNIST_API\\manage.py'> [05/Oct/2021 17:22:43] "POST /api/digits/ HTTP/1.1" 500 54505 Here's an image of my project file structure P.s: The class … -
SMTP Data Error when using sendgrid in django
I am encountering the following error when I try to send emails from my django app despite having setup sendgrid correctly here is my configuration in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'MY_API_KEY' EMAIL_PORT = 587 EMAIL_USE_TLS = True could django be having a from email that it is set to by default that needs to be overridden? -
How do i display multi images in two column grid in django
I Have tried using the forloop.counter but it makes the whole grid look messy and plus it only shows three pictures in the grid when you click a picture to have a detail view and sliding to see the other pictures it wont show other pictures as i have about eight pictures posted in the same grid. if the pictures are few i have to go back into the forloop.counter and change the divisible number which is not a good practice how best do i go about it. <div uk-lightbox> <div class="grid grid-cols-2 gap-2 p-2"> {% for p in photos %} {% if forloop.counter|divisibleby:3 %} # The First image goes here <a href="{{ p.pic.url }}" class="col-span-2"> <img src="{{ p.pic.url }}" alt="" class="rounded-md w-full lg:h-76 object-cover"> </a> The second goes here <a href="{{ p.pic.url }}"> <img src="{{ p.pic.url }}" alt="" class="rounded-md w-full h-full"> </a> # the rest of the pictures goes <a href="{{ p.pic.url }}" class="relative"> <img src="{{ p.pic.url }}" alt="" class="rounded-md w-full h-full"> <div class="absolute bg-gray-900 bg-opacity-30 flex justify-center items-center text-white rounded-md inset-0 text-2xl"> + {{ forloop.counter }} more </div> </a> {% endif %} {% endfor %} </div> </div> After i tried the above this what i did again but … -
Unauthorized response using Firebase auth with DRF
I have created a drf API which I have connected to a react-admin frontend in order to have a ready-to-go dashboard interface and it works. But I want to implement firebase authentication into the frontend, and when I try to do that I get errors, and seems that my backend is reading my auth header because it is giving me the bearer token into the console but still gives me an unauthorized response. The backend I am using for the moment is sqlite and I have not created any custom user models, for the moment I am trying to log in from the front-end with an account from firebase. Here are my code samples: class FirebaseAuthentication(authentication.BaseAuthentication): def authenticate(self, request): token = request.headers.get('authorization') print(token) if not token: raise NoAuthToken("No auth token provided") try: decoded_token = auth.verify_id_token(token) uid = decoded_token['uid'] except Exception: raise InvalidAuthToken("Invalid auth token") if not token or not decoded_token: return None try: user = User.objects.get(username=uid) return user except Exception: raise FirebaseError("User does not exist") and here is the react configuration for the firebase auth provider const authProvider = FirebaseAuthProvider(firebaseConfig, firebaseOptions) const dataProvider = drfProvider('http://127.0.0.1:8000/api') export { authProvider, dataProvider } -
Stop a C /C++ extension in Django
Summary of the problem I am implementing a long-running C/C++ extension within a Django framework (called via a request POST). In some cases, the user may want to interrupt the calculation by just leaving/unloading the specific web page that calls the C extension. Is it possible to kill the extension from Python? Minimal Reproducible Example In order to reproduce the problem, we can make our own Fibonacci C extension. The call in Django is as follows: import fibonacci from django.views.generic.base import TemplateView # Computation class ComputationView(TemplateView): template_name = 'Generic/computation_page.html' @staticmethod def get_results(request): N=1000 if request.method == "POST": # When button is pressed # Long computations cs_min = fibonacci.fib(N) else: cs_min = None return render(request, ComputationView.template_name, {'cs_min': cs_min}) While the code in C is: #include <Python.h> // Compute the Minimal cutsets int Cfib(int n) { int fib1; int fib2; if (n < 2) return n; else{ Py_BEGIN_ALLOW_THREADS // Release GIL // Some stric operations in C Py_END_ALLOW_THREADS // Reacquire GIL return Cfib(n-1)+Cfib(n-2); } } // Our Python binding to our C function // This will take one and only one non-keyword argument static PyObject* fib(PyObject* self, PyObject* args) { // instantiate our 'n' value int n; // Order of cutset // … -
TypeError: cannot unpack non-iterable Responses object
I am trying to save some data (fetched from an API) into my database. A list (named GetQuestion_response) was obtained from that API is kinda like this (The actual data from the API is a lot bigger, so I show the first 2 elements of the list here.): GetQuestion_response = [ { "Id":1, "GroupId":0, "QuestionTitle":"What is your first name?", "GroupName":null, "QuestionType":"TEXT","IsMappingAvailable":null,"BodyRegion":0,"EnableCalculation":false,"Responses":[] }, { "Id":2, "GroupId":0, "QuestionTitle":"And your last name?", "GroupName":null, "QuestionType":"TEXT","IsMappingAvailable":null,"BodyRegion":0,"EnableCalculation":false,\"Responses\":[] } ] my models.py: class Responses(models.Model): Answer_Id = models.IntegerField(primary_key=True) QuestionId = models.IntegerField(default=0) ResponseText1 = models.CharField(max_length=500, null=True, blank=True) ResponseText2 = models.CharField(max_length=500, null=True, blank=True) ResponseText3 = models.CharField(max_length=500, null=True, blank=True) IsDeleted = models.BooleanField(default=False) class GetQuestion_API(models.Model): Question_Id = models.IntegerField(primary_key=True) GroupId = models.IntegerField(default=0) QuestionTitle = models.TextField() GroupName = models.CharField(max_length=500, null=True, blank=True) QuestionChoice = [ ('TEXT', 'TEXT'), ('BUTTON', 'BUTTON'), ('NUMBER', 'NUMBER') ] QuestionType = models.CharField(max_length=50, choices=QuestionChoice, default='TEXT', null=True, blank=True) IsMappingAvailable = models.CharField(max_length=500, null=True, blank=True) BodyRegion = models.CharField(max_length=200, null=True, blank=True) EnableCalculation = models.BooleanField(default=False) Responses = models.ForeignKey(Responses, on_delete=models.CASCADE, related_name="QuestionReletedResponses", null=True, blank=True) In my views.py: for i in GetQuestion_response: this_Id = i['Id'] this_GroupId = i['GroupId'] this_QuestionTitle = i['QuestionTitle'] this_GroupName = i['GroupName'] this_QuestionType = i['QuestionType'] this_IsMappingAvailable = i['IsMappingAvailable'] this_BodyRegion = i['BodyRegion'] this_EnableCalculation = i['EnableCalculation'] GetQuestion_API_obj = GetQuestion_API.objects.create( Question_Id = this_Id, GroupId = this_GroupId, QuestionTitle = this_QuestionTitle, GroupName = this_GroupName, … -
Django create Email Change Confirmation Email
I want to create an confirm email for changing the email from the django user. For this I need an unique url which reffers to the site on which I can change it which expires after like 1hour. I also need to know how to send that unique url to the user's old email. How can I do that?