Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
forms.py can't validate proprely in django
def clean_name(self): valname = self.cleaned_data['name'] # if len(valname) < 3: # raise forms.ValidationError('name must be at least 3 characters') # return valname # return the value if no error if valname[0] == 'S': raise forms.ValidationError('name cannot contain the letter S') return valname # return the value if no error here I apply validation name that should start with S but when I enter a string that can't start with S so it will not give me Validation error. -
Django: Is there any way to acces the User models attribute using request.user.is_authenticated without hitting db?
I have created a middleware in which I have put some if conditions like, if request.user.is_authenticated and request.user.country: when I refresh the page my django debug toolbar shows me some duplicate and similar SQL queries that hits the DB while executing the middleware, so is there any way to access the attributes of the User model using the request.user without hitting the DB? -
AWS The request signature we calculated does not match the signature you provided
i linked s3 to my django app, but after uploading imagges from my website i try to access them i get this error The request signature we calculated does not match the signature you provided. Check your key and signing method. the images were uploaded succesfully to the bucket because i can already see them in the bucket dashboard but i can not access them through the website this is my CORS { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD", "POST", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] -
No Category matches the given query
I am trying to update my products so users can create product and use the checkout to fill form for payment, but when i click on the checkout button i am getting this No Category matches the given query. Here is my code for the Order_create views def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() return render(request, 'products/products/created.html',{'order': order}) else: form = OrderCreateForm() return render(request, 'products/create.html') and here is the URLS for my projects urlpatterns = [ path('product/', include('products.urls', namespace='products')), ] and here is the Order URLS from django.urls import path from . import views app_name = 'products' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), path('create/', views.order_create, name='order_create'), ] When i clcick checkout, i got this error.... Page not found (404) No Category matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/product/create/ Raised by: products.views.product_list -
Django Rest Framework API Performance
I have created an API I plan to list on RapidApi using Django Rest Framework and Heroku. This is my first time creating an API and I am wondering if there is anything I should be taking into consideration as far as performance goes. Do I need more worker dynos? If a lot of people are pulling data will it degrade my sites performance? Will data transfer be slow? I know this question really is opinion based but I am not sure as this is my first time. Thank you for your knowledge and help. -
IntegrityError at /users/create/ | NOT NULL constraint failed: users_post.author_id | Django Web App
I am following web app tutorials from codemy.com Youtube and CS50x. Now, I am trying to add a PostCategoryForm to my create function view for Post model in views.py. views.py def create(request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse("users:login")) if request.method == 'POST': # create new post if request.POST.get('title') and request.POST.get('content'): form = PostCategoryForm(request.POST) form.save() post=Post() post.title = request.POST.get('title') post.content = request.POST.get('content') post.author = request.user post.category = form post.save() return HttpResponseRedirect("/users/posts/{id}".format(id= post.id)) else: form = PostCategoryForm() return render(request, 'users/create.html', { "form": form }) models.py class Post(models.Model): title = models.TextField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() category = models.CharField(max_length=255, default='uncategorized') post_date = models.DateField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('users:home') class PostCategory(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('users:home') forms.py choices = PostCategory.objects.all().values_list('name', 'name') choice_list = [] for item in choices: choice_list.append(item) class PostCategoryForm(forms.ModelForm): class Meta: model = Post fields = ['category'] widgets = { 'category': forms.Select(choices=choice_list) } is there any way to resolve this or should I change my view function to class view? Thanks in advance.. -
Django model field with switching type using Djongo
I want to create a Django model with one field being able to store multiple different types of data. E.g. from djongo import models class DataForms(models.Model): title = models.CharField(max_length=200) description = models.TextField(default=None) items = models.ManyToManyField(Item) class Item(models.Model): NUMERIC = "NUM" TEXT = "TEXT" BOOLEAN = "BOOL" DATE = "DATE" name = models.CharField(max_length=200) description = models.TextField(default=None) ITEM_TYPE_CHOICES = ( (NUMERIC, "Numeric value"), (TEXT, "Text or Characters"), (BOOLEAN, "Yes or No"), (DATE, "Date and Time") ) type = models.TextField( choices=ITEM_TYPE_CHOICES, default=TEXT value = ??????? Note that I am using djongo and a MongoDB at the backend so storing different types of values within the same document should not be an issue, right? In the end the user should be able to choose the type of item he or she wants to create and then add it to the data form. The value field should be either a models.FloatField() or models.TextField() and so on, depending on the choice the user makes. I thought about creating different types of classes inheriting from the Item class like: class NumericItem(Item): value = models.FloatField() And then creating instances of these classes based on the users choices. But it seems to me like this is unnecessary overhead. I … -
DJANGO - create a form that saves to different databases based on choices
I have a project to learn this langage : Create a website that allows their users to add books to a database. So a form with different data. And, according to a form data called "literary movement" the data books are registered in the literary movement category. Then have a page presenting all the literary movements and allow users to click on the different literary movements to have access to the books belonging to these literary movements. I already did the form but i really don't know how to save the data based on the choices of "literary movements". Theses are my codes : Forms.py from django.forms import ModelForm from django.utils.translation import gettext_lazy as _ from . import models class LivreForm(ModelForm): class Meta: model = models.Livre fields = ('titre', 'auteur', 'date_parution', 'nombre_pages','resume', 'mouvement_litteraire') labels = { 'titre' : _('Titre'), 'auteur' : _('Auteur') , 'date_parution' : _('date de parution'), 'nombre_pages' : _('nombres de pages'), 'resume' : _('Résumé'), 'mouvement_litteraire' : _('Mouvement Littéraire') } localized_fields = ('date_parution',) class MouvementForm(ModelForm): class Meta: model = models.Mouvement fields = ('mouvement_litteraire',) labels = { 'mouvement_litteraire' : _('Mouvement Litteraire') } Model.py from django.db import models mouvement_litteraire = ( ('','Nouveau Roman'), ('', 'Surréalisme'), ('','Symbolisme'), ('','Naturalisme'), ('','Réalisme'), ('','Romantisme'), ('','Lumières'), ('','Classicisme'), … -
Return session data from external microservice to Django
I am trying to link an external python script which is kind of like a function webscraping the other domain with the user login data sent from the django views. After the external script is sucessfully ran, the result data will be return back to the django views and show in the page. So far I can sucessfully done the above but as the external python script consist of a part of logging in an external domain and scrape the data. I want the logged-in session from the external script to be returned back to the django then the user can access the data from my page without needing to log in again. Here is my code This is my external python script which consist of using the Requests library def webscrape (email, pwd, dj_req): # use the data from django views to login the other domain and webscrape URL = 'www.login.com' payload = { 'name': email, 'pwd': pwd, } s = dj_req.session() #Trying to utilize the user's request data r1 = s.post(URL, data=payload) list1 = r1.text return list1,s #Return the logged-in session to django views This is my django view from ... import webscrape def inputdata(request): if request.method == … -
Django nested serializer get request shows value from an other model
I would like to create transactions with product quantities, I have this 3 models: class Products(models.Model): name = models.CharField(max_length=100) barcode = models.CharField(max_length=100) price = models.IntegerField(blank=True, default=1) quantity = models.IntegerField(blank=True) def __str__(self) -> str: return self.name class ProductCount(models.Model): barcode = models.ForeignKey( Products, null=True, blank=True, on_delete=models.CASCADE) transaction = models.ForeignKey( Transactions, blank=True, on_delete=models.CASCADE) quantity = models.IntegerField(blank=True, default=1) class Transactions(models.Model): staff = models.ForeignKey( Staff, blank=True, null=True, on_delete=models.CASCADE) services = models.ManyToManyField( Services, through='ServiceCount', related_name="transactions") products = models.ManyToManyField( Products, through='ProductCount', related_name="transactions") costumer = models.ForeignKey( Costumers, blank=True, null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) Serializers: class TransactionSerializer(serializers.ModelSerializer): products = ProductCountSerializer(many=True) services = ServiceCountSerializer(many=True) class Meta: model = Transactions fields = ('id', 'staff', 'products', 'services') def create(self, validated_data): product_data = validated_data.pop('products') validated_data.pop('services') transaction = Transactions.objects.create(**validated_data) for data in product_data: print(data) ProductCount.objects.create(transaction=transaction, **data) transaction.products.add(product_data) return transaction class ProductCountSerializer(serializers.Serializer): quantity = serializers.IntegerField() barcode = serializers.PrimaryKeyRelatedField( queryset=Products.objects.all()) # barcode = ProductSerializer() class Meta: model = ProductCount fields = ['barcode', 'quantity', 'transaction'] class ProductSerializer(serializers.ModelSerializer): class Meta: model = Products fields = ('name', 'price', 'quantity', 'barcode') I do a post request on postman with this data: { "staff": 1, "products": [{"barcode":1 , "quantity":5}, {"barcode":1 , "quantity":3}], "services": [] } This works, but if I want to do a get request on transactions I get this … -
Django KeyError at 'HTTP_HOST'
In my Django project sometimes I get two kinds of errors by mail and I don't know where they are coming from. So far I can see, the user is not logged in. First kind of error: Internal Server Error: / KeyError at / 'HTTP_HOST' File "./core/views/iam.py", line 45, in prepare_django_request 'http_host': request.META['HTTP_HOST'], Exception Type: KeyError at / Exception Value: 'HTTP_HOST' Request information: USER: AnonymousUser Second type of error: Internal Server Error: / OneLogin_Saml2_Error at / SAML Response not found, Only supported HTTP_POST Binding File "var/www/schoolbox/venv/lib64/python3.6/site-packages/onelogin/saml2/auth.py", line 139, in process_response OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND Exception Type: OneLogin_Saml2_Error at / Exception Value: SAML Response not found, Only supported HTTP_POST Binding Request information: USER: AnonymousUser But users are able to login but, or maybe only some, I don't know where this error is coming from. Maybe I need to post more code in order to help me. Any help will be appreciated. -
DRF JSON format
I have created API for News model: models.py class News(models.Model): title = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title serializers.py class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = [ "id", "title", "created_at", ] views.py class NewsViewSet(ModelViewSet): serializer_class = NewsSerializer queryset = News.objects.all() The current result of this API which is below: [ { "id": 1, "title": "testing1", "created_at": "2022-04-02T16:05:08.353708Z", } ] And my question is there any ways to change the response format like below? I can not figure out how to make with Django DRF. { "status": 0, "message": "Success", "data": { "updatedAt": "2020-08-31 17:49:15", "serverTime": "2022-03-23 15:10:11", "news": [ { "id": 1, "title": "testing1", "created_at": "2022-04-02T16:05:08.353708Z", } ] } } -
after login django-allauth login page doesn't show good?
On my django project,I added django-alluth for google login.But after click google login button in my login.html,the page which will login is: after I clicked continue button google login the page is shownn at the bottom: I want to from here,At my login template when I clicked to login with google button directly second piture will be shown.How can I do that? Because first picture doesn't look good.I want to directly jump the other image. -
React fetch request is blocked by Django backend due to "origin forbidden"
I have a Django view that processes a contact message which I want to call via a fetch request from my React frontend. However, it returns the following error: Forbidden (Origin checking failed - http://localhost:3000 does not match any trusted origins.): /send-contact-message/ # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'applications.api', 'applications.core', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] I also tried CORS_ORIGIN_ALLOW_ALL = True which returns the same error. ContactForm.js const ContactForm = () => { const [formData, setFormData] = useReducer(formReducer, {}); const [submitting, setSubmitting] = useState(false); const submitHandler = event => { event.preventDefault(); setSubmitting(true); fetch('http://127.0.0.1:8000/send-contact-message/', { method: 'POST', body: JSON.stringify({ formData }), headers: { 'Content-Type': 'application/json' }, }) .then(res => res.json()) .then(json => setSubmitting(false)); } ... -
drf-spectacular extend_schema_serializer can't do empty value example
I'm using the extend_schema_serializer decorator to document examples of json data that can be sent in a POST request. The problem is, one of the variations/examples requires no data, but the generated swagger doc insists on showing what looks like an auto-generated default with all possible params. This isn't ideal when I'm trying to demonstrate the most simple examples. I have this for the serializer. @extend_schema_serializer( examples=[ OpenApiExample( 'Simple example', value={}, request_only=True, response_only=False, ), OpenApiExample( 'Single param example', value={ 'mult': 3, }, request_only=True, response_only=False, ), ], ) class RollChartSerializer(serializers.Serializer): mult = serializers.IntegerField(required=False, write_only=True) input_vars = serializers.DictField(required=False, write_only=True) foo_name = serializers.CharField(source="foo", allow_null=True, read_only=True) foo_url = ChartAbsoluteUrlField(source="foo.id", allow_null=True, read_only=True) results = serializers.StringRelatedField(many=True, read_only=True) ... Where I have value={}, I've also tried value=None and have tried removing it altogether. In all cases, the 'example value' in swagger showing. { "mult": 0, "input_vars": { "additionalProp1": "string", "additionalProp2": "string", "additionalProp3": "string" } } Is there something I'm missing? I did notice that the generated redoc docs show null. For the second example, swagger correctly shows { "mult": 3 } -
Django auth groups not finding groups and does not give permission to users, regardless of the group in which they are
I'm making a simple real estate app where the users must be separated into two different groups. A regular user and a broker. I'm using the Django admin backend for creating user groups. I'm also using a post_save signal to assign all the new users to the regular users' group. At first glance, it works well and in Django admin, it shows me that the user is in the corresponding group. But when I try to print self.request.user.groups the value is None. Also when I try to check if users have permission to do something, regardless of the permissions I gave the view I check always gives me 403 Forbidden regardless of whether the user has permission or not. I use class-based views and PermissionRequiredMixin respectively. Here is my user model: class DjangoEstatesUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): USERNAME_MAX_LENGTH = 30 username = models.CharField( max_length=USERNAME_MAX_LENGTH, unique=True, ) date_joined = models.DateTimeField( auto_now_add=True, ) is_staff = models.BooleanField( default=False, ) USERNAME_FIELD = 'username' objects = DjangoEstatesUserManager() Also the signal for assigning the new users to a group: @receiver(post_save, sender=DjangoEstatesUser) def create_user_profile(sender, instance, created, **kwargs): if created: instance.groups.add(Group.objects.get(name='Users')) and this is one view that I'm trying to restrict for different users: class AddEstateView(auth_mixins.LoginRequiredMixin, auth_mixins.PermissionRequiredMixin, views.CreateView): permission_required = 'main_estate.add_estate' … -
Using Models and Views in Django
I need help with a project in Django. In views.py I have created a login to the site including registration, but I need to somehow use models.py to edit and add more user parameters, which I don't think is possible in views. Can someone please help me with this. I am attaching the code below. views.py from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from rocnikovka import settings from django.core.mail import EmailMessage, send_mail from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode from django.utils.encoding import force_bytes, force_str from . tokens import generate_token def home(request): return render(request, "authentication/home.html") def signup(request): if request.method == "POST": # username = request.POST.get("username") username = request.POST["username"] fname = request.POST["fname"] lname = request.POST["lname"] email = request.POST["email"] pass1 = request.POST["pass1"] pass2 = request.POST["pass2"] if User.objects.filter(username=username): messages.error(request, "Username already exist! Please try some other username.") return redirect("home") if User.objects.filter(email=email).exists(): messages.error(request, "Email Address already registered! ") return redirect("home") if len(username)>20: messages.error(request, "Username must be under 20 characters.") return redirect('home') if pass1 != pass2: messages.error(request, "Passwords did not match") return redirect('home') if not username.isalnum(): messages.error(request, "Username must be Alpha-numeric!") return redirect("home") myuser = … -
Django Graphene union of 3 tables
I am programming a website using Django and using Graphene to implement GraphQL. I have three tables that contain different products types and would like to return a query that aggregates those three tables together. So that the products returns are all in a single nest in the response. class Cards(DjangoObjectType): class Meta: model = magic_sets_cards fields = ['name'] class Tokens(DjangoObjectType): class Meta: model = magic_sets_tokens fields = ['name'] class Sealed(DjangoObjectType): class Meta: model = magic_sets_sealed_products fields = ['name'] class MagicSearchTestUnion(graphene.Union): class Meta: types = (Cards, Tokens, Sealed) @classmethod def resolve_type(cls, instance, info): if isinstance(instance, magic_sets_cards): return Cards if isinstance(instance, magic_sets_tokens): return Tokens if isinstance(instance, magic_sets_sealed_products): return Sealed return MagicSearchTestUnion.resolve_type(instance, info) class MagicSearchTestQuery(graphene.ObjectType): magic_search_cards = graphene.List(MagicSearchTestUnion) @staticmethod def resolve_magic_search_cards(self, info, search=''): cards = magic_sets_cards.objects.filter(name=search).all() tokens = magic_sets_tokens.objects.filter(name=search).all() sealed = magic_sets_sealed_products.objects.filter(name=search).all() return list(chain(cards, tokens, sealed)) magicSearchTestSchema = graphene.Schema(query=MagicSearchTestQuery) This seems to work fine without errors and I am able to access the GraphQL GUI, but there is not the expected fields in the query. { magicSearchCards { __typename } } The above is all the fields that seem to be available to me. -
TypeError: Object of type Tag is not JSON serializable
I am trying to send my result as JsonResponse but when I run the function then it is showing every time TypeError: Object of type Tag is not JSON serializable views.py def saveJson(request): response = getReturnedData() results = [] for result in response: results.append({'json': result}) return JsonResponse({'results': results}) returned data from getReturnedData() is :- Note :- "Image1" is not the real data I got in list BUT it is a link of image url (not string), I didn't post it because stackoverflow was showing spam while posting img links [ "Image1", "Image1" ] converted from for loop is :- [ { 'response': [ "Image1", "Image2" ] } ] I have also tried by using json.dumps but it returns nothing And I also tried using data = serializers.serialize("json", results) but it showed 'NoneType' object has no attribute 'concrete_model I have tried hours but it didn't work, Any help would be much Appreciated. Thank You in Advance -
users (except come from createsuperuser) cannot login to web app
I have registration page and login page. Users who registrated cannot login in login page. It always return else block which is redirecting HttpResponse('error'). Could you please help me? note: users successfully registrated (can be seen in database) and they are all active users. note2: only users who created from createsuperuser can login at login.html. others cannot. in views.py def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: auth_login(request, user) return HttpResponseRedirect(reverse('users:home')) else: print("error") return HttpResponse('error') else: return render(request, 'auth/login.html', {}) in urls.py from django.urls import path from users import views app_name = 'users' urlpatterns = [ path('', views.home, name='home'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), ] in login.html {% extends 'base.html' %} {% block title %} Login {% endblock %} {% block head %} {% endblock %} {% block content %} <div class="container"> {% if user.is_authenticated %} <h1>You have already signed in</h1> {% else %} <h2>Login Page</h2> <form action="{% url 'users:login' %}" method="POST"> {% csrf_token %} <label for="username">Username:</label> <input type="text" name="username"><br> <br> <label for="password">Password:</label> <input type="password" name="password"><br> <br> <input type="submit" class="btn btn-primary" value="Login"> </form> {% endif %} </div> {% endblock %} I would be grateful if anyone help … -
Python panel (bokeh) server connection display empty html page without error message
I have a Django project where one view function start a bokeh server by a python script. Popen(["panel", "serve", "/opt/bitnami/projects/blog/EnviAI/scripts/visz_pn_ssm_1.py", "--show"]) With another view, I try to connect to the server and display the dashboard from visz_pn_ssm_1.py . def redirect_bokeh_server(request): session = pull_session(url="http://localhost:5006/visz_pn_ssm_1") script = server_session(model=None,session_id=session.id,url="http://localhost:5006/visz_pn_ssm_1") return render(request, 'dashboard_ssm.html', {'script' : script}) in my dashboard_ssm.html <body> {{script | safe}} </body> From the console i get: Starting Bokeh server version 2.4.2 (running on Tornado 6.1) 2022-04-03 08:26:03,800 User authentication hooks NOT provided (default user enabled) 2022-04-03 08:26:03,804 Bokeh app running at: http://localhost:5006/visz_pn_ssm_12022-04-03 08:26:03,804 Starting Bokeh server with process id: 269292022-04-03 08:26:06,550 WebSocket connection openedtest2022-04-03 08:26:07,762 ServerConnection created But the page is empty? The content of my panel script visz_pn_ssm_1.py: import pandas as pd import geopandas as gpd import panel as pn import hvplot.pandas import pickle pn.extension() pn.config.js_files = {'deck': 'https://unpkg.com/deck.gl@~5.2.0/deckgl.min.js'} pn.config.css_files = ['https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css'] with open ('/opt/bitnami/projects/data/filepath_ssm_user.pickl', 'rb') as temp: res = pickle.load(temp) # ried soil samples 30m 17-19 gdf = pd.read_csv(f'/opt/bitnami/projects/data/tables/{res[0]}' ,)[['date', 'ssm']].dropna().reset_index(drop=True) gdf['date'] = gdf['date'].astype('datetime64[ns]') #Options for Widgets years = gdf.date.dt.year.unique() # Widgets year_slider = pn.widgets.IntSlider(name = 'Year', start=int(years.min()), end=int(years.max()), value=int(years[0])) @pn.depends(year_slider) def plot_data(year_slider): data_select = gdf[gdf['date'].dt.year == year_slider] # Scatter Plot scatter = data_select.hvplot.scatter( x = 'date', y = … -
Fork() crashes Python in Mac OS Monterey
I'm running Djangorq on my virtualenv with python 3.8.6 as follows export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES;sudo python manage.py rqworker --with-scheduler When I call any function as django_rq.enqueue(func, request.user,arg=arg1) Python crashes and I get this on my console: +[NSPlaceholderString initialize] may have been in progress in another thread when fork() was called. objc[78776]: +[NSPlaceholderString initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug. 12:33:17 Moving job to FailedJobRegistry (work-horse terminated unexpectedly; waitpid returned 6) Before Monterey, I used to solve it with export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES But this doesn't seem to work anymore. Any idea how to fix this? -
Getting "CSRF token missing or incorrect" on obtain token request
We are using Django REST Framework and we are using user logins. From a web client we have a login screen and use obtain_auth_token from the REST Framework to obtain an api token. The web client uses XMLHttpRequest. It starts out with working fine. The web client obtains a token using username+password and uses that token in the following API calls. When I return the next day and open a new browser tab and try to log in I get a 403 Forbidden and the Django logs (and the body reply) says {"detail":"CSRF Failed: CSRF token missing or incorrect."} I can see that the incoming request has a csrftoken cookie and a sessionid cookie. I can see the same cookies if I use the browser "Developer Tools". If I remove those two cookies, it works fine afterwards. Also, if I launch a private browser window (= incognito), the web app works fine. I am do not know why those cookies appear, when they appear exactly and why the REST framework do not like them. I have two suspicions: We also use the Django admin interface. Could it be that the login to the admin interface on the same domain will … -
why increasing worker numbers increase request time in gunicorn, wsgi, django
I am using gunicorn with wsgi and django for my rest beckend app. When I used gunicorn with one sync worker and send 20 same parallel requests, request execution time is about 100ms. When I increased number of workers to 4 and do the same thing execution time of request is four time bigger. I am using AWS and my app is in docker. How this could be possible? Should times be the same in both cases? -
Login action not working in django, csrf token is missing or forbidden
when the login button is clicked it only refreshes the page it is not performing the function loginAction even i cant print the details that i write in that function. HTML page {% csrf_token %} <div class="row"> <div class="col-md-6 wow fadeInLeft" data-wow-duration="2s" data-wow-delay="600ms"> <div class="form-group"> <input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-validation-required-message="Please enter your email address."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="password *" id="phone" name="phone" required data-validation-required-message="Please enter your password."> <p class="help-block text-danger"></p> </div> <div class="col-lg-12 text-center wow zoomIn" data-wow-duration="1s" data-wow-delay="600ms"> <button type="submit" class="btn btn-primary">login</button> </div> </div> <div class="col-md-6 wow fadeInRight" data-wow-duration="2s" data-wow-delay="600ms"> <div class="form-group"> <img src="/static/asset/images/flickr/capture.jpg" height="330px" width="200px"> </div> </div> </div> </div> </div> </form> def loginAction(request): if request.method == 'POST': #print("email") email = request.POST["email"] password = request.POST["password"] user = register_tb.objects.filter(email=email, password=password) if user.count()> 0: return render('home.html',{'msg':"login success "}) else: return render ("login.html",{'msg':"login failed "})