Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I pass a Django url parameter to template's url method?
I have this urls.py file: ... urlpatterns = [ path('region_service_cost/<str:region>/', views.region_service_cost, name='region_service_cost'), path('monthly-region-service-cost/<str:region>/', views.monthly_region_service_cost, name='monthly-region-service-cost') ] And I have this views.py file: # Create your views here. from django.shortcuts import render from django.http import JsonResponse from .models import MonthlyRegionServiceCost def region_service_cost(request, region): return render(request, 'region-service-cost.html') def monthly_region_service_cost(request, region='global'): colors = ['#DFFF00', '#FFBF00', '#FF7F50', '#DE3163', '#9FE2BF', '#40E0D0', '#6495ED', '#CCCCFF', '#9CC2BF', '#40E011', '#641111', '#CCCC00'] labels = [ym['year_month'] for ym in MonthlyRegionServiceCost.objects.values('year_month').distinct()][:12] datasets = [] for ym in labels: for i, obj in enumerate(MonthlyRegionServiceCost.objects.filter(region=region, year_month=ym)): dataset = { 'label': obj.service, 'backgroundColor': colors[i % len(colors)], 'data': [c.cost for c in MonthlyRegionServiceCost.objects.filter(service=obj.service, region=region)] } datasets.append(dataset) return JsonResponse(data={ 'labels': labels, 'datasets': datasets }) and here is my region-service-cost.html file: {% extends 'base.html' %} {% block content %} <div id="container" style="width: 75%;"> <!-- canvas id="monthly-region-service-cost" data-url="{% url 'monthly-region-service-cost' %}/{{ region | urlencode }}/"></canvas --> <canvas id="monthly-region-service-cost" data-url="{% url 'monthly-region-service-cost' region=region %}/{{ region | urlencode }}/"></canvas> </div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> $(function () { var $productCostChart = $("#monthly-region-service-cost"); $.ajax({ url: $productCostChart.data("url"), success: function (data) { console.log(data); var ctx = $productCostChart[0].getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets: data.datasets, }, options: { plugins: { title: { display: true, text: 'Stacked Bar chart for pollution status' … -
Encryption for passing password from Frontend to backend in Django Application
I am working on Django Project and I want to setup authentication using LDAP backend. I have a form in UI where user will be able to enter user name and password and this will be passed to LDAP backend for authentication. While passing data from UI form to LDAP backend. DO I have to use any encryption technique? If yes, what kind of and how? Thank you. -
importing via Pandas CSV into Django model manytomanyfield
Total newbie to Django. I decided to put my hand up at work to develop a small POC app but cannot seem to get past importing csv data via Pandas into my Django model manytomanyField. Everything else is working except for the m2m field. Here is a portion of my model: class Service_Interval(models.Model): interval_name = models.CharField(null=True, max_length=200) class Task(models.Model): service_intervals = models.ManyToManyField(Service_Interval, related_name="intervals") Here is my View: def Import_Excel_pandas(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request. FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) #exceldata = pd.read_csv(filename, index_col ="Requirements") df=pd.read_csv('sheets/import_csv/'+filename, sep=',', usecols=['ID','Requirements','Service Intervals','Task Created']) #print(df) row_iter = df.iterrows() objs = [ Task( id = row['ID'], requirements = row['Requirements'], task_created = row['Task Created'], #service_intervals = row['Service Intervals'], << - dont work. ) for index, row in row_iter ] Task.objects.bulk_create(objs) Here in some of the CSV: enter image description here I think I need to connect to connect/create in Service_Interval first then add to Tasks inside the loop somewhere, but I'm stuck on how/where to add the code within the object task and if the process is correct. Any help would be appreciated as I've been stuck on this for a while now. intervals = row['Service Intervals'] … -
Issues with sending forgot passwords links with Django + AWS SES
I'm trying to add a feature on my Django App to send users who forgot their passwords a link to reset them via email. I'm not sure if I have set up my password reset email feature correctly, or if my AWS SES isn't configured to it. I have successfully sent email with a verified email in django shell with the method: send_mail('title','message','fromsender@mail.com',['toreciever@mail.com]) Which means that I have configured my environment variables correctly, but incase you need to see it: Here's my Django Settings.py: AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'us-east-2' AWS_SES_REGION_ENDPOINT = 'email.us-east-2.amazonaws.com' Here are my files views.py: from re import search from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import SignUpForm, AddRecordForm, RecordFilterForm, CustomUserChangeForm, CustomPasswordChangeForm from .models import Record from django.db.models import Q from django.views.decorators.http import require_http_methods from django.http import JsonResponse from django.contrib.auth.forms import UserChangeForm from django.core.exceptions import ValidationError from django.contrib.auth import update_session_auth_hash from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger #here is the homepage containing all the search filters def home(request): records = Record.objects.all().order_by('created_at') search_form = RecordFilterForm(request.GET) if search_form.is_valid(): search_query = search_form.cleaned_data.get('search') university_filter = search_form.cleaned_data.get('university_filter') course_name_filter = search_form.cleaned_data.get('course_name_filter') is_paid_filter = search_form.cleaned_data.get('is_paid') … -
django orm - multipule connections to postgesql
i have next code (django model) class AgentNmapTask(NmapTask): def execute(self): self.condition = ConditionTypes.LAUNCHED self.save() self.send_request_to_server('put', '/api/server/nmap/tasks/update/', { 'status': self.condition, 'id': self.id, 'count_of_launches': self.count_of_launches, 'next_run': self.next_run }) results, error = super().execute() if error: agent_nmap_result: AgentNmapResult = AgentNmapResult.objects.create(task=self, error=error) else: agent_nmap_result: AgentNmapResult = AgentNmapResult.objects.create(task=self, result=results) self.send_request_to_server('put', '/api/server/nmap/tasks/update/', { 'status': self.condition, 'id': self.id, 'count_of_launches': self.count_of_launches, 'next_run': self.next_run }) self.send_request_to_server('post', '/api/server/nmap/results/', {'nmap_task_id_on_agent': self.id, **model_to_dict(agent_nmap_result)}) i do next test for i in range(10): self.assertEqual(self.client.post( '/api/agent/nmap/tasks/', data={ 'ip_range': f'127.0.0.{i}', 'arguments': '-p0-1000 -Pn', 'company': f'test', }, format='json', ).status_code, 201) self.assertEqual(self.client.post( '/api/agent/nmap/tasks/', data={ 'ip_range': f'127.0.0.{i}', 'arguments': '-p0-1000 -Pn', 'company': f'test123', }, format='json', ).status_code, 201) def execute_task(agent_nmap_task): agent_nmap_task.execute() agent_nmap_tasks = AgentNmapTask.objects.all() executor = concurrent.futures.ThreadPoolExecutor(max_workers=10) future_tasks = [executor.submit(execute_task, agent_nmap_task) for agent_nmap_task in agent_nmap_tasks] concurrent.futures.wait(future_tasks) nmap_result_list = self.client.get('/api/agent/nmap/results/', format='json').json() self.assertEqual(len(nmap_result_list), 20) But when i start paralell processing by concurrent.futures.wait, python don't contunie test. Looks like it or postgesql locked . I see in "ps aux" next: postgres 65905 0.1 0.3 675020 29416 ? Ss 23:38 0:00 postgres: user test_scanner_db ::1(54510) idle in transaction postgres 65920 0.0 0.2 672076 19588 ? Ss 23:38 0:00 postgres: user test_scanner_db ::1(54408) INSERT waiting postgres 65922 0.0 0.2 672076 19576 ? Ss 23:38 0:00 postgres: user test_scanner_db ::1(54422) INSERT waiting postgres 65923 0.0 0.2 672076 19460 … -
How can I generate an annotated field with list of values in Django queryset?
I need to make up an advanced query that allows me get a queryset containing dictionaries with strings for keys and lists with all possible values for values. Here is what I got: ``` In [26]: Offer.objects.values('partner', 'partner_id') Out[26]: <QuerySet [{'partner': 'xex', 'partner_id': 'x_999'}, {'partner': 'xex', 'partner_id': 'x_888'}, {'partner': 'quiup', 'partner_id': 'q_888'}, {'partner': 'quiup', 'partner_id': 'q_777'}]> ``` Here is what I need to get: ``` <QuerySet [{'partner': 'xex', 'partner_ids': ['x_999', 'x_888']}, {'partner': 'quiup', 'partner_ids': ['q_888', 'q_777']} ``` I've tried annotations, F-expressions, `Value`, `.dictinct('partner')` but nothing brings me any closer. Any suggestions will be much appreciated and thank you very much for your attention. -
Issue with Django's LoginView after customizing User Model
I've encountered an issue after customizing Django's built-in User model (AbstractUser). I've created a custom user model named TheUser which inherits from AbstractUser. After making this change, the built-in LoginView from django.contrib.auth.views seems unable to authenticate users, even though the user data exists in the MySQL database. Here's a simplified overview of my code structure: models.py: from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField # Create your models here. choices = ( ('M', 'Men'), ('F', 'Female'), ('P', 'Personnalised'), ) class TheUser(AbstractUser): age = models.IntegerField(blank=True, null=True) genre = models.CharField(max_length=10, choices=choices, default='M') adress = models.OneToOneField('UserAdress', on_delete=models.CASCADE, null=True) phone_number = PhoneNumberField(null=True) class UserAdress(models.Model): country = models.CharField(max_length=20) city = models.CharField(max_length=20) I've defined a custom user model named TheUser which includes additional fields like age, genre, phone_number, and a one-to-one relationship with UserAdress. urls.py: from django.urls import path, include from django.contrib.auth import views as auth_views from .forms import userForm form = userForm() app_name = 'user' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='registration/login.html', context={'form': form}), name='login'), path('', include('django.contrib.auth.urls')), ] The login URL is configured to use Django's LoginView with a custom login template (login.html). Other URLs for signup, logout, and profile are also defined. forms.py: from django import forms from .models import TheUser from … -
relation "forum_forum" does not exist - Django Machina
I've been looking at documentation to install django-machina to use their forum capabilities. After following the quickstart guide I've run into an issue after makemigrations and migrate. relation "forum_forum" does not exist I've tried looking through the lib files of the package and doesn't seem to be wrong. I've tried to uninstall and reinstall but nothing has been working. """ Django settings for games_backend project. Generated by 'django-admin startproject' using Django 5.0.2. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from datetime import timedelta import environ import os from pathlib import Path from decouple import config from machina import MACHINA_MAIN_STATIC_DIR from machina import MACHINA_MAIN_TEMPLATE_DIR env = environ.Env( DEBUG=(bool, True) ) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent environ.Env.read_env(BASE_DIR / '.env') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'dasdddadsdadadsdd' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_ALLOW_CREDENTIALS = True # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.sitemaps', … -
i am recieving messages in my console but not in my notifications tab
i am using fcm to send push notificationsn in my django web app , i am recieving messages in my console but not in my notifications tab Message received. {from: '768143683456', collapseKey: 'campaign_collapse_key_3868676707069520118', messageId: 'c4a67ffd-5790-45a2-a339-64dad41dc i am tryng to get push notifications in laptop notifications but recieving only in console -
How to use ModelSerializer and serializer field on ModelSerializer?
serializer # serialize serializer = GetDealsResponseSerializer( data={ "deals": [model_to_dict(deal) for deal in deals], "is_remained": is_remained, } ) serializer.is_valid(raise_exception=True) # serializers class DealSerializer(serializers.ModelSerializer): area_for_exclusive_use_pyung = serializers.SerializerMethodField( "convert_square_meter_to_pyung" ) area_for_exclusive_use_price_per_pyung = serializers.SerializerMethodField( "calc_price_per_pyung" ) is_deal_canceled = serializers.SerializerMethodField("calc_is_deal_canceled") floor = serializers.SerializerMethodField("stringify_floor") def __init__(self, instance=None, data=..., **kwargs): super().__init__(instance, data, **kwargs) self.area_for_exclusive_use_pyung = None class Meta: model = Deal fields = ( "id", "deal_price", "brokerage_type", "deal_year", "land_area", "deal_month", "deal_day", "area_for_exclusive_use", "floor", "is_deal_canceled", "deal_canceled_date", "area_for_exclusive_use_pyung", "area_for_exclusive_use_price_per_pyung", "deal_type", "real_estate_id", ) def convert_square_meter_to_pyung(self, instance) -> Decimal: self.pyung = round( Decimal(instance.area_for_exclusive_use) / Decimal(3.305785), 2 ) return self.pyung def calc_price_per_pyung(self, instance) -> Decimal: return round(instance.deal_price / self.pyung, 2) def calc_is_deal_canceled(self, instance) -> bool: if instance.is_deal_canceled == "O": return True return False def stringify_floor(self, instance) -> str: self.floor = str(instance.floor) return self.floor class GetDealsResponseSerializer(DealSerializer): deals = DealSerializer(many=True) is_remained = serializers.BooleanField(required=False) class Meta: model = Deal fields = ( "id", "deal_price", "brokerage_type", "deal_year", "land_area", "deal_month", "deal_day", "area_for_exclusive_use", "floor", "is_deal_canceled", "deal_canceled_date", "area_for_exclusive_use_pyung", "area_for_exclusive_use_price_per_pyung", "deal_type", "real_estate_id", "deals", ) Error rest_framework.exceptions.ValidationError: {'deal_price': [ErrorDetail(string='This field is required.', code='required')], 'deal_year': [ErrorDetail(string='This field is required.', code='required')], 'land_area': [ErrorDetail(string='This field is required.', code='required')], 'deal_month': [ErrorDetail(string='This field is required.', code='required')], 'deal_day': [ErrorDetail(string='This field is required.', code='required')], 'area_for_exclusive_use': [ErrorDetail(string='This field is required.', code='required')], 'deal_type': [ErrorDetail(string='This field is required.', code='required')]} schema for … -
Debugger not stop on breakpoint
I'm trying to debug my Docker Django app with this configuration. launch.json: { "version": "0.2.0", "configurations": [ { "name": "Docker: Python - Django", "type": "python", "request": "attach", "connect": { "port": 5678, "host": "0.0.0.0", }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/project" } ], "django": true, "justMyCode": false } } docker-compose.debug.yml.py: ... django: extends: file: docker-compose.yml service: django command: sh -c "DEBUG_MODE=True python manage.py runserver 0.0.0.0:8000 --noreload" ports: - "5678:5678" manage.py: ... if os.environ.get("DEBUG_MODE", False): import debugpy debugpy.listen(("0.0.0.0", 5678)) debugpy.wait_for_client() I run docker compose with the debug file, the program waits to execute the vscode configuration but when I go to url the execution does not stop at the breakpoint. Output: Debugger warning: It seems that frozen modules are being used, which may make the debugger miss breakpoints. Please pass -Xfrozen_modules=off to python to disable frozen modules. Changing the command sh -c "DEBUG_MODE=True python -Xfrozen_modules=off manage.py runserver 0.0.0.0:8000 --noreload"doesn´t work either. Any sugestion? -
Second celery task in chain executing before database updates from first task are completed
I have a a chain of celery tasks and the second task needs to run, not just after the first task is complete, but after the database updates from the first task are complete. I've managed to get this working in my test by using a while loop to wait for the first chord in the chain to end but that seems wrong. I've tried other things like transaction.on_commit but that didn't work either. What's the right way to do this so that there isn't a race condition? # My simple model class TestModel(BaseModel): # The datetime the item occurred occurred_at = models.DateTimeField(null=False, blank=False, db_index=True) # A fake quantity quantity = models.DecimalField( max_digits=20, decimal_places=10, null=True, blank=True ) @shared_task def race_condition_tester() -> None: zulu = dateTime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') workflow = chain( # This chord should asynchronously write a bunch of things to the database chord( generate_list_of_test_items.s( zulu=zulu, ), spawn_tasks_from_list_of_test_items_and_write_each_item_to_database.s(), ), # This should run after the chord, but also needs to run after the database # updates are complete test_if_items_are_in_database.s( zulu=zulu, ), ) workflow.apply_async() return None @shared_task def generate_list_of_test_items( results=None, zulu: str = None, ) -> List: logger.info(f"generate_list_of_test_items: {zulu=}") task_param_lists = [] for i in range(10): task_param_lists.append([i, zulu]) return task_param_lists @shared_task def spawn_tasks_from_list_of_test_items_and_write_each_item_to_database( … -
Django might not found api endpoint with slug
I have ViewSets with using action decorator. All actions with slug work. But there is one action which return Page not found class DefectImageViewSet(GenericViewSet): queryset = DefectImage.objects.all() serializer_class = DefectImageListSerializer @action( methods=['get'], detail=False, url_path='<uuid:defect_id>', # This method not work in current case, # but I using this definition method of slug everywhere # and it work # url_path=r'(?P<defect_id>[^/.]+)', # This is work in current case url_name='image-list' ) def get_list(self, request, defect_id): queryset: QuerySet = self.get_queryset() queryset = queryset.filter(defect_id=defect_id) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I tried to remove slug and set default value and all work, but as soon as I add a slug, it returns Page not found -
Using django signals to update status of multiple models
I'm currently working on a Django project where I have models for ClientOrders, DesignerJob, and PrinterJob. I want to implement a functionality where changes in the status of DesignerJob and PrinterJob models trigger updates to the status of the associated ClientOrders model. For example, when the status of a DesignerJob changes from "new" to "in_progress," I want the status of the corresponding ClientOrders model to be updated to a specific status. Similarly, when the status of a PrinterJob changes, I want the associated ClientOrders status to be adjusted accordingly. I'm planning to use Django signals to achieve this, but I want to make sure I follow best practices and avoid potential pitfalls.Here are my specific questions: Signal Handling Approach: Should I use one signal for each model and implement all the conditions in that signal or make separate signals for each case? Circular Signal Calling: If I have a case where say PrinterJob signal updates DesignerJob status, will it cause circular calling? But this case is very unlikely. class ClientOrders(models.Model): franchise = models.ForeignKey( Franchise, on_delete=models.CASCADE, null=True) order_id = models.CharField(max_length=100, default=0 , unique=True) order_type = models.CharField(max_length=50, default='shop') payment_method = models.CharField(max_length=50, default='cash') card_no = models.CharField(max_length=16, default='', blank=True) expiry = models.CharField(max_length=50, default='', blank=True) … -
Error when trying to install Django using pip on Windows [duplicate]
I am new to Python and trying to install Django framework on my Windows machine using pip. However, I'm encountering the following error: pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + pip install django + ~~~ + CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I'm not sure what this error means and how to resolve it. Can someone please guide me on how to fix this issue? Keep in mind that I'm a beginner and may need detailed instructions. Thank you in advance for your help! #python, #django, #pip, #windows, #installation, #beginner Its a screen-shot of erorr -
How do I load a django template using absolute paths?
I have a template xyz.html stored in the path /doc-templates/ so the full path is /doc-templates/xyz.html I'm trying to load the template using my_template = get_template('/doc-templates/xyz.html') But this raises the TemplateDoesNotExist exception. Any ideas before I roll out my own template loader? PS: Yes I know where Django templates should be, I just want to see if this is possible now that everything is being "dockerized" I have explicitly enabled django.template.loaders.filesystem.Loader and set the DIRS to a non empty list as documented but it seems to be ignoring the absolute path (possibly appending it to the DIRS list) -
django admin foreignkey icons not active
In the django admin (4.2) I can find in case of foreignkey fields the icons for editing, adding, deleting and viewing the relevant foreignkey element. However, only the add button is active in my case. How can I activate the other icons= -
Issue with Google login using Django allauth: Not prompted to select Google account in Incognito mode or certain browsers (opera, Edge)
I'm using Django allauth for Google login in my web application. Everything works fine, but I've encountered an issue where when users try to log in using Google in Incognito mode or with certain browsers like Opera or Edge, they are not prompted to select a Google account. Instead, it automatically logs in with the previously logged-in Google account. Here's a snippet of my settings in settings.py: SITE_ID = 1 SOCIALACCOUNT_ADAPTER = 'microdistribution.users.adapters.CustomSocialAccountAdapter' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' SOCIALACCOUNT_LOGIN_ON_GET=True ACCOUNT_LOGOUT_ON_GET = True SOCIALACCOUNT_EMAIL_AUTHENTICATION = True ACCOUNT_SESSION_REMEMBER = False SOCIALACCOUNT_PROVIDERS = { 'google': { 'AUTH_PARAMS': {'access_type': 'online'}, } } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'allauth.account.middleware.AccountMiddleware', #new 'microdistribution.utils.middleware.DynamicSiteMiddleware', #new ] INSTALLED_APPS = [ 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] Custom Adapter im using class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form=None): user = sociallogin.user # Check if the user already exists existing_user = self.get_existing_user(user) if existing_user: return existing_user # If the user doesn't exist, create a new one try: new_user = super().save_user(request, sociallogin, form) new_user.name = sociallogin.account.extra_data.get('name') new_user.client_uid_id = User.objects.get(id = settings.CLIENT[request.META['HTTP_HOST']].client_uid_id) new_user.save() return new_user except Exception as e: print(f"Error While Creating User: {e}") return None def get_existing_user(self, user): existing_user = None try: … -
React & Django - WARNING:django.request:Forbidden: /api/user - SessionAuthentication
I'ved created this Django & React project (https://github.com/axilaris/docker-django-react-celery-redis), and I'm having difficulties with accessing API with SessionAuthentication. You can easily spin off with: docker-compose build docker-compose up I keep getting access issue with accessing /api/user (you can test with register, login) backend_container | Forbidden: /api/user backend_container | WARNING:django.request:Forbidden: /api/user You can look more the logs here: https://gist.github.com/axilaris/7b7a5c50f4f7112b440eaf8ef8100d9d In my django api code (backend/user_api/views.py): class UserView(APIView): permission_classes = (permissions.IsAuthenticated,) authentication_classes = (SessionAuthentication,) def get(self, request): serializer = UserSerializer(request.user) return Response({'user': serializer.data}, status=status.HTTP_200_OK) In settings.py: CORS_ALLOWED_ORIGINS = [ 'http://localhost', 'http://127.0.0.1', 'http://0.0.0.0', ] CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = [ .. 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] and in react: axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.withCredentials = true; useEffect(() => { client.get("/api/user") .then(function(res) { setCurrentUser(true); }) .catch(function(error) { setCurrentUser(false); }); }, []); why whenever after I login and I reload back localhost on the browser it has forbidden /api/user and goes back to the login page. I feel the CORS are setup correctly and credentials are set true on both backend and frontend. -
Django Model Choice Form display logo + name
How to make a form populated from a database values to display the image from the URLField (team.logo) and the name (team.name) next to it. I am trying to achieve this through the following code but it ignores the image display part and only shows the team name: class TeamModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, team): return format_html(f'<img src="{team.logo}" class="form-logo">{team.name}') class TeamChoiceForm(forms.Form): teams_extra = Team.objects.all() team_home = TeamModelChoiceField( queryset=teams_extra, empty_label="Team Home" ) team_away = TeamModelChoiceField( queryset=teams_extra, empty_label="Team Away" ) -
Bad Request: /dj-rest-auth/google/ . Request Failed with status code 400
With dj-rest-auth, google login, I keep getting Request failed with status code 400 and cant figure out what's wrong. All the other API end points are working, except for social login. The page redirects to Google Signup Page, and then the URL also contains the "key", but doesnt seem to login for some reason. Kindly help. //Action.js export const googleLogin = ( code ) => async dispatch => { if ( !localStorage.getItem('access') ) { const config = { headers: { "Content-Type": "application/json" } }; const body = JSON.stringify({ code }) try { const res = await axios.post("http://localhost:8000/dj-rest-auth/google/", body, config) dispatch ({ type: TYPE.LOGIN_SUCCESS, payload: res.data }) } catch (err) { dispatch ({ type: TYPE.LOGIN_FAIL, error: err.message }) } } else { dispatch( verify() ); dispatch( getUser() ); } } //reducer.js const AuthReducer = (state=initialState, action) => { const { type, payload } = action; switch (type) { case TYPE.LOGIN_SUCCESS: localStorage.setItem('access', payload.access); return { ...state, access: payload.access, isAuthenticated: true, user: payload.user, message: "Login has successed" } case TYPE.LOGIN_FAIL: localStorage.removeItem('access'); return { ...state, access: null, isAuthenticated: false, user: null, message: "Login has failed" } default: return state; } } //Header.js const Layout = (props) => { let location = useLocation(); useEffect (() … -
n.data.map is not a function in React
I am getting this error which may indicate the map function require arrays, while the data provided is not of the data type required. The console output in the browser Uncaught (in promise) TypeError: n.data.map is not a function t watchlistStore.jsx:14 d watchlistStore.jsx:2 O watchlistStore.jsx:2 E watchlistStore.jsx:2 em watchlistStore.jsx:2 a watchlistStore.jsx:2 promise callback*em watchlistStore.jsx:2 a watchlistStore.jsx:2 n watchlistStore.jsx:2 n watchlistStore.jsx:2 fetchStocks watchlistStore.jsx:22 im indexWatchlist.jsx:15 React 3 k scheduler.production.min.js:13 T scheduler.production.min.js:14 53 scheduler.production.min.js:14 Webpack 12 import React from "react"; import { create } from 'zustand'; import axios from 'axios'; const watchlistStore = create((set) => ({ stocks: [], filteredStocks: [], fetchStocks: async () => { console.log(`Fetching Watchlist`); const response = await axios.get('/watchlist'); if (response.data != 0) { const stocks = response.data.map((stock) => { return { symbol: stock.symbol, name: stock.name, } }); set({ stocks }); }; }, })); export default watchlistStore; The data to be fetched /watchlist {'symbol': 'WISH', 'name': 'ContextLogic Inc.'}{'symbol': 'GTII', 'name': 'Global Tech Industries Group, Inc.'}{'symbol': 'CCFN', 'name': 'CCFNB Bancorp, Inc.'}{'symbol': 'GAME', 'name': 'Engine Gaming and Media, Inc.'}{'symbol': 'SEMR', 'name': 'Semrush Holdings, Inc.'} The view in the backend: def watchlist(request): if request.user.is_authenticated: dataList = list() for x in Tickers.objects.filter(users=request.user): dataList.append({'symbol':x.symbol, 'name':x.name}) return HttpResponse(dataList) else: return HttpResponse('Watchlist is empty') -
Sessionid is not set to 'application/Cookies' in developer tools
I'm trying to implement a login function with Django and React. Reference: https://www.youtube.com/watch?v=diB38AvVkHw&ab_channel=Djangoroad When a post method is sent to login, the sessionid is set only in 'network/cookies'. Checking the 'application/cookies', only csrfToken is set. I'm not sure why the sessionid wasn't set to the Cookies. Is there anything to cause this problem? here is UserLogin view in django views.py class UserLogin(APIView): permission_classes = (permissions.AllowAny, ) authentication_classes = (SessionAuthentication, ) def post(self, request): data = request.data assert validate_email(data) assert validate_password(data) serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): user = serializer.check_user(data) login(request, user) return Response({'user_id': user.user_id}, status=status.HTTP_200_OK) Here is the react function to submit login form. function submitLogin(e) { e.preventDefault(); client .post("/api/login", { email: email, password: password, }) .then(function (res) { setCurrentUser(true); setUserId(res.data.user_id); }); } -
No module of _ffi found when create superuser
Python manage.py createsuperuser in django project in virtuelenv, reporting error: No module of _ffi found. Error Image 1 Error image 2 I got some clue from google. for example update cffi and argon2, run python from different locations. But nothing works. Thanks in advance! -
How to sort object by number of orders that is obtained by `get_queryset` field
Here in code below I can get all the number of orders that are assigned to business. But here is the question, how can I edit this code so that I can sort users by which business that has most orders? class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='ordersauthor') profile = models.ForeignKey(User, on_delete=models.CASCADE,related_name='orderscheck') article = models.ForeignKey(Article, null=True, blank=True, on_delete=models.CASCADE,related_name='ordersarticle') timestamp = models.DateTimeField(auto_now_add=True) --------- class PublicUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all().order_by('#HIGHEST NUMBER OF ORDERS') serializer_class = UserSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] pagination_class = StandardResultsSetPagination def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .annotate( num_orders=Count( 'orderscheck', orders__timestamp__range=Q( orderscheck__timestamp__range=(date.today(), date.today() + timedelta(days=7)) ), ) ) ) ---------- class UserSerializer(serializers.ModelSerializer): orders = serializers.IntegerField(read_only=True, source='num_orders')