Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot connect to Redis on Heroku using Celery on my Django project
I have created a Redis server on Heroku to use with Celery and I am trying to connect to it with my Django project. I have set the CELERY_BROKER_URL to the Redis URI provided in Heroku in settings.py and added files as per Celery documentation. celery.py import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SLGarage.settings') app = Celery('SLGarage') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') and __init__.py # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) When trying to connect to the server using the Terminal command "celery -A SLGarage worker -l INFO" I keep getting an error: (TM470) Arnass-MacBook-Pro:SLGarage arnasastapkavicius$ celery -A SLGarage worker -l INFO -------------- celery@Arnass-MacBook-Pro.local v5.1.2 (sun-harmonics) --- ***** ----- -- ******* ---- macOS-10.16-x86_64-i386-64bit 2021-06-28 15:20:39 - *** --- * --- - … -
How to overwrite create method in Viewset to accept my custom serializer in DRF?
I need to create a instance of my model, but in my request.data i don't have the correct information for my serializer. class CotizacionViewSet(viewsets.ModelViewSet): serializer_class = CotizacionSerializer permission_classes = [IsAuthenticated] def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response({'message': 'Cotizacion creada correctamente.'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and my serializer is CotizacionSerializer(serializers.ModelSerializer): cliente = ClienteSerializer() curso = CursoCatalogoSerializer() class Meta: model = Cotizacion exclude = ('state', 'created_date', 'modified_date', 'deleted_date') i want the information that gives me the serilizers from cliente and from curso but i don't know how to create a Cotizacion. -
How to open dynamically created files in django
okay my head hurts, i created 2 models one for image and one for file, each time i upload an image a file is automatically created containing the OCR result of the image. However my files are not being stores into the file folder and i can seem to open them. here is my code please help me guys i've been stuck not understanding how to pass the text to the fileField so that it can deal with it as w normal upload: class Image(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=50) image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) if self.id : File.objects.create( file=Create_Pdf(self.image)) File.objects.update(title=self.title) def __str__(self): return str(self.id) this is my File model : from django.db.models.fields import related from django.db import models # Create your models here. class File(models.Model): label=models.CharField(max_length=50, default='none') title=models.CharField(max_length=200,default='test') file=models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) and this is the use case : import uuid import os import pytesseract import PIL.Image pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def Create_Pdf(image): filename = f"{uuid.uuid4()}.pdf" path=r'C:\Users\DELL\Desktop\PFE Rihab\Django j\OCRapplication\media\files'#i know this is wrong i just wanted to save the files and view them. image=PIL.Image.open(image) text=pytesseract.image_to_string(image) with open (os.path.join(path,filename),mode='w+')as f: f.write(text) return(text)#i m not sure i should be returning … -
group_send inside a for loop randomly hangs - Django Channels 3.0.3
I am new to Channels and I am implementing a notification system where I might have to notify multiple people when an event occurs. I am calling the group_send method inside a for loop and it is acting weird. Here is the code snippet: class InboxConsumer(AsyncJsonWebsocketConsumer): . . . async def receive_json(self, data): . . . # Broadcast returned data to everyone broadcast_to.insert(0, self.scope['user'].id) for _user in broadcast_to: await self.channel_layer.group_send(str(_user), return_data) I create a group for each logged in user using their user id. The above code works without any errors. It absolutely has no issues when the size of broadcast_to is one. However, whenever I add more users in broadcast_to, it randomly hangs. It works perfectly most of the times, but suddenly hangs for ~30 sec (happens once in 6-7 times). There is absolutely no traffic in the system as the issue is replicable in localhost too. I am using Redis and Daphne (as mentioned in the tutorial). I have no idea what's wrong and how to fix this. Thanks -
django-user_agent not working on extended page, request.user_agent not responding
I am updating a site for mobile and have added the code to my base.html, using django_user_agent. {% if request.user_agent.is_mobile %} <link rel="stylesheet" href="{% static 'css/mobile.css' %}" type="text/css" media="screen" /> {% endif %} This is working for my home page, however for one of the pages extending off of it, it is not working. It looks like that extended page is unable to call request.user_agent after trying to get it to print if it is on mobile or pc. Does anyone know what could be causing this issue? -
Defining Django base url
I have a local Django app that works fine. For example, when I want to login, it goes to 127.0.0.1/users/login. I'm now deploying this app on a server with the URL https://examples.com/abc/. How can I tell Django that the base URL of the website is not https://examples.com/. So that when I'm calling my login function, it goes to https://examples.com/abc/users/login/ and not https://examples.com/users/login/. Thanks in advance ! -
Dropdown values not getting rendered?
I am trying to populate dropdown values with category values, somehow its showing empty dropdown template <select name="topic_name" id="cars"> {% for val in choices %} <option value="{{val.name}}">{{ val }}</option> {% endfor %} </select> View def add_page(request): if request.user.is_authenticated: if request.method == 'GET': context = { 'choices ': Category.objects.all(), } if request.method == 'POST': topic_n = request.POST['topic_name'] topic_det = request.POST['text'] picture= request.FILES['picture'] top = topic( user=request.user, article_name=topic_n) top.save() entery = entry.objects.create(topic=top, text=topic_det) entery.save() return redirect('/dashboard') return render(request,'learning_logs/add_page.html',context) -
Comparative database metrics for different implementations of Django Model
Considering two approaches in designing Django models: 1 - Very few models, but each model has a long list of fields. 2 - Many models, each model has significantly shorter list of fields. But the models employ multi-level hierarchical one-to-many structure. Suppose they both use Postgres as the database. In general, what would be the comparative database size, latency in retrieving, processing and updating data for these two approaches? -
Django + React - struct.error: unpack requires a buffer of 4 bytes
I'm trying to runserver using python manage.py runserver and I'm getting this error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Git\commerce\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Git\commerce\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Git\commerce\venv\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Git\commerce\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Git\commerce\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Git\commerce\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Git\commerce\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Git\commerce\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Git\commerce\venv\lib\site-packages\django\contrib\auth\models.py", line 90, in <module> class Group(models.Model): File "C:\Git\commerce\venv\lib\site-packages\django\db\models\base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Git\commerce\venv\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Git\commerce\venv\lib\site-packages\django\db\models\fields\related.py", line 1637, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) File "C:\Git\commerce\venv\lib\site-packages\django\db\models\fields\related.py", line 1099, in create_many_to_many_intermediary_model 'verbose_name': … -
Django - serving static files from collect_static folder in dev
I'm having troubles figuring out how I can serve my static files from the folder where I collect all static files (for eventually in production have those served from a different server). My frontend static files are under projectroot/frontend, and the static files folder where they collect is undert projectroot/static My settings.py files looks like this for the relevant bits: STATICFILES_DIRS = [ os.path.join(BASE_DIR,'frontend'), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") Then my urls.py (the root confs) look like this: urlpatterns = [ path(.....), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Then I run the dev server using python manager.py runserver. If I run python manage.py collectstatic, then I indeed see all the relevent files collected under projectroot/static. However, if I remove/rename the original folder (/frontend), then the static files are not served by the dev server, meaning it isn't using the /static folder. Which I would prefer to use even in dev, just because I'd rather catch any random issue right away.... What am I doing wrong? -
Memcached service is working as expected but stats items is empty
I'm using Django with docker - In my Docker-compose I created a memcached service: build: context: . dockerfile: memcached.Dockerfile ports: - '11211:11211' expose: - "11211" the Dockerfile looks like this: USER root RUN apt-get update && apt-get install -y \ telnet \ telnetd \ libmemcached-tools \ netcat USER memcache EXPOSE 11211 Now the cache location is defined in settings.py which retrieve it .ENV file : settings.py if os.getenv("CACHE_BACKEND"): cache_timeout = os.getenv("CACHE_TIMEOUT") CACHES = { 'default': { 'BACKEND': os.getenv("CACHE_BACKEND"), 'LOCATION': os.getenv("CACHE_LOCATION"), 'TIMEOUT': None } } .env CACHE_BACKEND = django.core.cache.backends.memcached.MemcachedCache CACHE_LOCATION = ***********:11211 # I covered the container name CACHE_TIMEOUT = None the actual caching function is wrapped and uses as an annotation: def caching(code_version=None): """ Decorator with argument :param code_version: code version from DB :return: real_decorator """ def real_decorator(func): """ Wrapper function that reads from the cache if the value already exists and if not then it saves it to the cache :param func: wrapped function :return: Wrapper function """ def func_wrapper(request): from django.http import HttpResponse from django.core.serializers.json import DjangoJSONEncoder from django.core.cache import cache if code_version: cache.version = code_version url = request.get_full_path() url_hash = f"{abs(hash(url))}" save_cache: bool = len(url_hash) <= 250 print(f"SAVE CACHE-----------------------{save_cache}") if save_cache: try: cache_result = cache.get(url_hash) if cache_result: … -
Displaying image URL on Django Blog Home Page
I am not able to load my blog image on landing page. Please any one can solve this issue. my HTML code inside for loop: {% for item in object_list %} <img class="rounded" src="{{item.main_image.url}}"> It gives error The 'main_image' attribute has no file associated with it. I am able to load the images in detail page by simply doing this: src="{{object.main_image.url}}"> My Model: class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=True, blank=True,upload_to='images/') date = models.DateTimeField(auto_now_add=True) item_slug = models.CharField(max_length=200, default=1) item_category = models.ForeignKey(Categories, default=1, on_delete=SET_DEFAULT) -
Django login and sign up in the same page
Is there a way to add login and registerati form in the same page in django? I don't know how to add signup form to loginview or importing log in form in registration page -
How to tell Django model that only one or other field must be not empty?
With Django models.Model class like that: class OrderLign(models.Model): Order = models.ForeignKey(Order,on_delete=models.CASCADE) Item = models.ForeignKey(Item, on_delete=models.RESTRICT, blank=True, default=0, null=True) Pack = models.ForeignKey(Pack,on_delete=models.RESTRICT, blank=True, default=0, null=True) I need that is possible to save OrderLign only if Item OR Pack is set, not both, and not neither. -
Update data from view context on post
I'm trying to update the context that i send to a template after receiving a post. Example of what i want to update in a template : <div id="testbox"> <a id="test ok">test</a> {{ element }} </div> The ajax for the post and update of the div : $(document).on('click', '#test', function (e) { e.preventDefault(); elementname = this.id; const request = new Request( "", {headers: {'X-CSRFToken': csrftoken, 'Content-Type': 'application/json'}} ); fetch(request, { method: 'POST', body: JSON.stringify({ pluginEdit: elementname }), mode: 'same-origin' }).then(function() { $('#testbox').load(document.URL + ' #testbox'); }); }) Extract of my views.py : if body.get("pluginEdit"): context = { //some things i send anyway 'element': body.get("pluginEdit") } return render(request, 'myapp/dashboard.html', context) I tested if it enters my "if" even though the page is already loaded, which it does, but the new part of the context doesn't reach the template when it's updated with js. Didn't found any other to do that by the way, so what am i doing wrong ? -
How to attach Datetime concentation of Django migration files names
When I run : ./manage.py makemigrations the generated migration files concatenate the model and field name together, but me I want to concatatenate Datetime on the file name generated. For example this is what I get, which I don't want : But I want something like this : This is my model : class Assessment(AllProcess, models.Model): title = models.CharField(_('Title'), max_length=100, null=False, blank=False) category = models.ForeignKey( Category, on_delete=models.DO_NOTHING, verbose_name=_('Category'), related_name='category') user = models.ForeignKey(User, on_delete=models.CASCADE) number_of_questions = models.IntegerField( _('Number of Questions'), help_text=_('Number of questions') ) time = models.IntegerField( _('Time'), help_text=_('Duration of the quiz in minutes')) score_to_pass = models.IntegerField( help_text=_('Required score to pass an assessment in %')) test = models.CharField(_('Test'), max_length=100, null=True, blank=True) difficulty = models.CharField(max_length=6, choices=DIFF_CHOICES) created_at = models.DateTimeField(auto_now_add=True) -
CSV file getting downloaded but not saved to computer
I'm working on a Django project where I create a csv file using some data that I have and then I want the user to be able to download it. The file is being created in views.py, which looks like this: def generate_csv_response(modelset, field_names, filename='export.csv'): """ Generate a CSV for all field_names in a DB model :param field_names is a dictionary which contains the model field name as a key and the CSV header display name as it's value """ response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'attachment; filename="{filename}"' # create the CSV writer and write a header row to the file writer = csv.writer(response) writer.writerow([v for _, v in field_names.items()]) # display names are the values # write a row of all specified fields for each model in the modelset for m in modelset: row = [getattr(m, field) for field in field_names] writer.writerow(row) # return the generated HTTP response return response class ConfigRuleViewSet(viewsets.ReadOnlyModelViewSet): queryset = ConfigRule.objects.all() serializer_class = ConfigRuleSerializer permission_classes = [permissions.IsAdminUser | ReadOnlyUser] config_rule_connector = AWSConfigRuleConnector() @action(detail=False, methods=['post'], permission_classes=[permissions.AllowAny]) def refresh(self, request): account_id = json.loads(request.body)['account_id'] if not account_id: logger.warn('Got blank account_id from ajax request: %s', account_id) if self.config_rule_connector.update(account_id): return Response(data={'updated': True, 'count': ConfigRule.objects.count()}) return Response(data={'updated': False, 'error': 'Config Rule could … -
Central position Images with CSS and HTML in django project
Working on landing page Django, trying to centre images with css, but it doesn't work for me, Im stucked, cant find any asnwer on the internet. My first project for portfolio. Please help me with this question, will be very glad. Thank you <!DOCTYPE html> {% load static %} <html lang="eng"> <! --looks good on mobile devices--> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'style.css' %}"> <head> <meta charset="UTF-8"> <title>Main page</title> </head> <body> <header class="header"> <div class="header-text" style="color:white">Follow me:</div> <a href="https://www.instagram.com/kseniia_ifbblatvia" class="header-link1">Instagram</a> <a href="https://www.tiktok.com/@super_zav" class="header-link2">TikTok</a> <a href="https://www.facebook.com/profile.php?id=100009190064504" class="header-link3">Facebook</a> <div class="images"> <img src="{% static 'tiktok.png' %}" width="100" height="100" alt="tiktok image" class="tiktok"> <img src="{% static 'insta.png' %}" width="100" height="100" alt="instagram image" class="instagram"> <img src="{% static 'facebook.png' %}" width="100" height="100" alt="facebook image" class="facebook"> </div> </header> <h1>Personal training and nutrition plan</h1> <p>Text about it</p> </body> </html> And CSS: body{ background: url(https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=889&q=80) no-repeat center center fixed; background-size: cover; } .tiktok { display: block; margin: auto; border: 2px solid white; padding: 10px; margin-right: 1070px; } .instagram { display: block; margin: auto; border: 2px solid white; padding: 10px; margin-right: 890px; } .facebook { display: block; margin: auto; border: 2px solid white; padding: 10px; margin-right: 690px; } } .header-text { height: 20%; width: 100%; display: flex; position: … -
Upload Image and parameters from android(retrofit) to django get bad request
I use API like this ; @POST("api/info/save") Call<ResponseBody> uploadMultiFile(@Body RequestBody file); and this function get images from an arraylist and add parameters to send server; private void uploadMultiFile(final String event_date, final int event_type, final int coordinate_x, final int coordinate_y) { String url = Constant.baseUrl; Coordinate coordinate = new Coordinate(); coordinate.setX(coordinate_x); coordinate.setY(coordinate_y); TokenInterceptor interceptor=new TokenInterceptor(); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(url) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); Api service = retrofit.create(Api .class); MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); builder.addFormDataPart("event_date", event_date); builder.addFormDataPart("event_type", String.valueOf(event_type)); builder.addFormDataPart("coordinate", String.valueOf(coordinate)); // Map is used to multipart the file using okhttp3.RequestBody // Multiple Images for (int i = 0; i < imagePathList.size(); i++) { File file = new File(imagePathList.get(i)); builder.addFormDataPart("image[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)); } MultipartBody requestBody = builder.build(); Call<ResponseBody> call = service.uploadMultiFile(requestBody); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Toast.makeText(MMEActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.d("d", "Error " + t.getMessage()); } }); } I got Bad Request Error. How can ı solve this problem? I use Django in my backend. This my function to get images and parameters from request. @api_view(['POST']) def eventInfoSave(request): event_date = request.data['event_date'] print(request.data) . . if … -
How to combine Django import_export with list_display in admin.py?
I'm new to Django, and I want to know how to combine import_export module with list_display in admin.py? For example: When I use list_display to disply two fields (id and IP), below codes in admin.py works fine, but I can't see the import export widgets: from django.contrib import admin from .models import SwitchModel @admin.register(SwitchModel) class SwitchAdmin(admin.ModelAdmin): list_display = ('id','IP') When I use below codes, I can see the import and export widgets, but I can no longer see the two fields (id and IP): from django.contrib import admin from .models import SwitchModel from import_export import resources from import_export.admin import ImportExportModelAdmin class SwitchModelResource(resources.ModelResource): class Meta: model = SwitchModel class SwitchModelAdmin(ImportExportModelAdmin): resource_class = SwitchModelResource admin.site.register(SwitchModel, SwitchModelAdmin) I tried to combine the two sets of codes together like below: from django.contrib import admin from .models import SwitchModel from import_export import resources from import_export.admin import ImportExportModelAdmin @admin.register(SwitchModel) class SwitchAdmin(admin.ModelAdmin): list_display = ('id','IP') class SwitchModelResource(resources.ModelResource): class Meta: model = SwitchModel class SwitchModelAdmin(ImportExportModelAdmin): resource_class = SwitchModelResource admin.site.register(SwitchModel, SwitchModelAdmin) Then I kept receiving the below Error: How can I have list_display and import_export widgets work together? Could anybody shed some light on this? -
How to loop over rows in a submitted csv file in django?
I have a Django form class SmsWebForm(forms.Form): csv_file = forms.FileField(required=False, widget=forms.FileInput(attrs={'accept': ".csv"}), label="Csv soubor s telefonními čísly") phone_number = forms.CharField(max_length=20, required=False, label="Telefonní číslo") number_format = forms.ChoiceField(label="Formát telefonního/ch čísla/el", choices=FORMATS) text = forms.CharField(max_length=300, label="Text zprávy", widget=forms.Textarea) and when it gets submitted, I expect a .csv file of the following format. eg: 777777777, 88888888, .. then I don't want to save it, only loop over the phone numbers in it and do something for each. However, I am struggling to access the contents of the .csv form file. The code in the view looks like this if request.method == "POST": form = SmsWebForm(data=request.POST, files=request.FILES) if form.is_valid(): phone_num = form.cleaned_data["phone_number"] csv_num_file = form.cleaned_data['csv_file'] orig_text = form.cleaned_data['text'] number_format = form.cleaned_data["number_format"] if not csv_num_file and not phone_num or phone_num and csv_num_file: raise forms.ValidationError("Právě jedno z polí 'telefonní číslo' nebo 'csv soubor' musí být vyplněno") if csv_num_file: with open(csv_num_file.seek(0), "r", encoding="utf-8") as f: csv_num_file.close() reader = csv.DictReader(f) for row in reader: print(row) for number in reader: ... I am "reopening" the file on the line with open(csv_num_file.seek(0), "r", encoding="utf-8") as f because when it comes in the form it is already opened but in bytes. The line for row in reader: never gets executed, the program … -
User getting logged out after external redirect in django
The user gets logged out after redirection from an external site(maybe cros-domain) to my Django app -
Seperate Resource Server(Django-oauth-toolkit) - 403 Forbidden Error(If RESOURCE_SERVER_INTROSPECTION_CREDENTIALS is used)
I run into an issue not sure if this is a bug. Any help would be appreciated. Some context: Authorization Grant Type is Resource Owner Password Credentials where the Client Type is "confidential". I used csrf_exempt decorator and protected_resource decorator for a view response function in the resource server. Django REST Framework is used. Django REST Framework v3.12.4 and Django OAuth Toolkit v1.5.0 are used. I referred to the official documentation: https://django-oauth-toolkit.readthedocs.io/en/latest/resource_server.html Testing Setup is similar to the Referenced Article using two different ports: https://medium.com/@sarit.r/simple-seperate-auth-server-and-resource-server-36a7813ea8aa Auth Server: https://github.com/pathumveyron24/Django-Auth-Server Resource Server: https://github.com/pathumveyron24/Django-Resource-Server Auth Server Settings File: """ Django settings for auth_server project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path from .config import DB_ENGINE, DB_NAME, DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT, TIME_ZONE # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-h6pzc5%ovv^&5o5dg0z&e8k$7y*)fufjz%2s3t(*jick@u_u9g' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application … -
I am learning a django course on udemy and have an issue with the CSRF token part
enter image description here Why is my {% csrf_token %} being read as a text? CSRF issue is not resolved and instead I see {% csrf_token %} printed beside my input box now. -
django url redirecting not working. it appending end of requested url
i try Django 3xx with Django rest redirect to URl but its not working and i also try but not working yet views.py def redirect_shortner(request): return redirect('www.google.com') url.py urlpatterns = [ path('', redirect_shortner, name='redirect_shortner'),] so it seems perfect but..