Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show customer orders in one model Django
I am creating an eCommerce website for my client. I am completely new to Django. I am following a tutorial: creating an eCommerce Django website. In tutorial instructor creates 3 models: Customer, Order, Order_Items. I did not like the model setup in that tutorial. When a customer places an order, in database order created and seperate order_items being created and they are being assigned to order. I want something different like in Wordpress Woocommerce, when a customer places an order, in the admin dashboard you can see Customer order, and when you view that order it shows products and their price, quantity, and total price in one place. I want to make an Order model that contains and shows: customer name, products, quantity, and total product price. As far as I know, Order and Order_item is a common solution for creating order but for the website admin(for my client), it would be very hard to understand and keep track of customer orders. I couldn't find any solution on the Internet. It would be great if you could give me an idea of how to solve this problem. Thanks in advance! -
Django share users in different databases causes 500 and 403 errors
The goal I want Doccano to use the users that are saved in my other app (app2) as its own users, instead of Doccano keeping its own users. These are both Django databases, so i assume these are not doccano specific issues The problem The connection between the users work, i can login in doccano with app2 users. when in the /projects page an 500 internal server error arises on the website and on the terminal app2 prints: "ERROR: relation "api_project" does not exist at character 363" When creating a new project a 403 Forbidden arises when doing a POST to /v1/projects What i did I am currently running the Doccano Backend, nginx and postgres in their containers and running app2 and the postgres_app2 in containers as well. Doccano backend shares a (docker-compose)network with Doccano postgres and another network with postgres_app2. doccano/app/app/settings.py has both databases and a link to the router: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': path.join(BASE_DIR, 'db.sqlite3'), }, "app2_db": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": os.getenv("POSTGRES_USER", "user_app2"), "PASSWORD": os.getenv("POSTGRES_PASSWORD", "pass_app2"), "HOST": "postgres", "PORT": 5432, } } DATABASE_ROUTERS = ['app.authRouter.AuthRouter'] with the AuthRouter.py looking like this: # AuthRouter.py class AuthRouter(object): def db_for_read(self, model, **hints): if … -
Django with SQLite - Database is locked - does it throw error? When does it occur?
I'm using Django + sqlite for my hobbist project (Gallery script). The whole script isn't very write-heavy. The only writes to database is incrementing views for each browsed photo. Today I was browsing logs and noticed few "Database is locked" errors. I know this is sqlite's issue, but I'm not sure how Django handles it. I'm unable to reproduce the error on my own, therefore I have two questions. If the "Database is locked" error occurs during the user visit (number of views update is called from PhotoDetailView) does it end up in 500 error or the user stills sees the photo? Does it fail silently (counter not updated, print to logs)? How does the single no parallel writes rule work for SQLite? Is it single write at given time for whole database or table? Item? Any ideas how can I manually lock the database to reproduce the "database is locked" error? -
how can i export excel file to views.py django project
i am trying to export a column in excel file in my database to a list then render it to my template. m code is: def home(request): ch = chart.objects.get() a= ch.chart_file.path labels = a['x'].tolist() b = [float(n) for s in labels for n in s.strip().split(' ')] context = { 's': b } return render(request, 'home.html', context) and in template: {% block content%} {% for i in s %} <p>{{ i }}</p> {% endfor % {%endblock%} but it raise this error: string indices must be integers how can i fix it? -
Cannot solve Error while running '$ python manage.py collectstatic --noinput'
I dont know what is going wrong but i cannot deploy my app in heroku. Everytime its throwing me this error but my code seems fine. I have also created staticfiles folder in my root-directory with an empty css file. Please can anybody help. I dont know if this issue is caused by static files or not. My error during deployment: -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.8.6 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.8.5 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting certifi==2020.6.20 Downloading certifi-2020.6.20-py2.py3-none-any.whl (156 kB) Collecting chardet==3.0.4 Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) Collecting Cython==0.29.21 Downloading Cython-0.29.21-cp38-cp38-manylinux1_x86_64.whl (1.9 MB) Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.1.1 Downloading Django-3.1.1-py3-none-any.whl (7.8 MB) Collecting django-crispy-forms==1.9.2 Downloading django_crispy_forms-1.9.2-py3-none-any.whl (108 kB) Collecting django-embed-video==1.3.3 Downloading django_embed_video-1.3.3-py3-none-any.whl (24 kB) Collecting django-js-asset==1.2.2 Downloading django_js_asset-1.2.2-py2.py3-none-any.whl (5.8 kB) Collecting django-mptt==0.11.0 Downloading django_mptt-0.11.0-py2.py3-none-any.whl (109 kB) Collecting gunicorn==20.0.4 Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) Collecting idna==2.10 Downloading idna-2.10-py2.py3-none-any.whl (58 kB) Collecting numpy==1.19.4 Downloading numpy-1.19.4-cp38-cp38-manylinux2010_x86_64.whl (14.5 MB) Collecting Pillow==7.2.0 Downloading Pillow-7.2.0-cp38-cp38-manylinux1_x86_64.whl (2.2 MB) Collecting python-decouple==3.3 Downloading python-decouple-3.3.tar.gz (10 kB) Collecting pytz==2020.1 Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting requests==2.24.0 Downloading requests-2.24.0-py2.py3-none-any.whl … -
Django Admin Site -- view path "admin/" at "/"
I'm developing a Django (3.1) app that only uses the Admin Site. The default behavior is then to serve the Admin Site with the path: http://localhost:8080/admin/ Which assumes that you have other sites at http://localhost:8080/other_site Because my only site is the Admin Site, I'd like to serve the admin site at: http://localhost:8080/ without the admin/. Here is the file website/urls.py (website folder has all the settings/config) from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('management/', include('management.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And here is the file management/urls.py (management is the app with all the models) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] How can I do this? -
Can I use single database for different Django website? [closed]
Q. Can I use single database for different Django website? . If the yes then how can I use data from the database in my views.py? . I was working on a website which will have different versions one for desktop users. Url will be like example.com and other for mobile user m.example.com. How can i use similar database for these two website. I am using Django=2.2 and sqlite -
Flask: get the context on the filter
I'm a beginner at the flask, I want to practice filter, I've read the official documentation, but it doesn't help. I want to create a firstof filter, i.e., Outputs the first argument variable that is not “false” .(same as Django's firstof). <h1>Hi, {{ "username, 'guest'"| firstof }} </h1> @app.route('/') def index(): return render_template('index.html') # expect output: Hi, guest # return render_template('index.html', username='Carson') # Hi, Carson I try, @app.template_filter('firstof') def firstof_filter(s: str): """ USAGE:: {{ "var1, var2, 'default_val'" | firstof }} """ for data in s.split(','): data = data.strip() if data[0] == data[-1] and data[0] in ("'", '"'): return data[1:-1] # a constant """ # does any similar grammar like below? if hasattr(app.current.context, data): return app.current.context[data] """ It would be nice if you could provide more links about flask-filter. thanks! -
Django form include Many2Many field from related_name
I have two models with two update forms. Now I want to achieve two things: be able to edit a certificate and set all the servers this certificate is used on be able to update a server and set all the certificates which are used on this server. class Certificate(models.Model): internal_name = models.CharField(max_length=1024) pem_representation = models.TextField(unique=True) servers = models.ManyToManyField( Server, related_name='certificates', blank=True) class Server(models.Model): name = models.CharField(max_length=1024, unique=True) class CertificateUpdateForm(forms.ModelForm): class Meta: model = models.Certificate fields = ['internal_name', 'pem_representation', 'servers'] class ServerUpdateForm(forms.ModelForm): class Meta: model = models.Server fields = ['name', 'certificates'] Without the field "certificates" in ServerUpdateForm I get no error but when updating via the form the changes for the certificates just aren't recognized. The error message I get with this code is: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib64/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File " venv/lib64/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File " venv/lib64/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File " venv/lib64/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File " venv/lib64/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 23, … -
pytest no django "lazy_django.py no Django settings"
my project list: main_project - projects/ - tests/ - project1/ - django_project/ - tests/ - django_app/ - django_project/ - manage.py now, when I on main_project path, run pytest ./projects/django_project, it can pass django_project pytest. But I want run one pytest to run wholl pytest including project1 & django_project on main_project path, it passed all project1 pytests, but auto skipped django_project's pytest, when I run with pytest -rsx it shows: SKIPPED [2] .../local/lib/python3.6/site-packages/pytest-django/lazy_django.py:14: no Django settings Any suggestion? thanks! -
Template inheritance with dynamic content
Is it possible to make one sub-template inherit a div with dynamic content from an upper level template? For eg., there are 3 templates as following: base.html <!DOCTYPE html> <html> <head> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> level_1_template.html {% extends "base.html" %} {% block content %} <div id="dynamic-level1"> ...some elements here that depend on variable {{ level_1_var }}} </div> {% block level2_content %} {% endblock %} {% endblock %} level_2_template.html {% extends "level_1_template.html" %} {% block level2_content %} ...doing level 2 stuff here ... {% endblock %} In this generic example, level_1_var variable is passed into the corresponding view for that template and not the view for level_2_template.html When rendering level_2_template.html, div dynamic-level1 is not rendered. Is there a way to make this inheritance possible? Of course, one way is to repeat the whole thing in level_2_template.html and to pass the variable level_1_var to the corresponding view. But this does not seem like a decent (or DRY) way to do. Thanks. -
Insert into many to many field Django
I'm trying to build Reddit in Django and for that, I am creating a board where users can discuss topics. But I am not able to map user and board. Model: class Board(models.Model): id = models.AutoField(primary_key=True) unique_id = models.CharField(max_length=100, null=False, unique=True) created_by = models.ForeignKey(User_Detail, on_delete=models.CASCADE, related_name="board_creator") name = models.CharField(max_length=100, null=False, unique= True) class UserBoardMapping(models.Model): user = models.ManyToManyField(User_Detail) board = models.ManyToManyField(Board) user_type = models.CharField(max_length=10, choices=USER_TYPE, default='moderator') My view: class CreateBoard(APIView): def post(self, request): data = JSONParser().parse(request) unique_id = data.get('board_id', None) created_by = data.get('created_by', None) name = data.get('name', None) if not created_by or not name: return Response({'ERROR': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST) if Board.objects.filter(name=name).exists(): return JsonResponse({'ERROR': "Board Already registered! "}, status=status.HTTP_409_CONFLICT) if not User_Detail.objects.filter(username=created_by).exists(): return JsonResponse({'ERROR': "Username is not registered! "}, status=status.HTTP_404_NOT_FOUND) username = User_Detail.objects.get(username=created_by) board = Board(unique_id=unique_id, created_by=username, name=name) board.save() user_board_mapping = UserBoardMapping(user=username, board=board) user_board_mapping.save() UserBoardMapping is not working, how can I map user and board and Insert data in many to many field what am I doing wrong here in this code? -
Error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I want to fetch some data from API, but I get the error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I've checked the code a hundred times but obviously there is something I'm missing. Can anybody see what I'm missing? also if that can help too it returns me Promise {<pending>} with [[PromiseState]]: "rejected" My function for the api from django views: def fetchapi(request): url = 'https://prime.webflow.com:30190/data_link' params={"user":"test", "api_key":"notarealapikey", "act":"get_system_users", "user_id":"all"} response = requests.get(url, params) #Read the JSON users = response.json() #print(users) #Create a Django model object for each object in the JSON and store the data in django model (in database)""" for user in users: Employee.objects.create(status=user['status'], email=user['user_email'], name=user['user_name'], webflow_id=user['user_id'], user_type=user['user_type']) context = { "users": Employee.objects.all(), } return render(request, 'fetchapi.html', context) fetchapi.html {% extends 'main.html' %} {% block content %} <h1>FetchAPI</h1> <script> function fetchData(){ fetch("http://192.168.2.80:8000/fetchapi/").then(response => { const data = response.json(); console.log(data) }); } fetchData(); </script> {% endblock %} what my json looks like I tried to print it in the terminal from views: { 'status': 'active', 'user_email': '', 'user_id': 701, 'user_name': 'formapi', 'user_type': 'backoffice' }, -
Cannot login to django admin right after implementing DRF token authentication. Setting is_active to True fixed it. Why?
After implementing DRF authtoken app, I deleted my previous superuser (because it did not have an auth token) and created a new one. Looking at the database, I see that the new superuser has an entry in authtoken_token table. It also has is_admin, is_staff, and is_superuser set to True. is_active is set to False but this was also set to False in the previous superuser and loging in to admin was not a problem. When I enter credentials in admin page with is_active=False, it says: "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." Before setting is_active=True, some answers from other SO questions I tried: I made sure I'm not setting SESSION_COOKIE_SECURE = True. I'm not using this setting in dev environment anyways. When I check the database, django_session table is there. When I try to authenticate, I do not see a new entry being created. I do create my superuser via python manage.py createsuperuser command, same as I did before. I also tried to change superuser pw via python manage.py changepassword . My db is synced, I checked the tables after deleting and creating a new superuser and they are … -
Django Rest Framework allauth Saving a PrimaryKeyRelatedField to a user during sign up
I have set up a CustomRegisterSerializer using dj-rest-auth and allauth. I can't seem to save the ManytoMany relationships. please can someone advise where I'm going wrong. serializer.py class CustomRegisterSerializer(RegisterSerializer): dbs_number = serializers.CharField(max_length=13, required=True) hospitals = serializers.PrimaryKeyRelatedField(many=True, queryset=HospitalListModel.objects.all()) area_to_work = serializers.PrimaryKeyRelatedField(many=True, queryset=AreaToWorkModel.objects.all()) def get_cleaned_date(self): data_dict = super().get_cleaned_data() data_dict['dbs_number'] = self.validated_data.get('dbs_number', '') data_dict['hospitals'] = self.validated_data.get('hospitals', '') data_dict['area_to_work'] = self.validated_data.get('area_to_work', '') print('serializer :' + str(data_dict)) return data_dict adapter.py class CustomAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): user = super().save_user(request, user, form, commit) data = form.data user.dbs_number = data['dbs_number'] user.save() user.hospitals.add(*data['hospitals']) user.area_to_work.set(*data['area_to_work']) user.save() return user -
django runserver start downlonding file containing this string <function render at 0x0000023B61F4F160>
After running: py manage.py runserver instead of showing me the html views, this string is shown on the page: <function render at 0x0000023B61F4F160> after few minutes this message appears on the terminal: [13/Nov/2020 08:39:05] "GET /socketcluster/ HTTP/1.1" 404 2129 -
Django Form Initial Value not Showing
I want to make a form to edit a model object, with the initial data being the original data (before the change), but it doesn't show, it was just a blank form models.py: class Employee(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) forms.py: class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['first_name', 'last_name'] labels = {'first_name' : 'First Name:', 'last_name' : 'Last Name:' } input_attrs = {'class' : 'form-control'} widgets = { 'first_name' : forms.TextInput(attrs=input_attrs), 'last_name' : forms.TextInput(attrs=input_attrs)} views.py: def edit(request, id): employee = Employee.objects.get(id=id) data = { 'first_name' : employee.first_name, 'last_name' : employee.last_name, } form = EmployeeForm(request.POST or None, initial=data, instance=employee) if (form.is_valid and request.method == 'POST'): form.save() return HttpResponseRedirect('/form/') response = {'employee_form' : EmployeeForm, 'employee':employee} return render(request, editemployee.html, response) editemployee.html: <div class="form"> <div class="form-group"> <form action="" method="POST"> {% csrf_token %} {% for form in employee_form %} {{ form.label }} {{ form }} <br> {% endfor %} <input type="submit" value="Submit" class="btn btn-primary"> </form> </div> </div> Can anyone please tell me where I went wrong? I've tried so many things but to no avail. The form works fine, but the initial data doesn't show. -
DFR simple jwt get authToken from a user instance instead of username/password
I have a simple chat app, authentication in it works exaclty as whatsapp Get phone number => if doesn't exist create one else skip => send validation code and set it as "phone_code" field in User model => finally remove the "phone_code" if validated The app is built in React Native with Rest framework as the API, I'm new to this and I'm struggling to get the authentication token without the password. i use djangorestframework-simplejwt my register view: @api_view(('POST',)) def register(request): if request.method == 'POST': serializer = UserSerializer(data=request.data) if not serializer.is_valid(): if 'is not valid' in serializer.errors['phone_number'][0]: return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) phone_number = serializer.initial_data['phone_number'].replace(' ', '') try: user = User.objects.get(phone_number=phone_number) except User.DoesNotExist: user = User.objects.create_user( phone_number=phone_number, username=phone_number) user.phone_code = randint(99999, 999999) user.save() TokenObtainPairView() return Response(serializer.data, status.HTTP_200_OK) # todo send validation code, I will handle later my Login view (Chich validates for the validation code) @api_view(['POST',]) def loginuser(request): if request.method == 'POST': phone_number = request.data.get('phone_number') try: user = User.objects.get(phone_number=phone_number) if int(request.data.get('phone_code')) == user.phone_code and user.phone_code: user.phone_code = None user.save() #!!!!!!!!!!!!!!!!!!!NOW HOW CAN I GET THE JWT AUTHENTICATION TOKEN AND SEND IT TO MY REACT NATIVE APP?! return JsonResponse({'phone_number': phone_number}, status=200) else: return JsonResponse({'error': "Invalid code"}, status=400) except Exception as error: return JsonResponse({'error': … -
how can i change the file in the django database
I have a model like this: class chart(models.Model): name = models.CharField(max_length=10) chart_file = models.FileField(upload_to='charts/1', null=True, blank=True) in chart_file object i have to many excel file. now in views.py i want to get the objects and extract one of the column like this def home(request): charts= chart.chart_file.url read = pd.read_excel(chrts) labels = read['x'].tolist() context = { 's': labels, } return render(request, 'home.html', context) finally for each excel file in my model i want to show the x column like this: {% block content%} {% for i in s %} <p>i</p> {% endfor %} {% endblock %} but it raise this error: 'FileDescriptor' object has no attribute 'url'. how can i render this.please help -
Force client request to include specific data in Django using Gunicorn
Big tech like Google, for instance, can collect the user(client)'s device name when they send a request to any of their services, and that allows them to track all the devices that a user has used to access a particular service, endpoint, application. While building applications with Django; request data or headers can be accessed through the META attribute of the request object. When developing locally, using Django's development server, requests are constructed with a bunch of useful data that could be used to keep track of the device sending requests. Data that interests me here are: request.META.get('LOGONSERVER') request.META.get('USERDOMAIN') Unless I am wrong, these are easily set by the development server and can be collected. In production, these values are nowhere to be found inside request.META. Is there a way to achieve this in production? Is there a condition of trust between server and client supposed to be made before it is possible? -
django-admin startproject command returning bad interpreter: No such file or directory
I can create a project outside of a virtual environment just fine, but when I am using a venv and try to create a django project, I get the following: /Users/justin/Desktop/Programming/Python/Django Projects/env/bin/django-admin: "/Users/justin/ Desktop/Programming/Python/Django: bad interpreter: No such file or directory I created the venv with python3 -m venv env, I then tried to run pip install django where the above error also appeared, I then learned I should be using python3 -m pip install django (pip3: bad interpreter: No such file or directory) and this successfully installed django, but I still cannot start a project. I've ran pip install django and django-admin startproject from a venv many times without an issue so it seems like I broke something recently. Does anyone know how to fix this/where I can begin looking for the issue? Thanks for any help. -
How to add created_by and updated_by fields in any Django model and fill the values automatically using Django middlewares?
This is the Profession model in my Django Project, I have added two fields named created_by and updated_by in this model. Whenever a new object is added to this model or an object is modified of this mode, created_by and updated_by should have relevant 'User' values. class Profession(models.Model): profession_name = models.CharField(max_length=50) is_active = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='profession_cb', on_delete=models.PROTECT) updated_by = models.ForeignKey(User, related_name='profession_ub', on_delete=models.PROTECT) def __str__(self): return self.profession_name That's a typical problem and answered by many on Stack Overflow, but I wanted to do it through django middlewares, I found a solution using middlewares but it was for Django older than 2.2. I am using Django 3.1 and 'curry' method is no more on this 3.1 version. I have also tried 'functools.partial' in place of 'curry' but that is also not working. This is my middleware. from django.db.models import signals from functools import partial class WhodidMiddleware: 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. self.process_request(request) response = self.get_response(request) # Code to be executed for each request/response after # the view is … -
Django serializer is not using the model manager
I am trying to work with my own model manager to annotate some properties. This is working fine till the serializers try to use one of this properties. The setup is a little bit complicated but i will try to explain it as best as i can. This is my model (reduced to the important part) class UserManager(DjangoUserManager): def get_queryset(self): return super(DjangoUserManager, self).get_queryset().annotate( is_counselor=Exists(Group.objects.filter(user=OuterRef('pk'), name=User.COUNSELOR_GROUP)) ) class User(AbstractUser): COUNSELOR_GROUP = 'Berater*in' objects = UserManager() Then i have another model which has a foreign key to the user model (simplified): class Message(models.Model): sender = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='sender_message') And in the end i have this serializer: class ConversationMessageSerializer(serializers.ModelSerializer): is_counselor = serializers.BooleanField(source='sender.is_counselor') The error im receiving is this one: AttributeError: Got AttributeError when attempting to get a value for field `is_counselor` on serializer `ConversationMessageSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Message` instance. Original exception text was: 'User' object has no attribute 'is_counselor' I tried to use a methodfieldserializer instead of a boolean serializer but its leading to the same error. I logged the database query from the serializer and the annotations are not in the query. So it seems like the serializer is … -
Fetching From Multiple Formats of the Same URL
Sorry if the title of the question is misleading, I wasn't sure how to ask it. I bought a URL from GoDaddy. Since I did that, I changed the fetch URL in all react components that fetched from my endpoint from local host to www.bluebird-teaching.com. The problem is, if I type exactly that, I get everything I expect. If I type just bluebird-teaching.com or https://www.bluebird-teaching.com, I still load the same website I made, but I don't see any information fetched with the API. Below is an example component where I fetch. Is there a way to fetch from multiple similar URLs depending on what the user types? componentDidMount() { this.setState({isLoading: false}) fetch("http://www.bluebird-teaching.com/focus_log_api/") .then(response => response.json()) .then(data => { this.setState({ focusInfo: data }) }) } I tried a couple of things in playing around with the fetch URL, but nothing seems to work without fixing one URL problem without creating another. Is it possible to fetch from like different http, or www, etc for the same website? -
How to sort a list containing multiple dictionaries based on a specific value which is an alphanumeric value
I have no idea how to proceed with this problem. I have a list containing multiple dictionaries which has some values. I have to sort the based on a value of 'emp_code' in alphanumeric way and emp_code is an alphanumeric value [{'emp_code':'AB100', 'emp_name':'John'}, {'emp_code':'3', 'emp_name':'Prince'}, {'emp_code':'BA250', 'emp_name':'AC500'}] Please help me with this