Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-cms: Cannot delete pages in page-tree
When I open the page tree and try to delete one of the pages, I encountered an error about 'GET actions-menu 500': I wonder if this error is due to 'bundle.admin.pagetree.min.js:1 [Deprecation] document.registerElement is deprecated and will be removed in M73, around March 2019. Please use window.customElements.define instead' in the console. Here is my environment: aldryn-apphooks-config 0.6.0 asgiref 3.3.1 dj-database-url 0.5.0 Django 3.1.7 django-admin-ip-restrictor 2.2.0 django-appdata 0.3.2 django-classy-tags 2.0.0 django-cms 3.8.0 django-filer 2.0.2 django-formtools 2.2 django-ipware 3.0.2 django-js-asset 1.2.2 django-meta 2.0.0 django-mptt 0.11.0 django-parler 2.2 django-polymorphic 3.0.0 django-sekizai 2.0.0 django-sortedm2m 3.0.2 django-taggit 1.3.0 django-taggit-autosuggest 0.3.8 django-taggit-templatetags 0.2.5 django-templatetag-sugar 1.0 django-treebeard 4.4 djangocms-admin-style 2.0.2 djangocms-apphook-setup 0.4.1 djangocms-attributes-field 2.0.0 djangocms-blog 1.2.3 djangocms-bootstrap4 2.0.0 djangocms-file 3.0.0 djangocms-googlemap 2.0.0 djangocms-icon 2.0.0 djangocms-installer 2.0.0 djangocms-link 3.0.0 djangocms-picture 3.0.0 djangocms-snippet 3.0.0 djangocms-style 3.0.0 djangocms-text-ckeditor 4.0.0 djangocms-video 3.0.0 easy-thumbnails 2.7.1 html5lib 1.1 lxml 4.6.2 Pillow 8.1.0 pip 21.0.1 pkg-resources 0.0.0 pytz 2021.1 setuptools 44.0.0 six 1.15.0 sqlparse 0.4.1 tzlocal 2.1 Unidecode 1.1.2 webencodings 0.5.1 Beside this, I have another problem: Djangocms: menu navigation error but it returned normal after zooming in······ Thank you for your help!!!! -
The object with alias 'default' was created in thread id 2281649653888 and this is thread id 2281728636176. Celery problem completing tasks
I am trying to figure out, how to get the created post id, so I could use it later to send an email to subscribers. But the system is giving me an error, that says the following: Traceback (most recent call last): File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\celery\app\trace.py", line 405, in trace_task R = retval = fun(*args, **kwargs) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\celery\app\trace.py", line 697, in __protected_call__ return self.run(*args, **kwargs) File "C:\Users\1224095\skillfactory\Testing2\NewsPaper\News\tasks.py", line 12, in Post_send post = Post.objects.get(id=oid) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\query.py", line 431, in get num = len(clone) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1167, in execute_sql cursor = self.connection.cursor() File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\backends\base\base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\backends\base\base.py", line 227, in _prepare_cursor self.validate_thread_sharing() File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\backends\base\base.py", line 552, in validate_thread_sharing raise DatabaseError( django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 2281649653888 and this is thread id 2281728636176. my views.py … -
How to play an uploaded video in django rest framework
I have a trouble with using django-rest-framework. I uploaded some videos. And I try to play that videos in react. But I faced 404 error. I added static and media root in setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") And in react I tried like this. <ReactPlayer url={`${baseurl}/media/${videoDetaildata.url}`} playing={true} controls={true} playIcon={true}/> This works when the url is Youtube url. Please help me. Thank you in advance. -
Adding an external HTML block inside a Django block
I'm developing a Django webapp, I created the layout.html and extended to all the HTMLs. Now, i need to take a <main> block and put on another file, because the same block is used twice in the project. As far as I know, I can't make a {% load static %} inside an already extended file {% extends 'layouts/layout.html' %} . I tried with the <div data-include="path/file.html"></div> and with the $(document).ready( function() { $("#load_home").on("click", function() { $("#content").load("content.html"); }); }); but nothing. I guess the problem is that I'm using a custom script, and it must necessarily be paired with the HTML block using it. Any other ideas? I can't stand repeating code snippets... -
why permission denied for superuser in drf?
Here I set permission like this for normal users in my views but the permission applied for the superuser also(which i don't want). my superuser doesn't belongs to this query return qs.filter...exists() so I get permission denied. But I didn't get that why it is not granted all the permissions by default for superuser ? Or Am I missing something here ? permissions class MyPermission(BasePermission): def has_permission(self, request, view): qs = myqs if request.method in ['put', 'patch']: return qs.filter(change=True).exists() elif request.method == 'post': return qs.filter(create=True).exists() elif request.method in SAFE_METHODS: return qs.filter(view=True).exists() elif request.method == 'delete': return qs.filter(delete=True).exists() else: return False views class MyView(ListAPIView): serializer_class = MySerializer queryset =qs permission_classes = [MyPermission] settings 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], I solved the issue with this but I think it should not be necessary for superuser. permission_classes = [IsAdminUser | MyPermission] But I didn't get that why it is not granted all the permissions by default for superuser ? Or Am I missing something here ? -
How make a dropdown selects using django rest and jquery?
i need to make a dynamic dropdown selects about the brands and models of the cars. In using Django Rest and Jquery. This is my models.py models.py class Coche(models.Model): matricula = models.CharField(max_length=7,primary_key=True) concesionario = models.ForeignKey('Concesionario', on_delete=models.CASCADE) brand = models.ForeignKey('CocheBrand', on_delete=models.CASCADE) model_name= models.ForeignKey('CocheModel', on_delete=models.CASCADE) class CocheModel(models.Model): model = models.CharField(verbose_name="Modelo", primary_key=True, max_length=30) brand = models.ForeignKey('CocheBrand', on_delete=models.CASCADE) def __str__(self): return self.model class CocheBrand(models.Model): brand = models.CharField(verbose_name="Marca", primary_key=True, max_length=20) def __str__(self): return self.brand serializers.py class CocheSerializers(serializers.ModelSerializer): class Meta: model = Coche fields = ('matricula', 'brand', 'model_name', 'type_car', 'location', 'doors', 'gearshift', 'years', 'precio_final', 'horsepower', 'kilometres') views.py class CocheListing(ListAPIView): pagination_class = StandardResultsSetPagination serializer_class = CocheSerializers def get_queryset(self): queryList = Coche.objects.all() brand = self.request.query_params.get('brand',None) model_name = self.request.query_params.get('model_name',None) if brand: queryList = queryList.filter(brand = brand) if model_name: queryList = queryList.filter(model_name = model_name) def getBrand(request): if request.method == "GET" and request.is_ajax(): brand = Coche.objects.exclude(brand__isnull=True).exclude(brand__exact='').order_by('brand').values_list('brand').distinct() brand = [i[0] for i in list(brand)] data = {'brand':brand,} return JsonResponse(data, status = 200) def getModel(request): if request.method == "GET" and request.is_ajax(): model_name = Coche.objects.exclude(model_name__isnull=True).exclude(model_name__exact='').order_by('model_name').values_list('model_name').distinct() model_name = [i[0] for i in list(model_name)] data = {'model_name':model_name} return JsonResponse(data, status=200) Jquery script $(document).ready(function () { // reset all parameters on page load resetFilters(); // bring all the data without any filters getAPIData(); // get all countries … -
How to show a message on a user's account when his email is listed on database by other user?
I am trying to make a system where one user can send file to other user using django. He have to enter the file, it's description and the receiver's email. Here's my model class data(models.Model): file_id = models.AutoField(primary_key=True) file_desc = models.TextField() file = models.FileField() receiver_email = models.EmailField() When sender fills these fields and submits the form everything gets stored on database. Have a look at my view def send(request): if request.method=="POST": file_desc = request.POST['file_desc'] file = request.FILES['file'] receiver_email = request.POST['receiver_email'] db = data.objects.create(file_desc=file_desc,file=file,receiver_email=receiver_email) db.save() design = data() context={ 'file':design } user = request.user if request.user.is_authenticated: return render(request,'file_sharing.html',context) else: return HttpResponse('Please login to continue') Now i want to show a message on the user's account whose email was provided on receiver_email(above). -
from cassandra db tables to python models to be used in Django based application
I'm developing a web application using Django and Cassandra db. I have to use an external Cassandra db and integrate this legacy database in my application. My idea is to have the inverse of the operation that given some python models gives the corresponding Cassandra tables. The operation that I'd like to invert can be made, for my understanding, in several ways: in Django, after defining your models in the module models.py, running python manage.py sync_cassandra will create from the models the corresponding tables; thus using the API provided by ci sondjango_cassandra_engine; externally with respect to Django, I can use cqlengine and its command sync_table(table_name) to translate the Python classes defining my models into Cassandra tables. What I want is the inverse operation, that I am not able to perform neither using django_cassandra_engine in Django nor cqlengine externally from Django. I've tried to use python manage.py inspectdb --database=cassandra after I gave the connection parameter settings for the Cassandra db in the module setting.py as specified here. Though the output of this command in my case is: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' … -
how to find data between two date range in django rest framework?
Creating a simple view to list three columns in between two date range. On doing some research I found that we have some Django ORM that we can use. Hence I have tried to impletemt it in my views as shown below. from rest_framework.response import Response import django_filters.rest_framework from rest_framework.generics import ListAPIView from .models import Revenue from .serializers import DataListSerializers # Create your views here. class DataListView(ListAPIView): serializer_class = DataListSerializers pagination_class = None queryset = Revenue.objects.all() filter_backends = [django_filters.rest_framework.DjangoFilterBackend, django_filters.OrderingFilter] def get_queryset(self): time_filter = self.queryset.objects.filter(datefield__gte=<some_date>, datefield__lte=<some date>) As you could see that I have written a simple ListAPIView. When we execute the above query in the Django ORM console then we can give some date range. But how to incorporate the above query in the view? What would be the value for datefield__gte, and datefield__lte? -
How is file path security provided in Django?
I have created a system with Django. In this system, users can upload various files (with FileField). These files can be unimportant like profile photos or important like company files. I am afraid that any user can find the files by playing with the paths. Can I keep the user profile photos in a different path and the uploaded files in a different path? And can these uploaded files be a unique, hidden, or inaccessible path? -
Getting actual model instance after aggregating by maximum value (Django)
I have the following models: class Browser(Model): id = UUIDField() class Session(Model): id = UUIDField() browser = ForeignKey(Browser) last_activity = DateTimeField() I want to select the Session object with the latest last_activity for each unique Browser. I've tried Session.objects.values('browser').annotate(Max('last_activity')), but this does not give the actual Session instance. Is this possible in Django? I would like to avoid raw SQL if possible. -
Django Aurora RDS transaction read inconsistency
I am using django atomic transactions to create objects. I am just writing new balances for a user (1 user, many balances) repeatedly. For example, if a user starts with a balance of 10 and we want to add 2 new balances: user.add_balance(5) -> user.balance = 15 user.add_balance(3) -> user.balance = 18 However, within the same atomic block, a subsequent balance write depends on reading the current balance, which was just affected by the previous write in the same transaction (I hope that makes sense). In other words, the second transaction above (adding 3) needs to read the balance as 15, NOT 10 which is the old balance. Here is a simplified version of the code. def add_user_balance(self, amount): WalletBalance = apps.get_model("wallet", "WalletBalance") # this is terse but it is just summing all of the user's balances to get the current balance current_balance = float( WalletBalance.objects.filter(user=self, cancelled=False).aggregate( Sum("amount") )["amount__sum"] ) # this does NOT use a cached relation from within the user model, it should go to the db and does in testing # HERE is where I need the new balance within the same transaction. if float(current_balance) + float(amount) < 0: raise ValueError("balance_low") balance = WalletBalance.objects.create( amount=amount, transaction_type=transaction_type, ) … -
How to reconnect to RDS psql DB in Django
I have recently wrote a small django app which connects to the external database (AWS RDS psql instance). Authentication is done using IAM role of EC2 instance (server). Things work OK for about 15-20min. After this time the error I'm getting is: Exception Value: FATAL: PAM authentication failed for user "quietroom_dev_beanstalk_ec2" My guess is that a token generated by boto3 expires and I loose the connection. Below shows how the token is obtained. client = boto3.client('rds', region_name=REGION) password = client.generate_db_auth_token(DBHostname=DB_HOST, Port=DB_PORT, DBUsername=DB_USER, Region=REGION) If this is the case, how can I force django to reconnect to the DB with a fresh token? The error originates in the django core. At the moment I work only with Django native admin panel. Thanks in advance for your help! -
how to update(calculate) a specific filed if the object exists django
i made a project for a store , and i want to prevent from duplicate products , if the product doesnt exists then insert it into the database , but otherwise if it doesn't then just update field(quantity) models.py class Item(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() for example we have inserted this data: item = mouse , quantity = 20 then we add this data later item = mouse , quantity = 30 now what i try to whenever the item exists , just update the quantity like this (20 + 30 ) = 50 , add the previous quantity with new quantity to get total number of quantities ! is it possible please ? i've read some articles about get_or_create and update_or_create but still i dont have any idea how it work in my case !? thank you for your suggestion regards .. -
Properly wiring RPC service communication in Django application
I'm developing a Django app which needs to execute scheduled and/or long-running tasks. To achieve this, I've set up a service using the rpyc, paired with the apscheduler package in order to execute jobs. It seems to work well so far, but I'm wondering if more experienced developers could give me their opinion because I worry that certain aspects of my design indicate a code smell. This is the generic flow of what I am doing: Make request to a particular view Instantiate connection to service IN view Invoke an add_job method exposed by the RPC service to schedule a job Register a callback that is called with successful execution of the particular job view returns and connection is closed/dropped Currently, I instantiate a Connection instance in the View, meaning that a new connection instance is made with the appropriate request to the Django View and this is dropped after the view returns. Due to the way that apscheduler works, it requires that callables set to execute as a deferred jobs must be globally accessible, so any callable that I wish to add as a job that is not already in the namespace of the service cannot be a remote … -
How Django's "override_settings" decorator works when launching tests in parallel
I'm checking how Django's settings module is built and how the override_settings decorator deals with the settings when testing and I just can't see how the implementation of this decorator avoid problems when running the tests in parallel. I see that it in the enable method it assigns to the settings' _wrapped attribute the settings values with the changes applied and that it stores a copy of the previous values that is then restored in the disable method. This works OK with me when executing it secuentially. But when running tests in parallel I can't see how this works without affecting other tests that also use the decorator, let's say to overwrite the same value. What I see is that the value set by the latest executed test will be returned everywhere when accessing settings.OVERRIDDEN_SETTING. In fact, this settings overriding should also affect the values returned in other tests even if they are not decorated. I mean, if we have these two tests: @override_settings(SETTING=1): def test_1(self): ... ... print(settings.SETTING) @override_settings(SETTING=2): def test_2(self): ... ... print(settings.SETTING) def test_3(self): ... ... print(settings.SETTING) If they are run in parallel, and let's say test_1 is executed, starts executing it's code and in the meanwhile … -
Hi guys,Trying to get past the user registration as I assign groups to different users through giving different permisions. Kindly assist
Traceback (most recent call last): File "/home/alvin/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/alvin/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/alvin/.local/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) TypeError: 'NoneType' object is not callable [28/Apr/2021 10:17:24] "GET / HTTP/1.1" 500 70741 from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.users.groups.exists(): group = request.users.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse("You are not allowed to view this page!") return wrapper_func return decorator -
Cookies not create in browser django rest
I am trying to do authorization via access token in cookie. But i am having trouble setting cookies with react. I set cookies in login: class ApiLoginView(APIView): permission_classes = [AllowAny] def post(self, request, ): password = request.data.get("password") email = request.data.get("email") user = authenticate(username=email, password=password) if user: try: user.auth_token.delete() except Exception as e: pass Token.objects.create(user=user) response = Response() response.set_cookie(key='access_token', value=user.auth_token.key, httponly=True) response.data = {"result": True, "token": user.auth_token.key} print(request.COOKIES) auth.info("user {} login".format(user)) return response else: return JsonResponse({"error": "Wrong Credentials"}, status=status.HTTP_400_BAD_REQUEST) If I auth into postman, everything goes well and the cookies are set. print(request.COOKIES) {'csrftoken': 'JZ1OOBZ0Ilxwo8Zt7DR0SbQ8MUMyNjiPhKYOIUQqY3OeXBEheeUoIa9MSI5S0HXG', 'access_token': 'd67ab794f8752ef02bcba5418bef2c6f87cb74f2'} But if you do it through the frontend, I get only this {'_ym_uid': '1612967974591822622', '_ym_d': '1614006098'} My frontend request: const response = await fetch("httpS://blablabla/api/auth/login", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); I also have cors headers configured CORS_ALLOW_CREDENTIALS = True -
How to set exact url route in django while others are dynamic?
So I build a simple vanilla JS frontend SPA that querys recipes from my own REST API that I build with django rest framework and of course I need to access the /admin route in order to add recipes. This is my routing at the moment: from django.contrib import admin from django.urls import path, re_path, include from django.views.generic import TemplateView urlpatterns = [ re_path(r'^admin/$', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), path('<id>', TemplateView.as_view(template_name='index.html')), path('api/', include('recipes.urls')) ] Now if someone wants to share a recipe with domain.com/<id> this should not be a problem and currently it works this way, but because I have this weird setup where anything in the pathname gets searched as an id the /admin route does not reach its desired location. I would be interested in a solution where I pass a exact keyword to the url-param for django to know when it gets a hit to return the admin page. My idea at first was a regular expression but it does not seem to work, any idea why? I also tried to match the <id> as an INT as shown in the docs. But I do not need for django to pass the <id> into a view because my JavaScript … -
drf-yasg: Change the request name appearing in redoc ui
enter image description here How do I change the name of the request that appears automatically in redoc-ui when using drf-yasg. For example: In the image, you can see that that the request is named fid_data-entities_update, it is picking this up from the url. How do I override/rename it to update data entities name -
Pass JSON object instead of array in AJAX call ->DJANGO
i have a code which should pass JSON object to another page using AJAX in django , currently when i use array it is working fine , but when i converted that to json object it is neither throwing success alert nor error alert , No idea why . Below is the code : $("[name=submit]").click(function(){ var myarray = []; $(".form-check-input:checked").each(function() { console.log($(this).val()); myarray.push($(this).val()); //push each val into the array }); var jsonObj = {}; for (var i = 0 ; i < myarray.length; i++) { jsonObj["position" + (i+1)] = myarray[i]; } var formdata = new FormData(); formdata.append('myarray', jsonObj); formdata.append('csrfmiddlewaretoken', $("[name=csrfmiddlewaretoken]").val()); formdata.append('RestartSubmit', 'RestartSubmit') $.ajax({ url: "secondtableonDashboard", //replace with you url method: 'POST', data: formdata, processData: false, contentType: false, beforeSend: function(){ // Show image container $("#loader").show(); }, success: function(data) { alert("message: " + data.message); var newDoc = document.open("text/html", "replace"); newDoc.write(data); newDoc.close(); $('#example').hide(); alert(data) }, error: function(error) { // alert('error..'+error); alert("ERROR") } }); }); so here i gave alert for both error and success but both of them is not showing up . Can anyone of you help . -
Django moving model from one app to another - ValueError: The field was declared with a lazy reference but app doesn't provide model
I am trying to move a model from one application to another. I created two migrations for this purpose. Migration 1 State operation - Creates model(Foo) in new app Migration 2 - Database operation - Alter all the models which have a foreign relation to Foo to point to new app. State operation - Deletes model(Foo) in old app When I ran the migrations on my company database, it worked fine and the model was migrated to new app. But when I am running all the migrations to create my local database, it is throwing this error. Somehow the foreign models are still pointing to the model in old app, not able to figure out where this is happening? Can someone please help. Command: python manage.py migrate main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 191, in handle pre_migrate_apps = pre_migrate_state.apps File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/db/migrations/state.py", line … -
Django computing variable vaue in custom middleware and passing to all view functions
I am using Django 3.2. I want to compute the value of variable and make that value available to all views in my project. I have decided to use middleware - but it is not clear (yet), how I can make the value I computed in MyCustomMiddleware available in a view. Here is my custom middleware class: class MyCustomMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. mysecret_value = 4269 return response After making the requisite modifications to the MIDDLEWARE section in settings.py, how do I acesss mysecret_value in my views? myapp/views.py def foobar(request): the_value = mysecret_value # <- how do I access the RHS variable? -
I want to target AUTH_USER_MODEL to a custom user model in sub directory
my project structure is like below: ./apps ./apps/bizusers ./apps/bizusers/admin.py ./apps/bizusers/apps.py ./apps/bizusers/models.py ./apps/bizusers/serializers.py ./apps/bizusers/tests.py ./apps/bizusers/views.py ./apps/bizusers/__init__.py ./apps/__init__.py ./config ./config/asgi.py ./config/settings.py ./config/urls.py ./config/wsgi.py ./config/__init__.py ./manage.py ./requirements.txt My custom user model is in ./apps/bizusers/models.py I have this in settings: INSTALLED_APPS = [ 'apps', ] I added AUTH_USER_MODEL = "bizusers.User" in settings.py I have tried to edit ./apps/__init__.py and ./apps/bizusers/apps.py but I cannot get it to work. I have tried these solutions below: having models directory and AUTH_USER_MODEL Model in sub-directory via app_label? 'MyAppConfig' must supply a name attribute Thanks. -
Django Rest Framework cannot access foreign key
I am trying to create a product which contains a foreign key yet when sending some JSON it doesn't work. My models : class Category(models.Model): name=models.CharField(max_length=200) objects = CategoryManager() def __str__(self): return self.name class Product(models.Model) : name=models.CharField(max_length=200) price=models.IntegerField(default=0,blank= True, null=True) category = models.ManyToManyField(Category, blank=True, null=True) The serializers: class CategorySerializer(serializers.ModelSerializer) : class Meta : model = Category fields = ['name'] class ProductSerializer(serializers.ModelSerializer) : category = CategorySerializer(many= True) class Meta : model = Product fields = ['name','price', 'category'] The JSON I send (for ex.): { "name": "HelloThere", "price": 30, "category": { "name": "GeneralKenobi" } } the view : @api_view(['GET', 'POST']) def productcreate(request): serializer = ProductSerializer(data=request.data) if serializer.is_valid() : serializer.save() return Response(serializer.data) When posting the data as it is, I create a product which has a name and a price but category doesn't work. Thanks in advance for your help,