Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow only the owners of the parent model to create a child model when utilising generic views (django-guardian)
Currently, I have two models, Parent and Child, with a one-to-many relationship. I am using the built-in generic class-based views for CRUD upon a Parent, where I'm using a django-guardian mixin to prevent users who do not own the Parent object from doing these operations, which works well. However, I want to be able to add Children to a Parent. This works fine using a generic CreateView and a modelform, where the pk of the parent is a kwarg passed in the url. However if the user changes the pk in the URL to another user's Parent object's pk, they can add a Child object to it. I want to use django-guardian (or some other means) to prevent a user from adding a Child to another User's Parent object. Can this be done or must it be done some other way? I have got it working by validating the Parent object belongs to the current user within get_form_kwargs in the CreateView but this seems hacky, and would prefer django-guardian. (I am also not using the 'pk' kwarg in production, and instead using a different 'uuid' kwarg, but I'd like to fix this security hole nonetheless). -
Pass a list of OrderedDicts from validated_data to **kwargs
with a ModelSerializer I needed to pass multiple generic relations and it works well. However, I need to recreate many for loops within the update/create methods for it work how could I pass them as **kwargs in a function since the outcome is a list of OrederedDicts? For instance I have two models: models.py: class Translation(models.Model): """ Model that stores all translations """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.CharField(max_length=50, null=True, blank=True) content_object = GenericForeignKey() lang = models.CharField(max_length=5, db_index=True) field = models.CharField(max_length=255, db_index=True, null=True) translation = models.TextField(blank=True, null=True) class Tags(models.Model): """ Tags Model """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) DISEASE = 0 TYPE = [(DISEASE, 'disease')] type = models.PositiveSmallIntegerField(choices=TYPE) name = GenericRelation(Translation) # < ------- description = GenericRelation(Translation) # < ------- serializer.py: class TranslationSerializer(serializers.ModelSerializer): """ Translation serializer to be nested into other serializers that needs to display their translation. """ # id added to be used on create/update query only # since it is not instantiated. id = serializers.IntegerField(required=False) class Meta: model = Translation """ Fields: object_id and content_type are not required and are passed dynamically. Uncomment if needed. """ fields = ["id","lang","translation","field"] class TagsSerializer(serializers.ModelSerializer): """ Tag serializer with generic relation to field 'name' and 'description'. """ name … -
Frameworks recommended for a structural engineering web-based app
I want to make a web-app that gets user input and makes structural analysis (say finite element analysis) and presents the results with a UI that includes 3D graphics (e.g. OpenGL). An example app is skyciv for those who know, but mine will be a lot simpler at the moment. I know Python, Qt and OpenGL enough to make a desktop app for my purposes. However, I want to make the code run online and people to use it anywhere without having to install the app. Plus I want to make a subscription page. What programming languages/frameworks would you recommend me to focus on in addition to Python, Qt and OpenGL for this purpose? Would Django + React + WebGL be a good combination? Would you recommend any other 3D graphics render library other than OpenGL? Thank you. -
Is there a way to have multiple names for the same integer in django IntegerChoices
So this is what im trying to do which obviously isnt working it is giving me an error because i am setting both names to the same value which is giving me duplicate integer choices: ValueError: duplicate values found in <enum 'EventTypes'>: Launched -> ExperienceLaunched, Downloaded -> ExperienceFinishedLoading, Closed -> ExperienceClosed class EventTypes(models.IntegerChoices): ExperienceLaunched = Launched = 0, ExperienceFinishedLoading = Downloaded = 1, ExperienceClosed = Closed = 2 event = models.IntegerField(choices=EventTypes.choices) -
Javascript card search filter card overview page
So I am currently building an overview page with a lot of cards which include data such as route name, number of routes, strarting point and date. Now im trying to build a filter using javascript where the user can filter on the route name, number of routes, strarting point and date so that the user can search for the specific card. Currently I have 6 cards with data and when I type in the search input field it just deletes the first 4 cards and shows the last 2. I used some unnecessary classnames like route__text, these were just for the purpose of trying to fix my search filter. My code: Help would be greatly appreciated const input = document.getElementById('search'); input.addEventListener('keyup', search); function search() { const inputValue = input.value; console.log(inputValue.toLowerCase()); const routeContainer = document.getElementById('route'); const routeDetail = routeContainer.getElementsByClassName('route__filter'); console.log(routeDetail); for(let i = 0; i < routeDetail.length; i++) { let searchTerm = routeDetail[i].querySelectorAll(".route__parent td.route__text"); // console.log(typeof searchTerm); for(let i = 0; i < searchTerm.length; i++) { let correctSearch = searchTerm[i]; console.log(correctSearch.innerHTML.toLocaleLowerCase()); if (correctSearch.innerHTML.toLowerCase().includes(inputValue.toLowerCase())) { routeDetail[i].style.display = ""; } else { routeDetail[i].style.display = "none"; } } } } search(); <div class="route" id="route"> <div class="row"> <div class="col-12 d-flex justify-content-end mb-4"> <input type="search" … -
NOT NULL constraint failed: accounts_personalcolor.user_id
I am new to Django and have trouble making django-rest-framework API for post, inheriting APIView. I'm using a serializer, that inherits djangos ModelSerializer. I face NOT NULL constraint failed: accounts_personalcolor.user_id error whenever I try saving the serializer or model object. color.js posts image using Django rest framework as follows. function PersonalColorScreen({navigation,route}) { const {image} = route.params; console.log('uri is', image.uri); const [userToken, setUserToken] = React.useState(route.params?.userToken); const requestHeaders = { headers: { "Content-Type": "multipart/form-data" } } // helper function: generate a new file from base64 String //convert base64 image data to file object to pass it onto imagefield of serializer. //otherwise, serializer outputs 500 Internal server error code const dataURLtoFile = (dataurl, filename) => { const arr = dataurl.split(',') const mime = arr[0].match(/:(.*?);/)[1] const bstr = atob(arr[1]) let n = bstr.length const u8arr = new Uint8Array(n) while (n) { u8arr[n - 1] = bstr.charCodeAt(n - 1) n -= 1 // to make eslint happy } return new File([u8arr], filename, { type: mime }) } //random number between 0-9 function getRandomInt(max) { return Math.floor(Math.random() * max); } // generate file from base64 string const file = dataURLtoFile(image.uri, `${getRandomInt(10)}.png`) const formData= new FormData(); formData.append('img',file,file.name); console.log(file.name); //axios post request to send data // axios.post('http://localhost:8000/accounts/personalcolor/', formData,requestHeaders) … -
Check if record exists when bulk POST'ing with Django REST Framework
I have a list dictionaries which I've parsed to JSON with json.dumps(). I would now like to POST this data to my database using Django REST framework. # Example Data to POST [ { "key_1":"data_1", "key_2":"data_2", }, { "key_1":"data_1", "key_2":"data_2", }, { "key_1":"data_3", "key_2":"data_4", } ] If we imagine that all entries are unique (which isn't the case with the above example dataset), we can successfully batch POST this data with: # models.py class data(models.Model): data_1 = models.CharField(max_length=64, blank=True, null=True) data_2 = models.CharField(max_length=64, blank=True, null=True) class Meta: unique_together = (( "data_1", "data_2")) # serializers.py class dataSerializer(serializers.ModelSerializer): class Meta: model = data fields = '__all__' # views.py class dataViewSet(viewsets.ModelViewSet): queryset=data.objects.all() serializer_class=dataSerializer filter_backends=[DjangoFilterBackend] filterset_fields=['key_1', 'key_2'] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) # Initiating the POST request api_url="localhost:8000/app/api/" requests.post( f"{api_url}data/", data=my_json_serialised_data, headers=headers ) However, this will fail if some records already exist in the database ("fields must be unique together"). As per the example data, entries in the list will occasionally already be present in the database and I would therefore like to avoid POST'ing duplicates (based on the combination of fields in the model; I have specified unique_together to be … -
How to make sure this order is retained
I want to make know what's the best way to make sure this order is retained, I think the best thing will be to apply a function that operates on this on the fly, while sqlite retains the order, postgres doesn't it reorders it when it's saved to the database, list_of_dicts = [[{'id': '3', 'text': ' Perpetual ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '1', 'text': ' Miles .T Morales ', 'score': 1}], [{'id': '3', 'text': 'Perpetual ', 'score': 3}, {'id': '1', 'text': 'Miles .T Morales ', 'score': 2}, {'id': '2', 'text': 'Peter Parker ', 'score': 1}], [{'id': '1', 'text': 'Miles .T Morales ', 'score': 3}, {'id': '3', 'text': 'Perpetual ', 'score': 2}, {'id': '2', 'text': 'Peter Parker ', 'score': 1}], [{'id': '3', 'text': ' Perpetual ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '1', 'text': ' Miles .T Morales ', 'score': 1}], [{'id': '1', 'text': ' Miles .T Morales ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '3', 'text': ' Perpetual ', 'score': 1}], [{'id': '2', 'text': ' Peter Parker ', 'score': 3}, {'id': '3', 'text': ' Perpetual ', 'score': 2}, {'id': '1', … -
Pre Populate Django Users From LDAP
I'm using Django Auth LDAP for authentication for my django app. However, the user object is not created until the user attempts to log in. So I'm trying to pre populate all the users from ldap, but currently it is not populating any fields other than name and username. Not email, not is_superuser, etc. Code to get list of usernames then attempt to populate users: from django_auth_ldap.backend import LDAPBackend l = ldap.initialize(LDAP_SERVER_URI) l.protocol_version = ldap.VERSION3 l.simple_bind(LDAP_BIND_DN, LDAP_BIND_PASS) search_filter = LDAP_USER_SEARCH_FILTER attributes = ['*'] backend = LDAPBackend() results = l.search_s(LDAP_USER_SEARCH_BASE, ldap.SCOPE_SUBTREE, search_filter, attributes) return Response(results) for query, u in results: username = u[LDAP_ATTR_USERNAME][0].decode('utf-8') user, created = backend.get_or_build_user(username, u) if created: user.save() backend.populate_user(username) log.debug(f'Pre-populate: {user}, {user.email}') How can I create all the users and have their info set correctly as if they logged in with django-auth-ldap, without them having to login? -
Get url variable and value into urlpatterns in Django
I was trying to get the variable and value of a url in urlpatterns in Django. I mean, I want to put in the address of the browser type: https://place.com/url=https://www.google.es/... to be able to make a translator. And be able to pick up the variable and value in the function that receives. At the moment I'm trying to get it with re_path like this: from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index), re_path('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', views.index_traductor), ] The regex match picks it up, but I don't know how to send it as a value in a variable to receive here: from django.http import HttpResponse def index(request): return HttpResponse("flag") def index_traductor(request, url=''): return HttpResponse("%s" % url) I get a blank page. Any ideas? -
Streaming Audio Files from Django Backend to Vue.js Frontend
I'm currently building a soundboard for our Pen and Paper session and I am loading the sounds as a static source from my Django backend as new Audio(data.url). I am simply using the Django Rest Framework to handle everything about the file data, like uploads and accessing the sound files: class File(models.Model): file = models.FileField(upload_to='sound-files') filename = models.CharField(max_length=100) looped = models.BooleanField() type = models.CharField( max_length=16, choices=[('bgm', 'background music'), ('sfx', 'sound effects')], default="bgm" ) But the initial loading time for the clients may be long as it needs to load a bigger 1 hour sound file for example, so I want to stream the audio instead of load it as a src. How can I go about implementing this in Django? Do I need to use another module on top of DRF or do I need to replace DRF entirely? And can I keep the instantiation of the new Audio() in the Frontend or is a different approach required there? -
How To Fix Django "127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS" in python
Whenever I Login With Agent User. Where Agent Only Have Perms to Access Leads Page and Agent Can't See Any other pages. But When I open /lead It Raise An Error 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS app urls.py from django.urls import path from .views import ( LeadDetailView, leadlistview,LeadCreateView, LeadUpdateView, LeadDeleteView, AssignAgentView, CatogoryListView, CatogoryDetailView, LeadCatagoryUpdateView ) app_name = "leads" urlpatterns = [ path('', leadlistview.as_view(), name='lead-list'), path('<int:pk>/', LeadDetailView.as_view(), name='lead-detail'), path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'), path('<int:pk>/delete/', LeadDeleteView.as_view(), name='lead-delete'), path('<int:pk>/assign-agent/', AssignAgentView.as_view(), name='assign-agent'), path('<int:pk>/category/', CatogoryDetailView.as_view(), name='lead-catagory-update'), path('create/', LeadCreateView.as_view(), name='lead_create'), path('categories/', CatogoryListView.as_view(), name='catagory-list'), path('categories/<int:pk>/', CatogoryDetailView.as_view(), name='catagory-detail'), ] app views.py from django.core.mail import send_mail from django.shortcuts import render, redirect from django.urls import reverse from django.views import generic from .models import Lead, Agent, Catagory from django.contrib.auth.mixins import LoginRequiredMixin from .forms import (LeadModelForm, LeadModelForm, CustomUserCreationForm, AssignAgentForm, LeadCategoryUpdateForm, ) from agents.mixxins import OrganizerAndLoginRequiredMixin # Create your views here. class LandingPageView(generic.TemplateView): template_name = "landing.html" def landing_page(request): return render(request, 'landing.html') class leadlistview(OrganizerAndLoginRequiredMixin,generic.ListView): template_name = "lead_list.html" context_object_name = "leads" def get_queryset(self): user = self.request.user # initial queryset of leads for the entire organisation if user.is_organisor: queryset = Lead.objects.filter( organisation=user.userprofile, agent__isnull=False ) else: queryset = Lead.objects.filter( organisation=user.agent.organisation, agent__isnull=False ) # filter for the agent that is logged in queryset = queryset.filter(agent__user=user) return queryset def … -
Installing ruamel.yaml.clib with docker
I have a small project in django rest framework and I want to dockerize it. In my requirements.txt file there is a package called ruamel.yaml.clib==0.2.6. While downloading all other requirements is successfull, there is a problem when it tries to download this package. #11 208.5 Collecting ruamel.yaml.clib==0.2.6 #11 208.7 Downloading ruamel.yaml.clib-0.2.6.tar.gz (180 kB) #11 217.8 ERROR: Command errored out with exit status 1: #11 217.8 command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py'"'"'; file='"'"'/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-n2gr5j35 #11 217.8 cwd: /tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/ #11 217.8 Complete output (3 lines): #11 217.8 sys.argv ['/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py', 'egg_info', '--egg-base', '/tmp/pip-pip-egg-info-n2gr5j35'] #11 217.8 test compiling /tmp/tmp_ruamel_erx3efla/test_ruamel_yaml.c -> test_ruamel_yaml compile error: /tmp/tmp_ruamel_erx3efla/test_ruamel_yaml.c #11 217.8 Exception: command 'gcc' failed: No such file or directory #11 217.8 ---------------------------------------- #11 217.8 WARNING: Discarding https://files.pythonhosted.org/packages/8b/25/08e5ad2431a028d0723ca5540b3af6a32f58f25e83c6dda4d0fcef7288a3/ruamel.yaml.clib-0.2.6.tar.gz#sha256=4ff604ce439abb20794f05613c374759ce10e3595d1867764dd1ae675b85acbd (from https://pypi.org/simple/ruamel-yaml-clib/) (requires-python:>=3.5). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. #11 217.8 ERROR: Could not find a version that satisfies the requirement ruamel.yaml.clib==0.2.6 (from versions: 0.1.0, 0.1.2, 0.2.0, 0.2.2, 0.2.3, 0.2.4, 0.2.6) #11 217.8 ERROR: No matching distribution found for ruamel.yaml.clib==0.2.6 However, there is no problem … -
What is the best practice for having html tags change their style after changing URL in Django?
Suppose I have this kind of navbar, the buttons in which turn white when you click it (adding an "active" class). But if the button redirects to a new url, the navbar renders anew, and the home icon is highlighted as it is by default. How to drag that "active" class on a button after a redirect? What is the best practice in that regard? Do I ask the wrong question? -
React is not displaying Rich-Text-Content from django
I am using django as backend and react as frontend, I am using tinymce to create description in django-admin page , But react is displaying description content with html tags Ouput: <p>Best Cough Syrup</p> I used dangerouslySetInnerHTML but page is not loading any content <div dangerouslySetInnerHTML={product.description} /> Is there any way to solve this issue -
Can not implement facebook oauth into my django app
I prepared backend to imlement facebook oauth. I set up all setiings as expected in docs SOCIAL_AUTH_FACEBOOK_KEY = os.getenv("FACEBOOK_APP_KEY") SOCIAL_AUTH_FACEBOOK_SECRET = os.getenv("FACEBOOK_APP_SECRET") SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'email' } AUTHENTICATION_BACKENDS = ( # Important for accessing admin with django_social 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) This is my link to get facebook oauth page {{baseUrl}}/api/auth/social/o/facebook/?redirect_uri={{redirect_uri}} Redirect url matches to facebook app's ap domain When i am going to facebook oauth page i get Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. if i didn't give needed information, ask me for it and i will add it. -
Should I store static files in a separated S3 when deploying with AWS Elastic Beanstalk?
I've got a Django app running on AWS Elastic Beanstalk. Beanstalk created an S3 bucket to store the source code, versions, etc. I've configured the S3 bucket to store also my static files. Every time I deploy a new version of the code, eb runs the collectstatic command correctly and creates the static files, but it overrides the permissions. So for every new deploy, I need to go, select the static folder and make the objects public manually. Question: Is it correct to store my static files in the same bucket, or should I create a separate one with a public policy? Question 2: If it's better to use the same bucket, how can I define a public policy for the static folder, but not the other folders such as the source code? -
need help for change attribute of models on view
i need to change attribute of my models on views but this my code dosent work view: class TaskRequest(APIView): permission_classes = [IsBenefactor,] def get(self ,request, task_id): obj = Task.objects.get(id=task_id) if not obj: raise Http404("not found") if obj.state==obj.TaskStatus.PENDING: data={ 'detail': 'This task is not pending.' } return Response(data , status=status.HTTP_404_NOT_FOUND) else: obj.assign_to_benefactor(self , obj.assigned_benefactor) obj.save() data={ 'detail': 'Request sent.' } return Response(data , status=status.HTTP_200_OK) my code of view get object If not available return 404 error if available and state equal to PENDING return some data otherwise change state to Waiting and assigned to benefactor user but this my code doesnt work what can i do ? and my models : class Task(models.Model): class TaskStatus(models.TextChoices): PENDING = 'P', 'Pending' WAITING = 'W', 'Waiting' ASSIGNED = 'A', 'Assigned' DONE = 'D', 'Done' title = models.CharField(max_length=60) state = models.CharField( max_length=1, default=TaskStatus.PENDING, choices=TaskStatus.choices, ) charity = models.ForeignKey(Charity, on_delete=models.CASCADE) description = models.TextField(blank=True) assigned_benefactor = models.ForeignKey( Benefactor, on_delete=models.SET_NULL, null=True, ) date = models.DateField(null=True, blank=True) age_limit_from = models.IntegerField(null=True, blank=True) age_limit_to = models.IntegerField(null=True, blank=True) gender_limit = models.CharField( max_length=2, choices=User.Gender.choices, default=User.Gender.UNSET, ) def assign_to_benefactor(self, benefactor): self.state = Task.TaskStatus.WAITING self.assigned_benefactor = benefactor self.save() -
Combining ordering and pagination in Django
I am using rest_framework.pagination.LimitOffsetPagination in combination with Django's sort filter (with filter_backends = [OrderingFilter] and ordering_fields in my view). The problem is that Django appears to be applying the sort on the pagination results, and not the other way around. Analogy with a list: If the results of the get_queryset are: ['b', 'e', 'c', 'a', 'd', 'f'] Pagination is applied first (e.g. with a limit of 3): ['b', 'e', 'c'] And then the results are sorted: ['b', 'c', 'e'] The result I would expect, however, is: ['a', 'b', 'c'] Any ideas how I can get sorting applied before pagination? Thank you very much in advance. -
django create super user command
Cmd pic Cmd 2 pic Cmd 3 pic Cmd5 pic hello , I had tried to use the createsuperuser command, it did not work, please can u help? The pics show the steps i used on windows cmd . I would have written it in text but its was not getting copied. Sorry, if u are not supposed to ask these easy qustions. -
Django Rest with Vuejs
I would like to run DjangoRest and Vuejs app on the same server. Something like this: PORT 8081 -> DjangoRest 8080 -> Vuejs app Deployment is successful and everything works except static files are not served correctly. On address http://{ip}:8081 static files are served correctly but on port 80 they are not. Isn't proxy_pass only proxying the request to port 8081 and everything should work the same way it works on port 8081? Thanks! -
CORS missing allow origins with login_required Django
here it is my problem as i said in title i have an issue with cors. I created a view with a "login_required" and since i have the error "cors missing allow origin", my get request worked fine before i set the login_required. Im using Django rest Framework i tried everything, i modified settting.py with allow_host, cors_origin_white_list, corsheader in installed app, add header options in my axios request, etc... the view class essai2(APIView): serializer_class = ComSerializer def get(self, request): Pictos = Pictograms.objects.all() data = ComSerializer(Pictos, many=True).data if data: return Response(data, status=status.HTTP_200_OK) the axios request (im using reactjs) useEffect(() => { axios.get("http://127.0.0.1:8002/com/test").then(function (response) { console.log("coucou"); setpictos(response.data); }) }, []); setting.py CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_ORIGIN = ["http://localhost:3000",] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] im using the build-in django login system so if there is no user logged in i have a redirect to login page and everything works fine on the server side, datas display when im logged in but i cant get datas on the client side even if there is a user logged in. -
How to decrypt a value on a different service that it was originally encrypted with Fernet?
I'm playing around with a project that is python backend-based. I'll have Django for the "core" stuff and FastAPI for some crawlers. I'm encrpting some data to the DB with Django using the Fernet module and a custom Field. class EncryptedField(models.CharField): description = "Save encrypted data to DB an read as string on application level." def __init__(self, *args, **kwargs): kwargs["max_length"] = 1000 super().__init__(*args, **kwargs) @cached_property def fernet(self) -> Fernet: return Fernet(key=settings.FERNET_KEY) def get_internal_type(self) -> str: return "BinaryField" def get_db_prep_save( self, value: Any, connection: BaseDatabaseWrapper ) -> Union[memoryview, None]: value = super().get_db_prep_save(value, connection) if value is not None: encrypted_value = self.fernet.encrypt(data=force_bytes(s=value)) return connection.Database.Binary(encrypted_value) def from_db_value(self, value: bytes, *args) -> Union[str, None]: if value is not None: decrypted_value = self.fernet.decrypt(token=force_bytes(s=value)) return self.to_python(value=force_str(s=decrypted_value)) Everything work as expected, the problem is when I try to decrypt the value on FastAPI side: def decrypt(value: bytes): return Fernet(FERNET_KEY).decrypt(token=value) Some important information: I double check and settings.FERNET_KEY == FERNET_KEY, ie, I'm using the same key on both sides. Both services share the same DB and the function are receiving different values when reading for it. Django -> from_db_value -> value -> b"gAAAAABhSm94ADjyQES3JL-EiEX4pH2odwJnJe2qsuGk_K685vseoVNN6kuoF9CRdf2GxiIViOgiKVcZMk5olg7FrJL2cmMFvg==" FastAPI -> from_db_value -> value -> b"pbkdf2_sha256$260000$RzIJ5Vg3Yx8JTz4y5ZHttZ$0z9CuQiPCJrBZqc/5DvxiEcbNHZpu8hAZgmibAe7nrQ=". I actually enter inside the DB and checked … -
How I can Extend templates In djnago?
enter image description here {% extends "index.html" %} {% block content %} <h1>test for the extend</h1> {% endblock %} extend block is not working ? please any advice -
Set default number of entries in Django formset modal table
I have a modal which displays a formset with a list of items (see screenshot) The default number of items is 10, which I want to change. I can't figure out where the settings are to change this. This is my forms.py: class AddTrackerForm(forms.Form): cubecontainerdetail = forms.CharField(required=False, widget=forms.HiddenInput()) boolean = forms.BooleanField(required=False) id = forms.IntegerField( required=False, label='id') name = forms.CharField( required=False, label='Name') school_year = forms.CharField( required=False, label='School Year') year = forms.CharField( required=False, label='Tracker Year') tracker_type = forms.CharField( required=False, label='Tracker Type') This is my views.py: class TrackersListView(ListView): """ View list of trackers """ model = EstablishmentCubeContainer template_name = 'trackers/trackers_list.html' def get_formset(self): tracker_formset = formset_factory(AddTrackerForm, extra=0) tracker_list = CubeContainerDetail.objects.filter(year=current_year) initial_formset = [] for tracker in tracker_list: data = { 'id': tracker.id, 'name': tracker.name, 'school_year': tracker.school_year, 'tracker_type': tracker.cubecontainertag.name, 'year': tracker.year, } initial_formset.append(data) return tracker_formset(initial=initial_formset) This my html : <form method="POST" action="{% url tracker_create_url establishment.id %}" id="trainer_form">{% csrf_token %} <div id="listview" class="tab-pane active display"> {{ form.management_form }} <table class="cell-border table table-striped map_table display nowrap table-condensed" id="tracker-list-table" style="width:100%;"> <thead> <tr> <th>Selected</th> <th>ID</th> <th>Name</th> <th>School Year</th> <th>Type</th> <th>Tracker Year</th> </tr> </thead> <tbody> {% for query in form %} <tr> <td> <input type="checkbox" value={{ query.boolean }}</td> <td>{{ query.id }}</td> <td>{{ query.name.value }}</td> <td>{{ query.school_year.value }}</td> <td>{{ query.tracker_type.value }}</td> …