Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access end points of Angular Application after deployment?
I have developed one app in Angular and it's running at local server very fine. Now, I have uploaded same app "Dist" folder to my server (linux) having WSGI + Apache server. I also run Django as backend server framework. I am doing this first time. I have made changes in Django and added index.html. The App is displaying only index.html just like local server. However, how can I access routes further? or end points? Any step by step guidance is available with full application? As mentioned, the app is working fine at local server with routes. http://localhost:4200/ or I want same with, http://my domain/end points Right now my domain is rightly pointing to index.html using Django framework. I have also inspected the page. There is no error in loading the page. Now only question is to access further routes- App module, and another modules. -
handling request priority in web sites
as a newbie in web programming i have an web project with a library study area rezervation system. i am doing the project with django and bootstrap5. so here is the question. how can i handle the rezervation request that come in the same time. there will be levels between my users like student, lecturer and guest. i want to give priority to student. also how can handle giving priority to between users who is in same level, is it (in same level prioritize) something i could do or does server decide what will be? if you give me any idea or title for search I would appreciate it. -
Passing a JSON object from Django to Javascript doesn't work properly
I need to pass a json object to a javascript script in Django. I used the method described here: Django: passing JSON from view to template Here is my view: def test_json(request): data = {} data['key'] = 'value' json_data = json.dumps(data) return render(request, 'test_json.html', {'json_data':json_data}) And my template: {{ json_data|json_script:"json_data" }} <script> const mydata = JSON.parse(document.getElementById("json_data").textContent); const keys = Object.keys(mydata); console.log(keys); </script> But the console output is this: [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" ] It is like it doesn't recognize the keys but recognize every character of the json object as a key, it is like is not recognizing the JSON structure. If I change the script in the template like this: {{ json_data|json_script:"json_data" }} <script> // const mydata = JSON.parse(document.getElementById('json_data').textContent); //const keys = Object.keys(mydata); //console.log(keys) let text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}'; const obj = JSON.parse(text); const keys1 = Object.keys(obj); console.log(keys1) </script> Output: [ "employees" ] I get the key properly. It is like in the process of feeding the JSON from Django to the template the problem. … -
Can I use JavaScript Variables inside a Django Project
I have written some JavaScript Code for my Django Project. ` let current_theme = 0; function darkmode() { if (current_theme == 0) { document.body.classList.add("darkmode") current_theme = 1; } else if (current_theme == 1) { document.body.classList.remove("darkmode") current_theme = 0; } } function switchMode() { if (current_theme == 0) { document.body.classList.add("darkmode") current_theme = 1; const lightModeBox = document.querySelector(".wrapper"); lightModeBox.classList.remove("show"); } else if (current_theme == 1) { document.body.classList.remove("darkmode") current_theme = 0; const lightModeBox = document.querySelector(".wrapper"); lightModeBox.classList.remove("show"); } } ` When I start the project (python manage.py runserver) and I go into the DevTools it says: Error When I click on the first link it doesn't show the declaration of the Variable. Error JavaScript I tried declerate the Variable inside the function, but that doesn't work. How else can I implement this? Thank you :) -
working with django Viewflow by non-superusers not superuser
I'm learning django viewflow (non-Pro) and the all processes that I've been creating works for superuser users only is any way to use django viewflow by normal user or non superuser or another way to disable django permission checking for django viewflow please help me. error list when i refer to process list in app: ...\lib\site-packages\viewflow\flow\views\mixins.py", line 24, in dispatch return permission_required(self.flow_class._meta.view_permission_name, raise_exception=True) -
How to customize drf-yasg / drf-spectacular open api schema for aws gateway integration?
I have a requirement to integrate all the api urls in my django service with AWS gateway. I tried importing the open api spec(swagger json) generated by drf-yasg/drf-spectacular into aws. But this seems create only the resources and methods for the api in the gateway. I notice that, in order to setup the method request, integration request and integration response for all the methods automatically during import, the spec file needs to have aws gateway extensions mentioned for each method. This seems to be a laborious task to write as there are too many resources and methods in my api. So is there a way to customize the schema genertion with aws gateway extensions in it using drf-yasg/drf-spectacular module? or perhaps is there any alternate method to solve this problem? -
Raise an exception using mock when a specific Django model is called
I have a class based view inheriting from FormView with an overridden form_valid() method that I would like to test. As you can see, form_valid() is required to access the CustomUser model which is wrapped with a try and except. What I am trying to do is raise an exception whenever create_user is called, but I am having no success. The CustomUser has been created in the usual way via a CustomUserManager with a create_user method. CustomUser = get_user_model() class SignUpView(FormView): template_name = 'accounts/signup.html' form_class = SignUpForm def form_valid(self, form): try: self.user = CustomUser.objects.filter(email=form.cleaned_data['email']).first() if not self.user: self.user = CustomUser.objects.create_user(email=form.cleaned_data['email'], full_name=form.cleaned_data['full_name'], password=form.cleaned_data['password'], is_verified=False ) else: if self.user.is_verified: self.send_reminder() return super().form_valid(form) self.send_code() except: messages.error(self.request, _('Something went wrong, please try to register again')) return redirect(reverse('accounts:signup')) return super().form_valid(form) What I have tried: def test_database_fail(self): with patch.object(CustomUserManager, 'create_user') as mock_method: mock_method.side_effect = Exception(ValueError) view = SignUpView.as_view() url = reverse('accounts:signup') data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'} request = self.factory.post(url, data) request.session = {} request.messages = {} response = view(request) and .. def test_database_fail(self): CustomUser = Mock() CustomUser.objects.create_user.side_effect = CustomUser.ValueError view = SignUpView.as_view() url = reverse('accounts:signup') data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'} request = self.factory.post(url, data) request.session = {} request.messages … -
How to search through encrypted field?
I want to make a search through a model. I'm making that with django-filter. But in a field, I'm using django-mirage-field to encrypt and because of that when I make research using django filter it accepts the encrypted version. I don't know if it's possible to decrypt that. What should I do for searching that too? models.py from mirage import fields class Document(Model): file_path = models.CharField(max_length=250) converted_content = fields.EncryptedTextField() filters.py class CaseSearchFilter(django_filters.FilterSet): documents = django_filters.CharFilter(field_name='documents__converted_content__icontains',lookup_expr='icontains', label='Documents') -
Problems with global variable Django
I write a quiz web site. And i need to save answers from users. Some of them have similar username. This is my start function global new_user_answer user_group = request.user.groups.values_list() university = user_group[0][1] num = Answers.objects.all().count() new_user_answer = num + 1 new_line = Answers(id=new_user_answer, id_user=user) new_line.save() return redirect(f'/1') Here I create new line in my DB. Second function save user answers. number_answer = request.POST.getlist('answer') id_questions = request.POST.get('id') a = ', '.join(number_answer) user_group = request.user.groups.values_list() university = user_group[0][1] c = f'q{int(id_questions)}' data = Answers.objects.get(id=new_user_answer) setattr(data, c, a) data.save() if int(id_questions) < 47: return redirect(f'/{int(id_questions) +1 }') else: return render(request, 'index.html') Sometime I have a error 500 name new_user_answer is no define How I can solve this problem? -
Import into tables from Django import_export
I am struggling to populate models in Django by using ForeignKey. Let's say we have as in import_export documentation the following example: class Author(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True, ) ... price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) def __str__(self): return self.name How can I implement import_export module that can check if there is an existing author by name (not by id), that is not case sensitive, and that can generate a new author if it does not exist? As an example, let's say the CSV file looks like: name,author,...,price,categories J.R.R. Tolkien,Lord of the Rings,...,40,["cat1","cat2"] Also, if there is a DateTime field, how to generate that in ForeignKey table? -
Calculate next_run at every run for a Schedule Object
I have got a question about django-q, where I could not find any answers in its documentation. Question: Is it possible to calculate the next_run at every run at the end? The reason behind it: The q cluster does not cover local times with dst (daylight saving time). As example: A schedule that should run 6am. german time. For summer time: The schedule should be executed at 4am (UTC). For winter time: The schedule should be executed at 5am (UTC). To fix that I wrote custom logic for the next run. This logic is taking place in the custom function. I tried to retrieve the schedule object in the custom function and set the next_run there. The probleme here is: If I put the next_run logic before the second section "other calculations" it does work, But if I place it after the second section "other calculations" it does not work. Other calculations are not related to the schedule object. def custom_function(**kwargs) # 1. some calculations not related to schedule object # this place does work related_schedule= Schedule.objects.get(id=kwargs["schedule_id]) related_schedule.next_run = ... related_schedule.save() # 2. some other calculations not related to schedule object # this place doesn't That is very random behaviour … -
how to bypass makemigration error on django deployment on fly io
I am trying to deploy my django app on fly.io I followed all the steps from this site: https://testdriven.io/blog/django-fly/ On running flyctl launch, I get the following error: (venv) PS C:\Users\Dell\desktop\re\real_estate> flyctl launch Creating app in C:\Users\Dell\desktop\re\real_estate Scanning source code ? Overwrite "C:\Users\Dell\desktop\re\real_estate\Dockerfile"? No ? Choose an app name (leave blank to generate one): re automatically selected personal organization: dave ? Choose a region for deployment: Chennai (Madras), India (maa) Created app re in organization personal Set secrets on re: SECRET_KEY Creating database migrations Error failed running C:\Users\Dell\desktop\re\venv\Scripts\python.exe manage.py makemigrations: exit status 1 I havent made any changes to the database. I tried running python manage.py makemigrations. It gave following error: ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS').split(' ') AttributeError: 'NoneType' object has no attribute 'split' then I tried: ALLOWED_HOSTS = [""] CSRF_TRUSTED_ORIGINS = [""] which gave following error: File "C:\Users\Dell\desktop\re\venv\lib\site-packages\dj_database_url.py", line 88, in parse if "?" in path and not url.query: TypeError: a bytes-like object is required, not 'str' -
Django authenticate: usage in login vs. register (signup): how do they differ?
I have noticed that the Django authenticate is used in the same way in both the login view and the register view, both return a User object to be used in the login(). In the login view authenticate() uses username and password from the submitted form, then checks on user if the credentials are ok. if request.method == 'POST': username = request.POST['username'] password = request.POST['password1'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) The register view looks very similar to the login view. It gets the credentials from the submitted form and uses the user to login. if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(request, username=username, password=password) login(request, user) Both call user = authenticate(request, username=username, password=password). Apart from saving the form in the register view, what is the difference here? Because the login (I guess) is only checking that the credentials are valid, but the register is creating a new user and, since it is creating, the credentials are new data coming in. Am I getting this correctly? -
probleme with django and postgres interaction
Hello, I have a problem with django and postgres. This is the context : I’m currently trying to create a login system using django for the request and the session système and postgres to store the users. From my systeme i use a form to recover the information of my user, a sql query to see if my user has the right login. But there is a problem, whatever i try there is always a problem to my query. For mor context here is one of my tries : # In the DB : vna_v2_1=# SELECT * FROM vna_users; id | prenom | nom | admin | motDePasse | ----+---------+-----+-------+--------------------------------------------------------------------------------------------------+---------------- 1 | Aksel | C | t | 7fd785e85c8fab96f2d6d683cd3439c0b1b91e21891fb9a1c68ff4a1087e13cadecb661bc0c4d77eab215b423be01da7 | 2 | Mathieu | P | f | test | -> (The first user have a ashed password and the second doesn't) Query : SELECT * FROM vna_users WHERE prenom='Mathieu' AND nom='P' AND vna_users.motDePasse='test'; -> This is one of the query i’d try The error is : LINE 1: ..._users" WHERE prenom='Mathieu' AND nom='P' AND vna_users.... HINT: Perhaps you meant to reference the column "vna_users.motDePasse". -> This is the result i always have whatever i change Other query tha i … -
How can I add a JavaScript event to my Django HTML template?
My current logout is GET, I just redirect the user to /auth/logout However, I’ve discovered that this is unsafe and I trying to add a post to this redirection. By the way, my login is using django-allauth, so I am looking to use this concept here too. But, I need to do it with JavaScript because my front end is written in Vue.js. https://django-allauth.readthedocs.io/en/latest/views.html#logout-account-logout This is my javascript file where I use too much vue: let userNavigation = [ { name: 'Account', href: '/account/'}, { name: 'Logout', href: '/auth/logout'} ] This is my HTML using vue const menu = ` <MenuItems> <MenuItem v-for="item in userNavigation" :key="item.name"> <a :href="item.href"> [[ item.name ]] </a> </MenuItem> </MenuItems> ` This is what I am trying to do to: <script type="text/javascript"> function logoutPost() { let form = document.createElement('form'); form.setAttribute('method', 'post'); form.setAttribute('action', '/auth/logout/'); let csrf = document.createElement('input'); csrf.setAttribute('type', 'hidden'); csrf.setAttribute('name', 'csrfmiddlewaretoken'); csrf.setAttribute('value', '{{ csrf_token }}'); form.appendChild(csrf); document.body.appendChild(form); let logoutAnchor = document.getElementsByName('Logout')[0].value; form.appendChild(logoutAnchor); logoutAnchor.addEventListener('click', function (e) { e.preventDefault(); form.submit(); console.log("logout clicked"); }); } </script> But, even if I try to add JavaScript DOM, nothing changes, I do not see anything in my console log and it just redirects. Where I am making a mistake? -
My API is sending data but its not getting stored in the backend
So i was following this tutorial https://youtu.be/hISSGMafzvU, with different approach of mine ( instead of being a to do app, I'm trying to make it a clinic management system ). So the problem I'm facing is that my api is receiving data, and there is no errors plus I'm getting 200 status code from the local server which means everything is okay, but its not hence the data isn't being stored in the DB for some reason. this is the code: models.py class Employee(models.Model): fullname = models.CharField(max_length = 250) age = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=(('Male', 'Male'), ('Female', 'Female')), default='Male') usertype = models.CharField(max_length = 50, choices= (('Admin','Admin'),('Doctor','Doctor'),('Receptionist','Receptionist')), default='Receptionist') def __str__(self): return self.fullname class Patient(models.Model): fullname = models.CharField(max_length = 250) def __str__(self): return self.fullname class Appointments(models.Model): Paitent_Attending = models.ForeignKey(Patient, on_delete= models.CASCADE) Doctor_Attending = models.ForeignKey(Employee, on_delete= models.CASCADE) appointment_date = models.DateField() def __str__(self): return self.Paitent_Attending.fullname serializers.py from rest_framework import serializers from .models import Employee,Patient,Appointments class PatientSerializers(serializers.ModelSerializer): class Meta: model = Patient fields = '__all__' class EmployeeSerializers(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' class AppointmentsSerializers(serializers.ModelSerializer): class Meta: model = Appointments fields = '__all__' views.py from django.shortcuts import render from rest_framework import generics from .models import * from .serializers import * from … -
Pandas read_sql_query function not working
I have configured the database connection and sql query in a pandas read sql query function, but when the function is running its throwing an error. def fetchDbTable(candidate_id): start_time = time.time() # candidate_id = 793 schema = env_config.get("DEV_DB_SCHEMA_PUBLIC") # Create Db engine engine = createEngine( user=env_config.get("DEV_DB_USER"), pwd=env_config.get("DEV_DB_PASSWORD"), host=env_config.get("DEV_DB_HOST"), db=env_config.get("DEV_DB_NAME"), ) # Create query for resume query_resume = ( """ select a.*, b.*, c.* from """ + schema + """.resume_intl_candidate_info a, """ + schema + """.resume_intl_candidate_resume b, """ + schema + """.resume_intl_candidate_work_experience c where a.c_id = b.c_id_fk_id --and a.c_id = c.c_id_fk_id and b.r_id = c.r_id_fk_id and b.active_flag = 't' and a.c_id = """ + str(candidate_id) ) # Fetch database df_resume = pd.read_sql_query(query_resume, con=engine) pandas current version- 1.5.2, numpy current version-1.23.5 in local but the version used in the server is pandas - 0.23.0, numpy = 1.16.5 I need to change the code for the latest version and run it without an error. Can you please help me fix the issue I had spent more than 2 days and i couldn't able to come to a solution. Error throwing as: Traceback (most recent call last): File "/home/vinoth/Documents/Req_Intelligence-master/Req_Intelligence-master/req_intl/resume_intl/extractedfields.py", line 483, in save_create_document meta_df = fetchDbTable(candidate_info.c_id) File "/home/vinoth/Documents/Req_Intelligence-master/Req_Intelligence-master/req_intl/resume_intl/candidate_meta_info.py", line 132, in fetchDbTable df_resume = … -
How to join 2 tables with getting all rows from left table and only matching ones in right
Table 1 Table 2 Table2.plan_selected shows what plan did the user choose. Eg: The user with user_id=4 in Table2 choose the id = 2 plan from Table1. I want to get all the rows from Table1 and only matching rows from Table2 for a particular user_id. The expected result is like this. I want to fetch all the rows of Table1 and only the selected plan from Table2 for a particular user_id lets say 4. The expected result will be like this: id name plantype plandetails requestpermonth price isdeleted planselected 1 EXECUTIVE MONTHLY {1000 MAY REQUSTS} 1000 50 0 NULL 2 BASIC MONTHLY {500 MAY REQUSTS} 1000 25 0 2 3 FREEEE MONTHLY {10 MAY REQUSTS} 1000 0 0 NULL 4 EXECUTIVE YEARLY {1000 MAY REQUSTS} 1000 500 0 NULL 5 BASIC YEARLY {500 MAY REQUSTS} 1000 250 0 NULL 6 FREEEE YEARLY {10 MAY REQUSTS} 1000 0 0 NULL What I have tried to do was use a simple left join. select plans.id, name, plan_details, plan_type, request_per_month, price,is_deleted, plan_selected from SubscriptionsPlans as plans left join SubscriptionsOrder as orders on plans.id=orders.plan_selected where orders.user_id = 4 These are my 2 models. ORM queryset or SQL query will help class SubscriptionsPlans(models.Model): id … -
Run django inside docker in airflow
Hellow I'm trying to run django inside a docker in Airflow through a Docker_Operator. The Docker_Operator remains in the Running state and does not enter the Success state. When I try to enter the IP address of the Web server, it does not show me anything. I've tried running Django in Airflow by having Django inside a Docker. Django starts up the service at address 0.0.0.0:8000 and Docker_Operator is left running without reaching the succed state. In addition to this, I cannot enter the webserver, but that may be a problem with the IP configuration since I am running it in a VM. I have configured the ALLOWED_HOSTS with the address of my VM but it does not let me enter either. Port 8000 is enabled, and I have verified it by running the container outside of Airflow and it shows me the Webserver without problems. Anyone know what might be happening? -
I created my own Memeber model in django and now I need to validate password in it with login credentials
This is My new_user model which I stores my user registration data I can save my data to database using this model its working properly. new_user model ` class new_user(models.Model): stuname = models.CharField(max_length=200) stubirthday = models.DateField() stuphoto = models.ImageField() stugemail = models.EmailField() stugrade = models.IntegerField() stuclass = models.CharField(max_length=1) sturegdate = models.DateField(auto_now_add=True) stuentrance = models.IntegerField() sturesidance = models.TextField() stuguardian = models.CharField(max_length=200) stugtele = models.IntegerField() stugemail = models.EmailField() stumother = models.CharField(max_length=200) stumothertele = models.IntegerField() stuotherskills = models.CharField(max_length=200) stucertificate = models.FileField() stuletter = models.FileField() stumedical = models.FileField() stusports = models.CharField(max_length=200) stupassword = models.CharField(max_length=200) def __str__(self): return self.stuname ` I have inherited another model named Member from this model to store my approved users. I use this model to give auto username. I inherited this class from new_users model because all my values saved in new_user are presented here. I am not sure about this decleration can someone tell me if my approach is correct Member model ` class Member(new_user): uid = models.AutoField(primary_key=True) uname = models.CharField(default=f'{super.stuname[:2]}{uid}',unique=True) password = super.stupassword office_role = models.OneToOneField(Roles.rname) mem_roles = [office_role ,'Member'] def __str__(self): return self.uname ` Since one member can have one office role and member role I created this model to store my member roles Roles model # … -
DRF Pymongo - POST Body insert_one Operation
I'm trying to use insert_one to insert a JSON document into a collection. The JSON comes from the POST body. I'm using a simple view and a serializer to validate the data and them I'm trying to insert it into the collection. However, I cannot get this thing to work at all. class Patient(APIView): def post(self, request, format=None): data = JSONParser().parse(request) print(data) # prints -> {'name': 'Jason'} serializer = PatientSerializer(data = data) if serializer.is_valid(): FHIR_Patients.insert_one(data) # throws error return Response(data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) The error that I get is: Traceback (most recent call last): File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/rest_framework/renderers.py", line 99, in render ret = json.dumps( File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/rest_framework/utils/json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/json/__init__.py", line 234, in dumps return cls( File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/rest_framework/utils/encoders.py", line 67, in default return super().default(obj) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of … -
DRF nested serializer is not serializing data
I am trying to serialize nested models for an API view. class Dashboard(models.Model): created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(IamUser, on_delete=models.CASCADE, related_name='dashboards') title = models.CharField(max_length=100) type = models.CharField(max_length=100) position = models.IntegerField() config = models.CharField(max_length=5000, blank=True, null=True) class WidgetLayout(models.Model): created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(IamUser, on_delete=models.CASCADE, related_name='widgets') dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE, related_name='widgets') type = models.ForeignKey(Widget, on_delete=models.CASCADE) position = models.IntegerField() width = models.IntegerField() config = models.CharField(max_length=5000, blank=True, null=True) with the following serializers class WidgetLayoutSerializer(serializers.ModelSerializer): class Meta: model = WidgetLayout fields = ['id', 'type', 'position', 'width', 'config'] class DashboardSerializer(serializers.ModelSerializer): class Meta: widgets = WidgetLayoutSerializer(many=True) model = Dashboard fields = ['id', 'title', 'position', 'config', 'type', 'widgets'] The view calls the serilizers like this: dashboards = request.user.dashboards.all() serializer = DashboardSerializer(dashboards, many=True) The expected output would be a list of Widgets in their JSON serialization for each Dashboard, however, I get only a list of Widget-IDs. I discovered that, if i remove the widgets = WidgetLayoutSerializer(many=True), the result is the same, so I suspect, the serializer is not being used or referenced properly. I went through https://www.django-rest-framework.org/api-guide/relations/#example and tried to spot any difference, but could not find it. Adding the prefetch_related for the widgets to the .all() in the view made … -
How to fix cryptography module import error?
I was trying to encrypt one field of a model with some libraries: django-encrypted-model-fields django-mirage-field encrypt-decrypt-fields After that, the project started to giving errors even though I uninstall all of the libraries and remove all the codes. I have no idea why. How can I solve it? Traceback (most recent call last): ... self.encryptor = Cipher(algorithms.AES(self.key),modes.CTR(self.nonce)).encryptor() File "/Library/Python/3.9/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 86, in __init__ backend = _get_backend(backend) File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/__init__.py", line 23, in _get_backend return default_backend() File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/__init__.py", line 14, in default_backend from cryptography.hazmat.backends.openssl.backend import backend File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/openssl/__init__.py", line 6, in <module> from cryptography.hazmat.backends.openssl.backend import backend File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 113, in <module> from cryptography.hazmat.bindings.openssl import binding File "/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 14, in <module> from cryptography.hazmat.bindings._openssl import ffi, lib ImportError: dlopen(/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/_openssl.abi3.so, 0x0002): tried: '/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/_openssl.abi3.so' (mach-o file, but is an incompatible architecture (have (arm64), need (x886_64))) -
Django - migrate command not using latest migrations file
I have 5 migration files created. But when I run ./manage.py migrate it always tries to apply the migrations file "3". Even though the latest one is file 5. How can I fix this issue? I have tried: ./manage.py makemigrations app_name ./manage.py migrate app_name ./manage.py migrate --run-syncdb Also, I checked the dbshell, and there is a table already created for the model which is part of migrations file 5. Any help would be great. -
VS Code - broken auto check of links for Django/Python
this is stupid question, but I used to have in Django/Python files in VS Code automatic check by yellow colour, that model, variable, view, function etc. are correctly somewhere defined and I can use them. But something broke and everything is now white. Does anybody know, where to switch on again this check for Python/Django? HTML and JavaScript files are working fine, but for Python files it was broken. Thanks a lot for any help.