Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
query set object could not be shown in website in Django
I have used Django2 in python3.7 to develop a web app in windows. I want to show a list of query set in html. view.py: @csrf_exempt def View_by_Course_list(request): print(request.method) if request.method == 'POST': ... query_results_book = Title.objects.filter(id=query_results_book_id).values() print(query_results_book) return render(request, 'list.html', context={'query_results_book': query_results_book}) list.html: {{query_results_book}} <ol> {% for obj in query_results_book %} <li>{{obj.title}} <br> iSBN:{{obj.isbn}} <br> Format issued: {{obj.is_etextbook}}</li> {% endfor %} </ol> The print debug, print(query_results_book) outputs this: <QuerySet [{'id': 4, 'created': datetime.datetime(2020, 6, 25, 10, 15, 41, 856235), 'isbn': 11112, 'is_etextbook': 'Textbook', 'title': 'ACC210 Accounting for Decision Making and Control (customised text), McGraw-Hill'`}]> But in the website page nothing is shown. I have added {{query_results_book}} in the html for debug, but also nothing shown. -
Show only most viewed post from last 2 days
I am building a BlogApp and I am stuck on a Problem. What i am trying to do:- I am trying to access only BlogPosts which is mostly viewed in last 2 days. models.py class BlogPost(models.Model): blog_post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_blog_posts',editable=False) views.py def viewd_post(request): d = timezone.now() - timedelta(days=2) posts = BlogPost.objects.annotate(total_views=Count('viewers')).filter(date_added__gte=d).order_by('-total_views') context = {'posts':posts} return render(request, 'most_views.html', context) What have i tried :- I also tried annotate method to get most viewed post, It works perfectly like : it shows most viewed blogpost at top but it shows all the posts which are posted in last two days and got no views. Any help would be Appreciated. Thank You in Advance. -
SAML2 with Django stuck on infinite loop
I am trying to use the djangosaml2 1.1.0 module in order to implement SSO login. After the successful login, it gets stuck in an infinite loop trying to constantly login again. I have tried to remove the @login_requried decorator, it works on then. But, I need the @login_required decorator in order to prevent not logged in users to access specific views. My believe is that django.contrib.auth.backends.ModelBackend is not properly configured with djangosaml2.backends.Saml2Backend This is my code: settings.py SAML_CONFIG = { # full path to the xmlsec1 binary programm 'xmlsec_binary': '/usr/bin/xmlsec1', # your entity id, usually your subdomain plus the url to the metadata view 'entityid': 'http://localhost:8000/saml2/metadata/', # directory with attribute mapping 'attribute_map_dir': path.join(BASEDIR, 'attribute-maps'), # this block states what services we provide 'service': { # we are just a lonely SP 'sp' : { 'name': 'Federated Django sample SP', 'name_id_format': saml2.saml.NAMEID_FORMAT_PERSISTENT, # For Okta add signed logout requets. Enable this: # "logout_requests_signed": True, 'endpoints': { # url and binding to the assetion consumer service view # do not change the binding or service name 'assertion_consumer_service': [ ('http://localhost:8000/tacdb/items/', saml2.BINDING_HTTP_POST), ], # url and binding to the single logout service view # do not change the binding or service name 'single_logout_service': [ … -
Django Q Filter - Too many Values to unpack
I want to dynamicly create some filter criteria depending on the url query params. For this I created a nested Django Q-Object which looks like: query = <Q: (AND: (OR: region=30, region=39), name__endswith=Hannover, zip_code=30165)> Now I want to pass this Q object to Model-Filter Eort.objects.filter(query) Thereby I get a ValueError : too many values to unpack (expected 2) Traceback (most recent call last): File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\felix\Documents\WZO\WZO\WZO_App\views.py", line 47, in get log.debug(Eort.objects.filter(eq)) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1380, in _add_q split_subq=split_subq, check_filterable=check_filterable, … -
scheduled web scraper using django and celery
I want to scrape multiple websites at every 15 minutes. If there's no update (new feed) found after 5 tries, I want to stop the worker and trigger a notification. I have tried the following: @app.task def scrape(): urls = Website.objects.all() for obj in urls: s_data = scrape(obj.url) for s in s_data: ser = WebsiteSerializer(data=s, many=True) ser.is_valid() ser.save() return 'updated' Celery config: app.conf.beat_schedule = { # Executes every 15 min 'scrape': { 'task': 'app.tasks.scrape', 'schedule': crontab(minute='*/15') }, } I am not sure if I should put a range function in scrape to execute 5 times and delay or there is a way to configure the celery settings? -
make django2exe python3.9 compatible
I want to use django2exe to run my django project. The problem is that it's using Python-2.7.10 and my django project is using Python3.9.1. I have tried replacing the Python-2.7.10 folder with Python3.9.1 folder and still not working, I don't know if I'm doing it right. -
Server taking too long to respond and I'm getting response 504 Gateway Time-out when running Docker, Nginx, Gunicorn
I have implemented an endpoint to upload excel file and then save the records into the database. Tested running locally on machine environment without using docker; When the request is made the file is uploaded, read and records saved on DB successfully and I get the response as a success. When I run on docker the request is taking too long and then get a 504 Gateway Time-out. logs: worker_1 | [2021-04-05 08:49:28,229: INFO/MainProcess] celery@e7d1cfa8d332 ready. appseed-app_1 | [2021-04-05 08:52:48 +0000] [11] [DEBUG] POST /api/uploaded_files/ nginx_1 | 2021/04/05 08:53:50 [error] 22#22: *2 upstream timed out (110: Connection timed out) while reading response header from upstream, client: x.x.x.x, server: , request: "POST /api/uploaded_files/ HTTP/1.1", upstream: "http://x.x.x.x:5006/api/uploaded_files/", host: "localhost:86" nginx_1 | x.x.x.x - - [05/Apr/2021:08:53:50 +0000] "POST /api/uploaded_files/ HTTP/1.1" 504 167 "-" "PostmanRuntime/7.26.10" "-" appseed-app_1 | [2021-04-05 11:54:19 +0300] [1] [CRITICAL] WORKER TIMEOUT (pid:11) appseed-app_1 | [2021-04-05 08:54:19 +0000] [11] [INFO] Worker exiting (pid: 11) appseed-app_1 | [2021-04-05 11:54:19 +0300] [24] [INFO] Booting worker with pid: 24 Questions Why is this happening? How do I fix this problem. I attempted to increase gunicorn's timeout to 90 and added 4 workers in the gunicorn-cfg.py file and also did a couple of changes to … -
Reset Password Using Django
I am trying to reset password using Django but I am getting the following error: Method Not Allowed (POST): /reset/done/ Method Not Allowed: /reset/done/ Below is my form: <form action="{% url 'password_reset_complete' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="password" class="form-control" name="new_pass" placeholder="New Password" required autofocus> </div> <div class="form-group"> <input type="password" class="form-control" name="confirm_pass" placeholder="Confirm Password" required> </div> <input type="submit" value="Update Password" class="btn btn-primary btn-block"> </form> URL path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='feebeeapp/login.html'), name='password_reset_complete') Not sure, what I am doing wrong. Can someone please guide me? -
! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/cardamageapp.git'
I followed the exact steps as mentioned in the article 'https://medium.com/bithubph/how-to-deploy-your-django-applications-on-heroku-8b58fdb09dd0', while deploying my django project to heroku. However, I am getting the following error: [git push heroku master][1] Please could anyone let me know what could be the possible issue. FYI: I have the Procfile, requirements.txt, runtime.txt in my project root directory. I am also sure my credentials are correct. Also, I havnt pushed anything to master before and I am the only owner of this app. My runtime.txt has the code: python: 3.7.9. My Procfile has the code: web: gunicorn cardamage.wsgi --log-file - My requirements.txt: absl-py==0.12.0 astunparse==1.6.3 cachetools==4.2.1 certifi==2020.12.5 chardet==4.0.0 cycler==0.10.0 dj-database-url==0.5.0 Django==1.10 django-heroku==0.3.1 gast==0.3.3 google-auth==1.28.0 google-auth-oauthlib==0.4.4 google-pasta==0.2.0 grpcio==1.36.1 gunicorn==20.1.0 h5py==2.10.0 idna==2.10 importlib-metadata==3.10.0 joblib==1.0.1 Keras==2.4.0 Keras-Applications==1.0.8 Keras-Preprocessing==1.1.2 kiwisolver==1.3.1 Markdown==3.3.4 matplotlib==3.4.1 numpy==1.20.2 oauthlib==3.1.0 opt-einsum==3.3.0 pandas==1.1.5 pickle5==0.0.11 Pillow==8.2.0 protobuf==3.15.7 psycopg2==2.8.6 pyasn1==0.4.8 pyasn1-modules==0.2.8 pyparsing==2.4.7 python-dateutil==2.8.1 pytz==2021.1 PyYAML==5.4.1 requests==2.25.1 requests-oauthlib==1.3.0 rsa==4.7.2 scikit-learn==0.24.1 scipy==1.4.1 seaborn==0.11.1 six==1.15.0 tensorboard==2.2.2 tensorboard-plugin-wit==1.8.0 tensorflow==2.2.0 tensorflow-estimator==2.2.0 termcolor==1.1.0 threadpoolctl==2.1.0 typing-extensions==3.7.4.3 urllib3==1.26.4 Werkzeug==1.0.1 whitenoise==5.2.0 wrapt==1.12.1 zipp==3.4.1 -
python django prefetch_related on form set and inlineformset_factory
Hi folks I have a forms.inlineformset_factory with 50 extra rows. It is taking forever to load and getting 204 queries are running to get that data with almost 200 duplicate queries how do I get prefetch_related in the forms.inlineformset_factory here is the code from forms.py AddReceipeDetailFormSet = forms.inlineformset_factory( ReceipeMaster, ReceipeDetail, fields=( 'item_type', 'item', 'quantity'), extra=50, widgets={ 'item_type': forms.Select(attrs={'class': 'form-control'}), 'item': forms.Select(attrs={'class': 'form-control'}), 'quantity': forms.NumberInput(attrs={'class': 'form-control'}), } ) Here is my view from views.py def create_receipe(request): child_forms = AddReceipeDetailFormSet(request.POST or None) parent_form = ReceipeCreateForm(request.POST or None) context = {'parent_form': parent_form, 'child_forms': child_forms} if request.method == 'POST': if parent_form.is_valid(): print('parent form is valid') else: print('invalid parent form', parent_form.errors) if child_forms.is_valid(): print('child form is valid') else: print('invalid child form', child_forms.errors) print("post request is received***", request.POST) return render(request, 'receipes/create.html', context=context) regards -
If block not being evaluated in templates
I am trying to render a list of items using ListView like so: views.py class EventView(generic.ListView): model = Event template_name = 'timer/index.html' def get_queryset(self): events = Event.objects.order_by('-day')[:7] return events events is then passed to index.html like so: index.html {% block content %} {% if events %} <ul> {% for event in events %} <li><a href="{% url 'timer:detail' event.id %}"></a>>{{ event }}</a></li> {% endfor %} </ul> {% else %} No events to show {% endif %} {% endblock %} The challenge is that the else block is always returned. I made sure that I have objects in my db and they are never returned. What am I doing wrongly? -
django.jQuery is not a function
I am using redis cache and select2 with settings like this: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': [env('REDIS_URL', default="redis://127.0.0.1:6379"), env('REDIS_REPLICA_URL', default="redis://127.0.0.1:6379")], 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'IGNORE_EXCEPTIONS': True } }, 'select2': { 'BACKEND': 'django_redis.cache.RedisCache', # 'LOCATION': 'redis://127.0.0.1:6379/2', 'LOCATION': env('SELECT2_CACHE_URL', default='redis://127.0.0.1:6379/2'), 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'IGNORE_EXCEPTIONS': True, 'MAX_ENTRIES': 10000 }, 'TIMEOUT': 60*30 } } Error found is this : Not Found: /select2/fields/auto.json on the python debugger console When I do inspect element in the browser I get: 1. django_admin_hstore_widget.js:171 Uncaught TypeError: django.jQuery is not a function at django_admin_hstore_widget.js:171 2. jquery.js:10099 GET http://localhost:8000/select2/fields/auto.json?field_id=IjE0ZjIxNjE2LWIxNTgtNDUxYi05NWEzLTM4YmQ1NzBjYzQyOSI%3A1lTKnr%3A8caHvDkhDEVA4bOSFOfsaVaxqQs Basically select2 is unable to load results wherever it is used in the code. -
Django Wagtail - How to set the date format?
I have created a Blog with the Django CMS "Wagtail". As a part of a blog page, I want to set a date in a specific format. Now, setting the date itself is not a problem at all. The blog page is constructed a bit like this: date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) author = models.ForeignKey(BlogAuthor, on_delete=models.PROTECT, null=True) ... The DateField then creates a date on my blog page in the format "April 2, 2021". Alas, as we are located in Germany I'd like to change this format to "2. April 2021". I was searching a lot whether it would be feasible to add a parameter to the DateField in order to define the format. Didn't find anything that worked so far. Any ideas? Thanks in advance! Timo -
Django Model save methode
I trying to add a save method for an model: def save(self, *args, **kwargs): if self.Position: ProductImages.objects.filter(Position=self.Position, ProductID=self.ProductID).update( Position=self.Position+1) It is working fine, but if I have an Image in Position 1 and one in 2 and add another in Position 1 then I have 2 times Images in Position 2. Is there an uncomplicated way to check all Positions with the ProductID? -
How to use sqlite3 database with Django on Kuberenets pod
I am having one python-django project which consist of sqlite3 database, I am deploying it on Kubernetes pod, wanted to know how to access the sqlite3 database, once I deploy the app on Kubernetes. Generally If I was using postgres or mysql, I would have created another pod and then expose my services, not sure for sqlite3 database. How to access it and use the database, or I have to create a new pod for sqlite3? Dockerfile for my Django app: FROM python:3.4 RUN apt-get update \ && apt-get install -y --no-install-recommends \ sqlite3 \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] -
How to achieve Asynchronous I/O in python2.7?
I have my project running in django1.1, how to implement async support for one of the methods which involves call made to db, I want to optimize it. I have gone through tornado library but I am not sure how to implement / use it with django1.1. Please suggest if there is any other library to achieve async support and how to use tornado with django -
Errors during configuration of the neo4j django-neomodel
I'm trying to do a simple project in Django using the Neo4j database. I've installed a django-neomodel library, set the settings as follows: import os from neomodel import config db_username = os.environ.get('NEO4J_USERNAME') db_password = os.environ.get('NEO4J_PASSWORD') config.DATABASE_URL = f'bolt://{db_username}:{db_password}@localhost:7687' created a model: class Task(StructuredNode): id = UniqueIdProperty() title = StringProperty() added 'django_neomodel' to INSTALLED_APPS, removed the default database configuration and when I try to enter the website it raises the error: ImproperlyConfigured at / settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.. It's the only error because after running the python manage.py install_labels command it raises: ServiceUnavailable("Failed to establish connection to {!r} (reason {})".format(resolved_address, error)) neo4j.exceptions.ServiceUnavailable: Failed to establish connection to IPv6Address(('::1', 7687, 0, 0)) (reason [Errno 99] Cannot assign requested address). I'm pretty sure that the database works correctly because as you see I can access this. screenshot docker-compose: version: "3.9" services: api: container_name: mm_backend build: context: ./ dockerfile: Dockerfile.dev command: pipenv run python manage.py runserver 0.0.0.0:8000 volumes: - ./:/usr/src/mm_backend ports: - 8000:8000 env_file: .env depends_on: - db db: container_name: mm_db image: neo4j:4.1 restart: unless-stopped ports: - "7474:7474" - "7687:7687" volumes: - ./db/data:/data - ./db/logs:/logs -
When i am trying to upload file its showing FieldFile is not JSON serializable - Django
TypeError at /web/ticketcreation/ Object of type FieldFile is not JSON serializable here is my models.py class Ticket(models.Model): Email=models.CharField(max_length=60) to=models.CharField(max_length=60) cc=models.CharField(max_length=60) subject=models.CharField(max_length=25) module = models.CharField(max_length=25) priority = models.CharField(max_length=25,null=True) message = models.CharField(max_length=70) choosefile = models.FileField(null=True, blank=True) -
How to make a blogpost model in Django?
I am trying to make a website and I want to add blogs and articles to my website using the admin page. How do I make a model that takes both text and the images I want after every paragraph in my article? If that's not possible how do I input both separately and render it in the correct order together? -
How to get the uploaded file content in json format using django rest framework?
Hi I was trying to get the get the uploaded file content in json format as response ( not file details) Upto now I did the upload of file using django rest framework which I did mention in my previous question “detail”: “Method \”GET\“ not allowed.” Django Rest Framework now I am getting the json response as follows in the given picture link https://ibb.co/wzTmG6W please help me thanks in advance -
Compare two text files to show changes made like in version control systems in python
Background: I'm trying to make a VCS for text articles using django as a learning project, like so, where anyone can edit an article and the changes made can be displayed on the site. Till now I've only found the difflib module. I've copied and tried code from here. import difflib lines1 = ''' How to Write a Blog Post This is an extra sentence '''.strip().splitlines() lines2 = ''' How to Write a Blog Post '''.strip().splitlines() for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0): print (line) It outputs the following: --- file1 +++ file2 @@ -2 +1,0 @@ -This is an extra sentence But this code only shows the differences between two files and even in that it won't show differences properly if for example words or letters in a line are edited. Is there a python library/module which can help show the changes made to the file or even the differences between any two edits? -
How to calculate the price of Order using (sum of) OrderItems prices in django rest framework
I am able to calculate the OrderItem model prices using @property decorator but unable to calculate the total price of the Order model while creating the order object. When I called the post api for creating the orde, there is no error but I am not getting total_price in the api response. My models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) #logic to calculate the total_price, and its not working @property def total_price(self): return sum([_.price for _ in self.order_items_set.all()]) #realted name is order_items def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) #total_item_price = models.PositiveIntegerField(blank=True,null=True,default=0) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') #Logic to calculate the total_item_price, it works. @property def price(self): total_item_price = self.quantity * self.order_variants.price return total_item_price My serializers: Class OrderItemSerializer(serializers.ModelSerializer): order = serializers.PrimaryKeyRelatedField(read_only=True) #price = serializers.ReadOnlyField() class Meta: model = OrderItem fields = ['id','order','orderItem_ID','item','order_variants', 'quantity','order_item_status','price'] # depth = 1 class OrderSerializer(serializers.ModelSerializer): billing_details = BillingDetailsSerializer() order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) # total_price … -
How to make Django link to different html pages based on the result of a form?
I am confused on how to change html pages based on the results of a form. I want to create a form to get a search query. Based on this query, a page should be rendered to the user. For example, if the page query is chocolate, then a page should be main/chocolate. Same for any other query: main/"query". How is it possible to do this? I have tried using a normal form in order to do this, but this did not work. I have tried: this is from views.py: if request.method == "GET": ask = NewForm(request.GET) if ask.is_valid: Muk = ask.cleaned_data("Stuff") result = util.get_entry(Muk) good = markdown2.markdown(result) return page(request, good) else: return render(request, "encyclopedia/index.html") return render(request, "encyclopedia/layout.html", { "form": ask })``` And it always meets me with an error page, since earlier in views.py, I defined: def page(request, name): ```stuff = util.get_entry(name) if stuff is None: return render(request, "encyclopedia/error.html") things = markdown2.markdown(stuff) return render(request, "encyclopedia/content.html", { "things":things })def page(request, name): stuff = util.get_entry(name) if stuff is None: return render(request, "encyclopedia/error.html") things = markdown2.markdown(stuff) return render(request, "encyclopedia/content.html", { "things":things })``` -
How to count and make addition with for loop with a table in Django?
I created a customer system. In this system, a user has several customers. I have a Customer model and this model has multiple fields like risk_rating, credit_limit, country, etc... I want to list the countries where customers are located and show data about them in a data table. I am using .distinct() method for that, but I cannot figure out how can I show some data. For example, I want to total credit_limit (adding operation) in the related country and I want to count all customers that have Low risk risk_rating. I can do this the long way with if statement. But I can't think of anything other than just creating a concatenated if statement for all countries. This would be a very long and inefficient way. Because there are 208 countries in the world. How can I do that? Note: I try to use for loop counter for counting the number of risks but it did not work properly. models.py class Customer(models.Model): RISK_RATING = [ ('Low Risk', 'Low Risk'), ('Medium Risk', 'Medium Risk'), ('Moderately High Risk', 'Moderately High Risk'), ... ] customer_name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False) credit_limit = models.FloatField(default=0, null=True) risk_rating = models.CharField(max_length=50, default='Select', choices=RISK_RATING, … -
Django suddenly gives me error that Apps aren't loaded yet
I am using Django3.1. All was working fine. I pip installed a new app and tried to run makemigrations. It suddenly doesn't work anymore. I get error 'Apps are not loaded yet'. I thought it was the app. Uninstalled it. Didn't work. Deleted the virtualenv directory. Created new one and installed all apps again except the last one. It didn't work. I had installed another version of Postgres and hadn't restarted my computer since then. Restarted but didn't work. Tested by running another project to make sure it was not new Postgres issue. That worked as expected. Commented out my url confs and installed apps in the settings.py. But still the same error. Tried multiple SO suggestion related to this error but nothing works. Can anyone please help. Error from console: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\checks\translation.py", line 60, …