Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating an Image with Foreign Key to model instance does not return Image URL in serializer.data
I have two models that are connected through a foreign key. An article can have 0, 1 or many images. Both height_field and width_field are autocalculated. is_title_image is set in the POST request. class Article(models.Model): slug = models.SlugField(null=True, default=None, unique=True, max_length=255) heading = models.CharField(max_length=2550) summary = models.CharField(max_length=25500) class Image1(models.Model): height_field=models.PositiveIntegerField(default=0) width_field=models.PositiveIntegerField(default=0) file = models.ImageField(storage=PublicMediaStorage(), height_field='height_field', width_field='width_field') is_title_image = models.BooleanField(default=False) article = models.ForeignKey(Article, related_name='images', null=True, on_delete=models.DO_NOTHING) First I create the article in the DraggableArticleSerializer and use the pk to create the images. Here I am not sure, if this is the optimal way. I use the ImageSerializer to receive all fields from the image instance. Article and image are both being created correctly in the db. But I am not able to use that data in the views.py in order to return it to the frontend. The images property is empty in serializer.data, and serializer.validated_data just returns the input InMemoryUploadedFile: serializer.validated_data['images'][0]['file'] returns OrderedDict([('file', <InMemoryUploadedFile: husky4.jpg (image/jpeg)>), ('is_title_image', True)]) I dont know how my view should be changed from the regular CreateAPIView. Do I have to give some extra data to serializer.save() or is my problem located somewhere else. class DraggableArticleSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True, required=False) class Meta: model = Article fields = … -
Paginator works slow
I work with large database (over 23,000,000 records) and find out that Django Paginator works too slow. So basically is it a problem with database (perhaps, we should do some optimizations in db) or Django Paginator is a bad solution in this case? -
Find annotated list of siblings in Django
I have a simple database with two models that define a parent-child relationship. In it, a child can have two possible gender, "Male" or "Female". class Parent(models.Model): id = models.UUIDField(primary_key=True, editable=False, unique=True, ) name = models.CharField(max_length=64) MALE = "MALE" FEMALE = "FEMALE" class Child(models.Model): id = models.UUIDField(primary_key=True, editable=False, unique=True, ) name = models.CharField(max_length=64) parent = models.ForeignKey( Parent, null=True, on_delete=models.SET_NULL) GENDER = [ (MALE, 'Male'), (FEMALE, 'Female'), ] status = models.CharField( max_length=8, choices=GENDER ) For the purposes of this question, a parent will only ever have zero or one male children, and zero or one female children. (Though this is not enforced in the database model definition.) What I would like to achieve is an annoted query, that returns all Parent objects, annoted with their male child and female child. I can't quite figure out how to produce this: I can get a list of all parents, all male and all female children, but I don't know how to put them together so that the right children are with the right parent. This is far as I get: annotated_parent_set = Parent.objects.get_queryset() brothers = Child.objects.filter(gender=MALE) sisters = Child.objects.filter(gender=FEMALE) annotated_parent_set = annotated_parent_set.annotate( brother=F(???)) ) annotated_parent_set = annotated_parent_set.annotate( sister=F(???)) ) How can I now … -
Django,update the same row field in model getting data from serializer
I have this model: class AgentDetail(MethodID): first_name = models.CharField(max_length=50, blank=True, null=True, unique=True) last_name = models.CharField(max_length=50, unique=True, null=True) email = models.EmailField(null=False) authen_method = models.ForeignKey(AuthMethodID, on_delete=models.CASCADE) country_code = models.BigIntegerField(default=1) mobile_number = models.BigIntegerField(null=False) sms_provider = models.CharField(max_length=50, null=True) active_status = models.BooleanField(default=True) created_time = models.DateTimeField(default=now, editable=False) created_by = models.CharField(max_length=50) updated_time = models.DateTimeField(auto_now=True) updated_by = models.CharField(max_length=50) and this serializer: class AgentSerializer(serializers.ModelSerializer): class Meta: model = AgentDetail fields = [ "first_name", "last_name", "email", "authen_method", "mobile_number", "sms_provider", ] and this views.py: @api_view(["POST"]) def create_agent(request): if request.method == "POST": serializer = AgentSerializer(data=request.data, many=False) if serializer.is_valid(): serializer.save() request_data = serializer.data # AgentDetail.objects.update_or_create( # created_by=request_data["first_name"] + request_data["last_name"], # updated_by=request_data["first_name"] + request_data["last_name"], # ) return Response(status=status.HTTP_200_OK) error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return error As in serializer I'm not passing created_by field and I need that field gets value of first_name+last_name which are coming from serializer data.I'm new to DRF. -
React Native (expo) + Django JWT axios error
Trying to make Login Screen. Using axios to get data from Django JWT url('http://127.0.0.1:8000'). Tried to find url works from Postman and also from terminal and both worked, but I got AxiosError from simulator. Does anyone know why my base url not work on React Native App? I tried 'http://localhost:3000/' and 'http://10.0.2.2:8000'too but not worked. This is my Codes... LoginScreen.js const LogInScreen = () => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const handleSubmit = (e) => { e.preventDefault(); const config = { headers: { "Content-Type": "application/json", }, }; const body = JSON.stringify({ email, password }); axios .post("http://127.0.0.1:8000/api/token/", body, config, console.log(body)) .then((res) => { console.log("token"); AsyncStorage.setItem("access_token", res.data.access); AsyncStorage.setItem("refresh_token", res.data.refresh); axiosInstance.defaults.headers["Authorization"] = "JWT " + AsyncStorage.getItem("access_token"); navigate("Home"); console.log(res); console.log(res.data); }) .catch((error) => console.log("error", error)); }; console.log(body) showed up {"email":"test@mail.com","password":"Test1234"} console.log('token') not showed up, and 'error' part pop up. Django urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/user/', include('api_user.urls')), path('api/flashcard/', include('api_card.urls')), ] settings.py ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', # … -
How can one display contents of a database to a template from a non Django project
I am working on a Django project to display data from an existing database. The database was created by PHP language. How should I get the models into the views to pass the context into the template? Kindly note, that the database already exists hence I haven't created any models in the models.py file. Therefore no migrations have been made. -
django render project information from linked site
project site in my Django-project with a link which links to conversation. Is it possible to render out project-information like project.category from single-project.html in the url conversation. single-project.html <div> <span> <small>{{project.category}}</small> </span> </div> <div> <a href="{% url 'conversation' project.owner.user %}">Send message</a> </div> -
How to convert different rss feed dates with Python so they can be ordered
Trying to make an RSS feed reader using django, feedparser and dateutil Getting this error: can't compare offset-naive and offset-aware datetimes I just have five feeds right now. These are the datetimes from the feeds.. Sat, 10 Sep 2022 23:08:59 -0400 Sun, 11 Sep 2022 04:08:30 +0000 Sun, 11 Sep 2022 13:12:18 +0000 2022-09-10T01:01:16+00:00 Sat, 17 Sep 2022 11:27:15 EDT I was able to order the first four feeds and then I got the error when I added the last one. ## create a list of lists - each inner list holds entries from a feed parsed_feeds = [feedparser.parse(url)['entries'] for url in feed_urls] ## put all entries in one list parsed_feeds2 = [item for feed in parsed_feeds for item in feed] ## sort entries by date parsed_feeds2.sort(key=lambda x: dateutil.parser.parse(x['published']), reverse=True) How can I make all the datetimes from the feeds the same so they can be ordered? -
from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'
S C:\Users\pande\anaconda3\WebApp> python.exe .\manage.py runserver Traceback (most recent call last): File ".\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception:Traceback (most recent call last):File ".\manage.py", line 22, in main() File ".\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? my manage.py is: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebApp.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() -
Is it possible to implement Django-allauth using Apache Cassandra as default database
Explanation: I know Apache Cassandra is a NoSQL database and I have been figuring a way out to use this. However when I run sync-db command, it doesn't create tables in the database. Django-allauth works fine in a RDBMS but not working in Cassandra. Before anyone downvote this question, I want to tell that I have done proper research but I couldn't find a single post on the internet regarding this. So if anyone can help, it would be highly appreciated. Also here is a link for this issue opened on GitHub by someone. -
Django UnboundLocalError: local variable 'tags' referenced before assignment
Why do I face this problem? I am trying to get the tags from the Post table.Post and tags are two tables with Many to Many relation. in models.py class Tag(models.Model): caption = models.CharField(max_length=40) class Post(models.Model): tags = models.ManyToManyField(Tag) in views def post_details(request,slug): post = Post.objects.get(slug=slug) tags = Post.objects.filter(tags) comment = post.comments.all() return render (request,'mblog/post_detail.html',{'post': post ,'tags': tags,'comment': comment}) -
AttributeError: 'User' object has no attribute 'user' while trying to verify user's email
I have django web app with authentication and email verification. I have two options of authentication. One is authenticating with Customer or with Employee. I have User(AbstractUser) to connect them both. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_customer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) signup_confirmation = models.BooleanField(default=False) class Customer(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) phone_number = models.CharField(max_length=20) location = models.CharField(max_length=20) class Employee(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) phone_number = models.CharField(max_length=20) designation = models.CharField(max_length=20) views ...employee_register... class customer_register(CreateView): model = User form_class = CustomerSignUpForm template_name = '../templates/customer_register.html' def form_valid(self, form): user = form.save() # current_site = get_current_site(request) current_site = '127.0.0.1:8000' subject = 'Please Activate Your Account' message = render_to_string('activation_request.html', { 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) send_mail( subject, message, 'from@example.com', ['to@example.com'], fail_silently=False, ) # login(self.request, user) return redirect('/') def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.user.signup_confirmation = True user.save() login(request, user) return redirect('index') else: return render(request, 'activation_invalid.html') In my views first I have class which is triggered … -
how to allow throttle only if the response was successful
I'm trying to make throttling on OTP authentication so user can only send one message every minute class BurstRateThrottle(AnonRateThrottle, UserRateThrottle): scope = 'burst' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',), 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'burst': '1/min', 'anon': '200/min', 'user': '250/min', }, @api_view(['POST']) @permission_classes([AllowAny]) @throttle_classes([BurstRateThrottle]) def login_send_token(request): ... The problem with this is that the api gets throttled even when the phone number is wrong so I'm trying to only throttle when the OTP message is send or when the response is 200 or 201 is there anyway to access the response status code in allow_request method? or to manually execute the throttle from the function that call twilio api? -
In django,Use one field from one model in other model
I'm trying to use auth_method field from MethoID model in AgentDetails Model.But when I enter the value of primary key id in serializer for authen_method it is not being validated. Models: class MethodID(models.Model): auth_method = models.CharField(max_length=50, default="Google") def __str__(self): return self.auth_method class AgentDetail(MethodID): authen_method = models.ForeignKey(AuthMethodID, on_delete=models.CASCADE) Serializer: class AgentSerializer(serializers.ModelSerializer): class Meta: model = AgentDetail fields = [ "authen_method", ] and in views I use POST request. Views: @api_view(["POST"]) def create_agent(request): if request.method == "POST": serializer = AgentSerializer(data=request.data, many=False) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return error -
I want to make my site can be accessed only through redirect from paypal django
I want to make my site can be accessed only through redirect from paypal in django and cannot be accessed through url i tried if request.META.get('HTTP_REFERER') == 'paypal' but not work because it returns none value i'm using ajax is there any working alternative that i can use please help me. -
Django: Select count of foreign key field
I have the following models: class System(models.Model): # ... class Page(models.Model): # ... system = models.ForeignKey(System) I want to perform the following SQL query: select s.*, (select count(*) from page p where p.system_id = s.id) as NUM_OF_PAGES from system s; How do I perform the above query with Django's ORM without having to use a for loop? I do not want a result based on one system, I want to retrieve all systems with their page counts. -
I want to have a user select multiple events from another table in django. How do i achieve it?
I am making a Django project. I want that my users table field should automatically update when they register for an event. I Have used ForeignKey in my Events model to achieve this. But the problem here is, I can select only 1 user in the events model when creating a new event or editing it(since the relationship is manyToOne). What I want is my events model should show every user that has registered for that event (Something like this). Am I using the right relationship? If Not, what should be the correct relationship that I should use? I am attaching my models for Users and Events. Kindly Look it through. accounts/models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255, null=True, blank=True) mobile = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) short_description = models.CharField(max_length=180, null=True, blank=True) instagram_url = models.URLField(null=True, blank=True) linkedin_url = models.URLField(null=True, blank=True) # is_member = models.BooleanField(default=False) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] class Meta: verbose_name = 'User' verbose_name_plural = 'Users' models.py class Event(models.Model): banner_image = models.ImageField(upload_to="Events/", max_length=400) event_name = models.CharField(max_length=150, null=False) organiser_of_event = models.CharField(max_length=200) format_of_event = models.CharField(max_length=300, null=True, blank=True) … -
Arrays in django rest framework
Can anyone help me represent this in django rest framework? I need to recreate this json data in the DRF, but I don't know how to create an array inside the views, taking the data from another model. { "name": "Fabiano Felipe", "email": "fabiano.webdev@gmail.com", "phone": "55(81)98121-3241", "products": [ { "product_type": "Hotel", "product_description": "Recife Palace", "start_date": "12/10/2025", "end_date": "15/10/2025", "from_location": "", "to_location": "New York" }, { "product_type": "Transfer", "product_description": "Passeio X", "start_date": "12/10/2025", "start_time": "12:00", "end_time": "15:00", "end_date": "12/10/2025", "from_location": "Miami", "to_location": "New York" } ] } The first four fields will be created within the model, however, the array, I need to bring from another model so that the user can fill it. -
Django: How to sort by presence of M2M (Pizza Example)
Say I have the common pizza example: class Topping(models.Model): order = models.IntegerField() name = models.CharField(max_length=250) class Pizza(models.Model): toppings = models.ManyToManyField(Topping) With the following toppings: Topping.objects.create(order=1, name="tomato") Topping.objects.create(order=2, name="cheese") Topping.objects.create(order=3, name="olives") Topping.objects.create(order=4, name="salami") Topping.objects.create(order=5, name="onion") Topping.objects.create(order=6, name="rocket") Now say I had a pizza with tomato, cheese and salami I wish to get an order list of all the toppings of the pizza according to the topping__order, along with a list of all the toppings it does not have, also ordered by topping__order So its sort by first where the pizza has the topping, and secondly by the topping__order field. The result would be something that has the same info as this (probably in a queryset though): { { "id": 1, "name": "tomato", "has_topping": True}, { "id": 2, "name": "cheese", "has_topping": True}, { "id": 3, "name": "salami", "has_topping": True}, { "id": 2, "name": "olives", "has_topping": False}, { "id": 5, "name": "onion" , "has_topping": False}, { "id": 6, "name": "rocket", "has_topping": False}, } Is this possible via a database query? (I can do it manually in python via two querries) -
Do I need to write triggers and functions directly to DB server while using a programming framework like django?
I am new to DB based programming and was trying to build trigger functions to update one table on INSERT/UPDATE on another table. I plan to use django for backend and PostgreSQL or SQLite for DB. Would like to know whether I should write all DB functions within django or should write some SQL functions directly in the DB server. I know django can handle SQL queries etc. But considering separate DB servers in big projects, I wonder how this is done. -
Django, CSP: How to activate Nonce in scripts for Admin pages
At my page scripts are only executed, when the nonce tag is included (because of CSP settings). That causes at the admin pages, that scripts are not working. Therefore I am overwriting now all the admin templates, for example from: <script src="{% static 'admin/js/nav_sidebar.js' %}" defer></script> to <script src="{% static 'admin/js/nav_sidebar.js' %}" nonce="{{request.csp_nonce}}" defer></script> Is there an easier way to do this? Deactivate CSP on the admin pages or somehow tell Django to add Nonce to all scripts? Thanks -
ImageField Test In View
I'm trying to post an Image on 'accounts/profile_edit' url in one of my tests. I have a Profile model which resizes images bigger than (225, 255) and this is the functionality I want to test. I read how to unit test file upload in django but I can't get client.post to work with image. What is the problem? class TestProfileEditView(TestCase): # other tests... def test_profile_picture_resize(self): self.client.force_login(user=self.user) image = Image.new('RGB', (500, 500), (255, 255, 255)) image_location = f'{settings.MEDIA_ROOT}/TestProfilePictureResize.png' image.save(image_location) with open(image_location ,'rb') as f: response = self.client.post(reverse('profile-edit-view'), {'picture': f}) profile = Profile.objects.get(user=self.user.id) picture_path = profile.picture # falsely returns default picture location self.assertEqual(picture_path, /media/profile_pictures/TestProfilePictureResize.png) self.assertTemplateUsed(response, 'user/profile.html') # returns False views.py : @login_required def profile_edit(request): if request.method == 'POST': user_form = UserEditForm(request.POST, instance=request.user) profile_form = ProfileEditForm( request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, f'Profile Edited Successfully.') return redirect(reverse('profile-view'), request.user) else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) context = { 'user_form': user_form, 'profile_form': profile_form } return render(request, 'user/profile_edit.html', context) models.py : class User(AbstractUser): email = models.EmailField(unique=True, blank=False, null=False) first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=False, null=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return f"{self.first_name} {self.last_name}" class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField( default=f"default_profile_picture.png", upload_to="profile_pictures" … -
User has no attribute session
After looking online I cannot come up with the solution. I am building my own authentication app: I can register the user, send activation account email, activate the account, login, and correctly change password. However, when it comes to logging out, I get the error 'User' object has no attribute 'session'. I try to print the user and it shows correctly the email and username associated to it. Checking inside the cookies there seem to be a valid csrf token and a valid session id. I would love if you can double check my login, logout and settings to see if I am messing something up. settings.py REST_FRAMEWORK = { 78 'DEFAULT_AUTHENTICATION_CLASSES': ( 79 'rest_framework.authentication.SessionAuthentication', 80 'rest_framework.authentication.BasicAuthentication', 81 ), 82 'DEFAULT_PERMISSION_CLASSES': ( 83 'rest_framework.permissions.IsAuthenticated', 84 'rest_framework.permissions.IsAdminUser', 85 ), 86 } loginView class LoginView(APIView): 23 authentication_classes = [SessionAuthentication, BasicAuthentication] : list[Unknown] 24 permission_classes = [AllowAny] : list[Type[AllowAny]] 25 26 def post(self, request): -> Response 27 serializer = LoginSerializer(data=request.data) : LoginSerializer 28 if serializer.is_valid(): 29 try: 30 user = authenticate(request, : Unknown | None 31 email_or_username=request.data["email_or_username"], 32 password=request.data["password"]) 33 34 except ValueError as e: 35 return Response({"errors": f"{e}"}, status=status.HTTP_400_BAD_REQUEST) 36 37 login(request, user) 38 return Response({"success":"user successfully logged in"}, 39 status=status.HTTP_200_OK) 40 … -
Django not setting cookies after deployment
I have created a vue and DRF application, which is working fine locally, it sets access, refresh and csrf token in cookies on login and so all of the isAuthenticated routes work fine. But i handed it over to the person who's meant to deploy this on vps and now it doesn't set cookie on login. I'm able to login, but since no cookie is set, refreshing it logs me out and all routes give 401 error. These are my django settings, removing secret_key here: import os from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_api_key', 'rest_framework_simplejwt.token_blacklist', 'corsheaders', 'django_filters', 'api' ] AUTH_USER_MODEL = 'api.User' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.AllowAllUsersModelBackend', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", "fxbNh4", ] # CORS_ALLOWED_ORIGINS = [ # "http://localhost:8080" # … -
int() argument must be a string, a bytes-like object or a number, not 'list
def request_id_generator(script_id): script_id = str(script_id) mnf_reference = MNFScriptDatabase_2.objects.get(script_id=script_id) service_no = int(mnf_reference.script_used_by_services) + 1 mnf_reference.script_used_by_services = int(service_no) mnf_reference.save() request_id = str(script_id) + "_" + str(service_no) return request_id