Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I resolve the following error in Django: "OperationalError: foreign key mismatch"
I'm getting the following error whenever I attempt to save to the table in a SQLite database: foreign key mismatch - "procedure_tbl" referencing "filename_tbl" In models.py, these are the tables that the error is referring to: class FilenameTbl(models.Model): rowid = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='FileID', db_column='rowid') filename = models.TextField(blank=True, null=True) creation_datetime = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'filename_tbl' ordering = ['rowid'] class ProcedureTbl(models.Model): rowid = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ProcedureID', db_column='rowid') ... filename_id = models.ForeignKey(FilenameTbl,db_column='filename_id', to_field='rowid',null=True,blank=True,on_delete=models.SET_NULL) class Meta: managed = False db_table = 'procedure_tbl' ordering = ['rowid'] Data can be read from the tables and querysets like the following return the correct data: queryset = FilenameTbl.objects.values( 'rowid', 'filename', 'proceduretbl__rowid') Raw SQLite commands to write/update to the ProcedureTbl table function properly. If I removed filename_id from the ProcedureTbl, then data can be saved to the table. -
Azure active directory SAML SSO configuration issue with Django backend
I am trying to set up SAML Single Sign-On (SSO) with my Django app, but I am getting an error when I try to login to my app. I go to the app url, Microsoft processes the request (the url displays microsoft.loginonline.com/etc briefly), and then I get redirected to this page: https://my-app.azurewebsites.net/.auth/login/aad/callback which displays this error: {"code":400,"message":"IDX10501: Signature validation failed. Unable to match keys: \nkid: '[PII is hidden]', \ntoken: '[PII is hidden]'."} The reply url is set to: https://my-app.azurewebsites.net/.auth/login/aad/callback I did the set-up following both the Azure docs and following this documentation: https://django-auth-adfs.readthedocs.io, it's ostensibly working on my localhost, just not on the actual azure app service... I am unsure of what I am doing wrong, and the error message is not very informative for me as I am new to back-end programming and cloud. Any help appreciated, thanks! -
Django not auto-filling a new html file
starting to learn django, and in the video im watching django automatically fills minimum html code when you create a new html file in the templates folder, but its not happening for me. i can switch to HTML language mode and ctrl+space & choose HTML_sample, but its not the same code as shown in the video. is it just a pycharm thing? the video uses pycharm, but they say the Django autofills the code so didnt think it was the issue. the html files path: "project_name\app_name\templates\app_name" using VScode 3.9 and django 3.2.5. (had some trouble with django-html, had to add it manually to the settings.json) -
Django Rest: Why is the access denied, although AccessAny is set as permission?
I want to give all people, without any permissions access to my API. The following definitions I made in my files: views.py from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.parsers import JSONParser from rest_framework.permissions import AllowAny from django.http import HttpResponse, JsonResponse from rest_framework import status from api.models import Application, Indice, Satellite, Band from api.serializers import OsdSerializer import logging logger = logging.getLogger(__name__) class OsdView(APIView): permission_classes = [AllowAny] def get(self, request): applications = Application.objects.all() serializer = OsdSerializer(applications, many=True) return Response({"Applications:": serializer.data}) class DetailView(APIView): permission_classes = [AllowAny] def get(self, request, machine_name): application = Application.objects.get(machine_name=machine_name) downloads = OsdSerializer(application, context={"date_from": request.query_params.get("from", None), "date_to": request.query_params.get("to", None), "location": request.query_params.get("location", None), }) return Response(downloads.data) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } But when I access the API the result is the following instead of the content: {"detail":"Invalid username/password."} -
No installed app with label 'polls' - activating models - error
I am learning Django3.2.5, from https://docs.djangoproject.com/en/3.2/intro/tutorial02/. I created a project with the name, 'mysite', then 'polls' app, and using the default 'SQLite' database. Project's (mysite) file hierarchy: mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py App's (polls) file hierarchy: polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py mysite/mysite/settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.11.29. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '4)2m9i5*y=icl-9bpiw#w@n!(y^y%38+8smh70mqupeppb&o#r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': … -
502 Bad Gateway nginx/1.20.0 Error when Deploying Django app using AWS Elastic Beanstalk
I was following closely following AWS's documentation on how to deploy Django apps using Elastic Beanstalk until I received a 502 Bad Gateway nginx/1.20.0 Error when opening my app. From there, I followed a couple of solutions offered by users that suffered similar problems. Specifically, I added a Procfile and went about editing how my django.config file was set up. However, the error still remains and I would like some guidance on how to tackle this problem. Below are the relevant logs and files: eb-engine.log django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: hifive.wsgi:application Procfile web: gunicorn --bind :8000 --workers 3 --threads 2 djangoproject.wsgi:application settings.py """ Django settings for djangoproject project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'thesecuritykey' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost','127.0.0.1','djangoproject.eba-fuipjhfa.us-west-2.elasticbeanstalk.com'] # Application definition INSTALLED_APPS … -
How can I test a single field in a form?
I want to create a test that would confirm that in case of a user not putting any input into the question field, the error will be raised. def test_new_question_form_no_question(self): form = NewQuestionForm(data={ 'question': "", 'choice1': "ok", 'choice2': "fred@example.com", 'choice3': None }) self.assertEqual(len(form.errors), 1) That would probably be a perfect solution, but it doesnt work for me. Here I'll show why: class NewQuestionForm(forms.Form): question = forms.CharField(label='Question', max_length=1000) set = re.compile(r'fuck') choice1 = forms.CharField(label="Choice 1", validators=[RegexValidator(regex=set, inverse_match=True)]) choice2 = MultiEmailField() choice3 = forms.BooleanField(required=False) def clean_choice2(self): data = self.cleaned_data['choice2'] if 'fred@example.com' not in data: raise ValidationError("You've forgotten about Fred") return data def clean(self): super().clean() cc_myself=self.cleaned_data['choice3'] subject = self.cleaned_data**['question']******** if cc_myself and subject and 'help' not in subject: msg="What are you doing?" self.add_error('question', msg) In the part, which i highlighted with ******, there is this reference to question and because i didnt put a question in a test, this part cannot be executed. Thats why i struggle with testing if the form accepts only a filled question field. I tried this way def test_new_question_form_no_question(self): form = NewQuestionForm(data={ 'question': "", 'choice1': "ok", 'choice2': "fred@example.com", 'choice3': None }) self.assertFalse(form.is_valid()) Unfortunately doesnt work too. The thing that is shown on my terminal after i type ,,py … -
How to load ckeditor on Django project
I have a django project that have to following structure. -node_modules -src -account -chat -templates/chat chat.html -DjangoChat (my app) -venv .gitignore package-lock.json Inside chat.html I'm trying to load the ckeditor that is inside node_modules. <script src="/node_modules/@ckeditor/ckeditor5-build-classic/build/ckeditor.js"></script> <script> ClassicEditor .create( document.querySelector( '#editor' ) ) .then( editor => { console.log( editor ); } ) .catch( error => { console.error( error ); } ); </script> for some reason is not working. The structure of my project is correct? If is, how I can access the ckeditor file? -
how to mount different volumes of your docker-compose with AWS EFS using django react and postgres
while using AWS ECS Fargate, how do we mount files in AWS EFS from the volumes of different applications being used in the docker-compose? version: "3.9" services: backend: build: ./backend restart: "on-failure" volumes: - ./backend:/backend <======= THIS ONE - ./backend/static:/backend/static <======= THIS ONE ports: - 8000:8000 ... db: image: postgres:latest restart: always volumes: - postgres_data:/var/lib/postgresql/data/ <======= THIS ONE ... frontend: build: ./frontend volumes: - ./frontend:/frontend <======= THIS ONE I have the above configuration of my docker-compose and what i am trying to achieve is to make sure all those volumes <=== THIS ONE persist no matter what happen to my AWS ECS Fargate Task From what i read i must use AWS EFS and define that option in the task definition, but my question is to know whether i could persist all of those volumes from my docker-compose at once when i provide the single path in AWS EFS or should i provide a single path for each one of the volume above? -
Django redirect and modify GET parameters
I am implementing magic tokens and would like clean URLs. As a consequence, I would like to remove the token from the URL upon a successful user authentication. This is my attempt: def authenticate_via_token(get_response): def middleware(request): if request.session.get('authenticated', None): pass else: token = request.GET.get('token', None) if token: mt = MagicToken.fetch_by_token(token) if mt: request.session['authenticated'] = mt.email if not request.GET._mutable: request.GET._mutable = True request.GET['token'] = None request.GET._mutable = False else: print("invalid token") response = get_response(request) return response return middleware IE, I would like to send /products/product-detail/3?token=piyMlVMrmYblRwHcgwPEee --> /products/product-detail/3 It's possible that there may be additional GET parameters and I would like to keep them. Any input would be appreciated! -
Django/Js Direct to s3 App, Getting the Error: "The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256"
Have read all the posts here and elsewhere on this, tried everything I can find out there, and still can't figure my issue when trying to pass the s3v4 signature version. I get the presigned url ok then get the 400 error when I go to post the files to the bucket. I've used the same setting for a django project that uploads through the sever and have no issues. Am trying to pass the necessary fields in through the view below. Tried passing them in form in the html as well. No matter what I do the 'signature' in the network header logs doesn't change it's format. [![Network Headers Log][1]][1] View to get the presigned url and pass the post form fields: def sign_s3(request): if request.method == 'GET': file_name = request.GET.get('file-name') file_type = request.GET.get('file-type') file = File.objects.create(name=file_name) key = file.key file_url = 'https://{bucket}.s3.{region}.amazonaws.com/{key}'.format(bucket=S3_BUCKET, key=key, region=AWS_S3_REGION_NAME) url = 'https://{bucket}.s3.amazonaws.com'.format(bucket=S3_BUCKET) s3 = boto3.client('s3') presigned_post = s3.generate_presigned_post( Bucket=S3_BUCKET, Key=key, Fields={ "x-amz-algorithm": 'AWS4-HMAC-SHA256', "x-amz-credential": '{key}/{date}/{region}/s3/aws4_request'.format( key=S3_ACCESS_KEY, date=date, region=AWS_S3_REGION_NAME), "x-amz-date": '{date}'.format(date=date), "acl": "public-read", "Content-Type": file_type, }, Conditions=[ {"x-amz-algorithm": 'AWS4-HMAC-SHA256'}, {"x-amz-credential": '{key}/{date}/{region}/s3/aws4_request'.format( key=S3_ACCESS_KEY, date=date, region=AWS_S3_REGION_NAME)}, {"x-amz-date": '{date}'.format(date=date)}, {"acl": "public-read"}, {"Content-Type": file_type}, ], ExpiresIn=3600, ) presigned_post['url'] = url return HttpResponse(json.dumps({ 'data': presigned_post, 'url': file_url })) else: … -
URI Malformed Parcel Relative Module import
Relative import not being formed with correct URI when running parcel build/watch resulting in incorrect /trends/static/src/Shared/SiteHeader.vue not the correct /static/src/Shared/SiteHeader.vue /static/src/app.js … # here is where error is occurring import SiteHeader from './Shared/SiteHeader' … parcel is building off these commands in package.json … "scripts: { "watch": "parcel watch ./static/src/* -d ./static/dist/", "build": "parcel build ./static/src/* -d ./static/dist/", … Expected Behaviour: running npm run build should build my components so there are the main page components (which it does when the line causing the error is gone) AND be able to import from the Shared components What's Actually Happening: running npm run build errors out with /trends/static/src/Shared/SiteHeader.vue: URI malformed visiting mysite.com/static/src/Shared/SiteHeader.vue results in a download of the file notice the uri does not start with /trends, why is /trends being put on the URI? Full Error Trace: /trends/static/src/Shared/SiteHeader.vue: URI malformed at decodeURIComponent (<anonymous>) at HTMLAsset.resolveDependency (/trends/node_modules/parcel-bundler/src/Asset.js:94:22) at HTMLAsset.addURLDependency (/trends/node_modules/parcel-bundler/src/Asset.js:119:38) at HTMLAsset.processSingleDependency (/trends/node_modules/parcel-bundler/src/assets/HTMLAsset.js:99:26) at /trends/node_modules/parcel-bundler/src/assets/HTMLAsset.js:187:43 at traverse (/trends/node_modules/posthtml/lib/api.js:105:26) at traverse (/trends/node_modules/posthtml/lib/api.js:111:5) at traverse (/trends/node_modules/posthtml/lib/api.js:105:17) at traverse (/trends/node_modules/posthtml/lib/api.js:111:5) at traverse (/trends/node_modules/posthtml/lib/api.js:105:17) at Array.walk (/trends/node_modules/posthtml/lib/api.js:39:10) at HTMLAsset.collectDependencies (/trends/node_modules/parcel-bundler/src/assets/HTMLAsset.js:138:9) at HTMLAsset.getDependencies (/trends/node_modules/parcel-bundler/src/Asset.js:81:18) at async HTMLAsset.process (/trends/node_modules/parcel-bundler/src/Asset.js:215:7) at async Pipeline.processAsset (/trends/node_modules/parcel-bundler/src/Pipeline.js:46:7) at async Pipeline.processAsset (/trends/node_modules/parcel-bundler/src/Pipeline.js:74:25) -
How to make the web page title TAB in the browser + the URL changes depends on the title of the article opened, in DJANGO
Hello coders, I am making a blog in Django framework, My problem is that when i make new post or article and i enter to the page of the post ( the single post page ) My blog tab title in the browser doesnt change to the title of the article and the same thing with the URL too thank u all -
How to delete django model data on button click
I am creating a donation application. I have a screen in which people can click on if they want to learn more about a specific donation. On that screen, I have the following button: <button class="btn btn-success"onclick="showAlert()">Accept</button> . When this button is clicked, I bring up a confirmation alert, which is down bellow. (it uses swal to style but functions like a regular alert). When the alert comes up, if the user clicks the ok button, I want to delete the data that they are currently viewing and redirect them to another page. I am struggling with this, because I am not sure how to do this. Many people have said to use AJAX, but it does not seem to work. Javascript alert: swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } URL: (This is the unique url that renders the donation) path('donations/<int:pk>/', views.DonationDetail.as_view(), name='donation-detail'), I … -
Django how to delete sender from list
I am using django signals for create an notifications system.I want to delete sender from list if his status sender and receiver same. Let you explain Mr. Jhone send an message to all users and Mr Jhone aslo included in all user group. So I want to remove Mr. Jhone from list of all user. Here I tried this code but didn't work: if sender in notifications: #here I am trying to remove sender from notifications list notifications.remove(Notifications(sender=sender, receiver= receiver,text_preview=text,notification_type="global_noti")) here is my full code: def global_noti(sender, instance, *args, **kwargs): global_notify = instance sender =global_notify.user receivers = User.objects.all() text = global_notify.text if global_notify.is_published == 'global_notification': notifications=[] for receiver in receivers: notifications.append(Notifications(sender=sender, receiver= receiver,text_preview=text,notification_type="global_noti")) if sender in notifications: #here I am trying to remove sender from notifications list notifications.remove(Notifications(sender=sender, receiver= receiver,text_preview=text,notification_type="global_noti")) Notifications.objects.bulk_create(notifications) -
Using django-filter generic view and paginate_by, how to build the pagination urls?
First time using django-filter, so I might be using it wrong. I'm basically trying to mimic Django Admin filtering, using a generic FilterView, setting filterser_class and adding paginate_by filters.py class ProductFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains', label='Filter by Title') categories = django_filters.AllValuesFilter( field_name='categories__name', label="Filter by Category", widget=django_filters.widgets.LinkWidget(attrs={'class': 'list-menu'}), ) brand = django_filters.AllValuesFilter( field_name='brand__short_name', label="Filter by Brand", widget=django_filters.widgets.LinkWidget(attrs={'class': 'list-menu'}), ) class Meta: model = Product fields = ['categories', 'brand', 'name'] views.py class ProductFilterView(FilterView): filterset_class = ProductFilter paginate_by = 20 product_filter.html <section class="section-content padding-y"> <div class="container"> <div class="row"> <aside class="col-md-3"> <div class="card"> <form method="get"> {% csrf_token %} {% for field in filter.form.visible_fields %} <article class="filter-group"> <header class="card-header"> <a href="#" data-toggle="collapse" data-target="#collapse_1" aria-expanded="true" class=""> <i class="icon-control fa fa-chevron-down"></i> <h6 class="title">{{ field.label_tag }}</h6> </a> </header> <div class="filter-content collapse show" id="collapse_1"> <div class="card-body"> {{ field }} </div> <!-- card-body.// --> </div> </article> <!-- filter-group .// --> {% endfor %} <input type="submit" class="btn btn-block btn-primary" value="Filter"/> </form> </div> <!-- card.// --> </aside> <!-- col.// --> <main class="col-md-9"> <header class="border-bottom mb-4 pb-3"> <div class="form-inline"> <span class="mr-md-auto">{{ filter.qs | length }} products found </span> </div> </header><!-- sect-heading --> <div class="row"> {% for obj in page_obj %} <div class="col-md-4"> <figure class="card card-product-grid"> <div class="img-wrap"> <img src="/media/{{ obj.productimage_set.first.image|default:'products/missing.png' }}"> </div> <!-- img-wrap.// … -
next steps after deploying Django and react app to Azure app service
I am failry new to Clouad Service and I have a React and Django web app running on Azure app service. Thing that I have done already. Django and react app up and running fine locally. 2 docker Images with 2 containers deployed into Azure App service. I have one azure resource registry and 1 app service with two docker containers (frontend and backend) Both react and django are up and running in azure app service and are accessible using similar to following urls. frontend.azurewebsites.net #This is just a sample name djangorestapi.azurewebsites.net #This is just a sample name I wanna publish this to public using domain. I am aware that I have to buy a domain and stuff. I would really appreciate if somebody can point out what are the next steps to follow. I wanna make it available to public. Also, with new changes I need to fix my React restapi endpoits which I made it using Django Rest Framework. -
Dynamic URL for user profiles /Django
I trying to make dynamic URL for my users page For Example: mypage/profiles/(username) I trying a < str> tag in my urls path but it not works. I have it usernames but i dont this send to url here i am getting this error: NoReverseMatch at / Reverse for 'users' with no arguments not found. 1 pattern(s) tried: ['users/(?P[^/]+)$'] VİEWS: from django.shortcuts import render def users(request,username): username = request.user # it's works return render(request, "profiles.html") URLS: from django.urls import path from . import views urlpatterns = [ path('users/<str:username>',views.users, name="users"), ] -
How to use inter-process communication in django with discord.py and discord-ext-ipc
I'm currently using discord-ext-ipc as an inter-process communication (IPC) extension for discord.py and linked this with quart-discord. Quart is an asyncio reimplementation of Flask and can natively serve WebSockets and other asynchronous stuff. I can so easily use a Web-Frontend as a Dashboard to interact with the discord users on a guild. Doing fun stuff like, using the discord role model for a permission model at the dashboard. Recently I stumbled over django and got hooked up with that powerful framework. As a learning project, I wanted to port the current working project into django but I stumbled over some impasses. First the working example with discord-ext-ipc and quart-discord: bot.py import logging import discord from discord.ext import commands, ipc intents = discord.Intents.default() logging.basicConfig(level=logging.DEBUG) TOKEN = DISCORD_TOKEN class MyBot(commands.Bot): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.ipc = ipc.Server(self,secret_key = IPC_SECRET_KEY) async def on_ready(self): """Called upon the READY event""" print("Bot is ready.") async def on_ipc_ready(self): """Called upon the IPC Server being ready""" print("Ipc server is ready.") async def on_ipc_error(self, endpoint, error): """Called upon an error being raised within an IPC route""" print(endpoint, "raised", error) my_bot = MyBot(command_prefix = ">", intents = intents, chunk_guilds_at_startup = False) @my_bot.ipc.route() async def get_guild_ids(data): final = [] for guild in … -
How to add Query String Auth on all files in Django with Amazon S3
I am using Django with Amazon s3 with Libraries(django-storages boto3) To be specific the base.css is being served and fonts.css is not being served(Err 403). This is happening in Django Admin Console. I have confirmed that the fonts.css is in the bucket The problem being these files don't have query string auth # This is working GET https://bucket-name.s3.amazonaws.com/static/admin/css/base.css?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AFD34GE4VTLUKQOTHAW7%2F20210726%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20210726T193438Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=815bd068805f60f90c6acf27b24028424e85afbf7ba2939b51471cab2ba8e8b9 # This isn't working GET https://bucket-name.s3.amazonaws.com/static/admin/css/fonts.css Almost all static files are being served The fonts.css is not in the HTML page source and maybe is being called from a JS code that is not appending the Query String Auth Also when I shift from S3 to django default storage, it works perfectly fine. -
Django Slugs as principal url
I want to do the following, so that the profile of each registered user can be seen as follows: http://127.0.0.1:8000/username/ I was able to achieve this, the problem is when wanting to create another page, for example http://127.0.0.1:8000/explore/ Django consider "explore" as a user and throw me a 404 error. this is my urls.py urlpatterns = [ path("<slug:slug>/", PerfilView.as_view(), name="perfil"), path("explore/", UserListView.as_view(), name="explore"), ] Am I doing it the right way or am I unable to do this with django? Regads -
Replace Default PK slug with Multiple Lookup Fields for ModelViewSet
I have two slugs, against which I run queries. Thanks to base class MultipleFieldLookupMixin, which my view class is inherited from and thus allows me to have multiple lookup_fields. We know that when ModelViewSet is used with DefaultRouter, appends a pk at the end of URL, which I don't want. For example, when I do this: router = DefaultRouter() router.register(r'organization', OrganizationModelViewSet, basename='organization') urlpatterns = [ path('viewset/', include(router.urls)), path('viewset/<str:device>/<str:start_time>/', include(router.urls)) ] it gives me the URL mydomain.com/viewset/<str:device>/<str:start_time>/organization/<int:pk>/ I don't want this pk at the end. If we can remove organization, that's even better. I want the endpoint to be, mydomain.com/<str:device>/<str:start_time>/. More playing around, I learned that adding extra_kwargs like this in my serializer class, extra_kwargs = { 'url': {'lookup_field': 'start_time'} } and modify lookup_fields in view class, with singular lookup field, like lookup_field, with value let's say, start_time. To clarify, changing lookup_fields = ["device", "start_time"] with lookup_field = "start_time" and also modify the URL accordingly by removing the start_time slug, then URL becomes mydomain.com/viewset/<str:device>/organization/<str:start_time>/ modify singular lookup_field with org, apparently gives us more or less the desired URL, but doesn't get the job done because we have a single lookup_field now! mydomain.com/viewset/str:device/organization/str:start_time/ If we edit this line router.register(r'organization', DeviceActivityModelViewSet, basename='device_activity') to … -
How to implement only accepting username and token as request in django view and not password?
I have created a custom User model in Django that has username, email, password and some other fields. I am using jwt token which can be acquired from /token after providing valid username and password of a user. I have created a serializer for /authstatus and implemented it's view in views.py. Currently it works only when both username and password are provided with authentication token as header. Is there any way to ask only username and not password from user as a request for /authstatus? Code: Serializer: class AuthSerializer(serializers.ModelSerializer): password = serializers.CharField( required=True, style={"input_type": "password"}, write_only=True ) class Meta: model = get_user_model() fields = ["id", "username", "password", "auth_status"] read_only_fields = ["id"] Any help will be appreciated. Thank you! -
Add general [to all models] queryset method
I can create a new class from models.QuerySet to override a specific model queryset manager, but is it possible to write a method that applies to all models? For example: Every time i need to see the unique values of a variable, i need to write (*using SQLite) list(map(lambda v: v[my_var], qs.values(my_var).distinct().order_by())) But it would be nice to have something like my_queryset.unique_values(my_var) # Returns [value1, value2, value3, ...] Without having to specify it to every model -
How can i make a move button for a site created in django, html and python
How can i make a move button for a site created in django, html and python. To make myself better understood. I want to add the questions in categories. example: test 1 - 5 questions test 2 - 5 questions and so on but when I add the questions, they run one after the other this is the source - https://github.com/akashgiricse/lets-quiz