Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's static file (.js) is not displayed on frontend
This is my folder structure in my react.js app. I have set NO router to display worker.js file on frontend. The file is just there with no further settings. And yet, since its in "public" folder, I can display it on my frontend like this My question is, how can I achieve same thing with Django? ***I tried different urls, different paths to see my file on my frontend but nothing worked ***... I also tried to set path/router for worker.js both in django and react side but then its rendered as html... I need it to be seen as js file. I need to achieve this because I'm using that react app's production folder in my Django app as template and need that worker.js file to be reachable in that same link you see in the image. My settings.py file: ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "settledhead/build/static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "settledhead/static_root") ... And this is how react's production folder looks like in my django app -
in Django make calculate remaining dates
I have this code for calculate remaining days. The result in first field works great. But How can I get all result for others fields in same first one. I have tried but, I do not know how to make it. Any idea please any help would be greatly appreciated here iterate through ending date Django part {% for obj in obj %} </td> <td class="end-dates"> <div id="end_date"> {{obj.date_end|date:"M d Y"}} </div> </td> {% endear %} script part <script> function func (){ var endDate = document.getElementById('end_date').innerHTML; console.log(' end date :', endDate) const EndDatesAll = document.getElementsByClassName('end-dates'); const currentEndDateCount = EndDatesAll.length console.log(EndDatesAll.length) var today = new Date().getTime(); var date2 = new Date(endDate).getTime(); var diff = Math.floor( date2 - today); days = Math.floor(diff / (1000 * 60 * 60 * 24)); hours = Math.floor(diff / (1000 * 60 * 60)); mins = Math.floor(diff / (1000 * 60)); secs = Math.floor(diff / 1000); dd = days; hh = hours - days * 24; mm = mins - hours * 60; ss = secs - mins * 60; console.log(currentEndDateCount) document.getElementById('remaining-days').innerHTML = days; } func(); </script> -
How to solve this error "django.core.exceptions.FieldError: Cannot resolve keyword 'user' into field."
` Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/rest_framework/mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) File "/Users/mihirshah/Desktop/picalert/create_area_api/views.py", line 17, in get_queryset return self.queryset.filter(user=self.request.user) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1420, in filter return self._filter_or_exclude(False, args, kwargs) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1438, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1445, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1532, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1562, in _add_q child_clause, needed_inner = self.build_filter( File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1407, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1217, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1709, in names_to_path raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'user' into field. Choices are: created_at, created_by, created_by_id, desc ription, end_date, id, start_date, title ` create_area_api/serializers.py ` from rest_framework … -
Django Test | How to pass a a dictionary containing a dictionary value through clients.post
I have a dictionary A that contains a single value that is also a dictionary B B = {"k1": "v1", "k2": "v2", "k3": "v3"} A = {"User": B} This type of dictionary is used in one of my views function def views_function(request): # request.data is a dictionary containing a single value that is also a dictionary. Just like A I'm trying to write a unit test for views_function from django.test.TestCase. from django.test import TestCase class test_cases(TestCase): def setUp(self): self.B = {"k1": "v1", "k2": "v2", "k3": "v3"} self.A = {"User": self.B} self.url = reverse("views_function_url") def test_views_function(self): response = self.client.post(url, self.A, format="json") But clients.post seems unable to take A as an input. When I print A inside test_views_function it shows the proper dictionary. def test_views_function(self): B = {"k1": "v1", "k2": "v2", "k3": "v3"} A = {"User": B} print(A) # {"User": {"k1": "v1", "k2": "v2", "k3": "v3"}} response = self.client.post(url, A, format="json") But when I add a print statement to views_function for some reason only the last key of B is there def views_function(request):{"User": "k3"} print(request.data.dict()) # {'User': 'k3'} -
How do i stop dark mode from flickering when page is refreshed
I'm having a difficulty in stopping my night mood from flickering whenever a user refresh page or try navigating to their timeline, the dark mode flicker making it not look professional even though I check some solution on here that said I should put the dark mode function at the top of my base HTML for it to be the first to load, which didn't work in my case and I was wondering what seem to be problem or what could I do, can any one be of help. {% load static %} <!DOCTYPE html> <html lang="en"⚡> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Favicon --> <link href="{% static 'images/logot.png' %}" rel="icon" type="image/png"> <link href="https://fonts.googleapis.com/css2?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://unpkg.com/@trevoreyre/autocomplete-js/dist/style.css"/> <!--AMP--> <!-- Basic Page Needs ================================================== --> <title>Fassfy</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- icons ================================================== --> <link rel="stylesheet" href="{% static 'css/icons.css' %}"> <!-- CSS ================================================== --> <link rel="stylesheet" href="{% static 'css/uikit.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/tailwind.css' %}"> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> <link rel="stylesheet" href="{% static 'cropperjs/dist/cropper.min.css' %}"> </head> <body> {% if request.user.is_authenticated %} <div class="container" id="id_loading_spinner" style="display: none"> <div class="d-flex flex-row mx-auto flex-grow-1 justify-content-center"> <div class="spinner-border text-primary" role="status"> … -
502 Bad Gateway (13 permission denied) Nginx + Gunicorn
I am trying to deploy a simple hello-world Django site to EC2 (Ubuntu 22.04) using Gunicorn and Nginx. Nginx and Gunicorn services are both reporting as running successfully, and the .sock file has been created seemingly without issue. Gunicorn configuration file: [Unit] Description=gunicorn daemon After=nextwork.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/sites/mysite-main ExecStart=/home/ubuntu/.local/share/virtualenvs/mysite-main-_EzVOJAm/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/sites/mysite-main/mysite-main.sock myapp.wsgi:application [Install] WantedBy=multi-user.target Nginx configuration: server { listen 80; server_name <domainname>.com <ipaddress>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/sites/mysite-main; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/sites/mysite-main/mysite-main.sock; } } Permissions on the .sock file, as well as both the "sites" and "mysite-main" directories are ubuntu:www-data. I attempted to try moving it out of the ubuntu user's home directory into a more "common" location in case it was permissions on the home directory stopping it, but was unable to even get the .sock file to generate in that case, probably due to my unfamliarity with how this works. It looks like this is one of the most queried problems of all time, but I've tried every solution I could find to no avail. Any help would be greatly appreciated. Thanks in advance! -
Get Choice Description in queryset.value_list django
I have a model and within it I have IntegerChoice Class (Gender) When I get field value with values_list() I don't want to get value as a number (1 or 2) but as a label string (Female or Male) class Policy(models.Model): class Gender(models.IntegerChoices): MALE = 1, _("Male") FEMALE = 2, _("Female") maca = models.CharField(max_length=100, db_column="Maca", null=True, blank=True) Policy.objects.all().values_list("maca", "gender") -
Multiple file environment variable in django project without docker
In the open source project that I am planning to develop, Docker is used to use several env files, but I have to run the project without Docker. Does anyone have a solution? I also added this part of the code to the settings import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # Take environment variables from .env file environ.Env.read_env(os.path.join(BASE_DIR, '.env')) But still it gives the following error The SECRET_KEY setting must not be empty. -
How to know which extension is chaning the code in VSCode
I have this code in VSCode: import django from models import Product The problem is that when I save the file, VSCode change the code (somehow trying to beautify it): from models import Product import django I had this Prettier extension, and I disabled it, but I still got the problem. -
How can I use addEventListener to multiple buttons which are displayed with a for loop?
I have a page that displays social media posts from users and all posts have an Edit button. When the Edit button is clicked on, a form with a textarea pre-filled with the current content and a submit input is displayed. The problem is that regardless of which post's Edit button I click, always the first post is changing. I guess I should add an "id" somewhere to track which post is being edited but I couldn't figure out how to do that. Or is there another solution? views.py: def index(request): post_list = AllPost.objects.all().order_by("date").reverse() paginator = Paginator(post_list, 10) # Show 10 posts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "posts": post_list, "page_obj": page_obj }) def edit(request, id): if request.method == "POST": new_content = request.POST["new_content"] updated_post = AllPost.objects.filter(id = id) updated_post.update(content = new_content) return JsonResponse({}, status = 201) return JsonResponse({"error": "Bad Request"}, status = 400) index.html: {% for post in page_obj %} {{ post.full_name|upper }}<br> <div class="frame"> <h4><a href="{% url 'profile' post.user.username %}" style="color: black;">{{post.user.username}}</a></h4> {% if post.user == user %} <button class="btn btn-sm btn-outline-primary" id="edit">Edit</button> {% endif %} <div id="content">{{post.content}}</div> <form action="{% url 'edit' post.id %}" method="post" id="edit_post" style="display: none;"> {% csrf_token %} <div class="form-group"><textarea … -
When does using sqlite become a bottleneck?
I am currently working my way through the Udemy course Python Django - The Practical Guide by Academind, and during the deployment section the author mentions that one deployment consideration is the choice of database. He states that for larger sites with a larger volume of requests, using a sqlite database (the default when using Django) can become problematic and can slow down the site. However, he does not go on to explain this in a quantitative way. Is there some value, or perhaps a rule of thumb, by which you could draw a line between those sites for which a sqlite database is adequate, and those for which it is not? Thanks -
Run scarpy project from djnago views,py
I am building a scraper which will extract email ids from website urls , and i want this to integrate this to my Django views.py module. I have my project structure as follows : emails emails -init.py -asgi.py -settings.py -urls.py e_scrapy (django-app) email_scrapper //scrapy project spiders --init__.py -email_extraction.py init.py items.py middlewares.py pipelines.py settings.py scrapy.cfg __init__.py admin.py apps.py models.py tests.py urls.py //manually added views.py my email_extraction.py have this code:: import scrapy from scrapy.spiders import CrawlSpider, Request import re from scrapy_selenium import SeleniumRequest from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import openpyxl from time import sleep import xlsxwriter from bs4 import BeautifulSoup import os from selenium import webdriver from pathlib import Path from tldextract import extract class EmailExtractor(CrawlSpider): name='emailex111' def __init__(self,filename): self.queries=[] self.emaillist=[] self.row=0 self.write_wb=xlsxwriter.Workbook('emails_list.xlsx') self.sheet=self.write_wb.add_worksheet('sheet1') self.filename=filename wb=openpyxl.load_workbook(self.filename) self.save_file=self.filename+"_emails.txt" sh=wb.active for i in range(1,sh.max_row+1): cell_obj=sh.cell(row=i,column=1) tsd, td, tsu = extract(cell_obj.value) search_query=td + '.' + tsu #pass_val='"@'+str(search_query)+'" Email Address' self.queries.append(search_query) def start_requests(self): WINDOW_SIZE="1920,1080" path="C:/Users/iamfa/OneDrive/Desktop/SCRAPY/email_extraction/email_extraction/spiders/msedgedriver.exe" options=webdriver.EdgeOptions() #options.add_argument("--headless") #options.add_argument("--window-size=%s" % WINDOW_SIZE) options.add_argument('--ignore-ssl-errors=yes') options.add_argument('--ignore-certificate-errors') options.add_experimental_option('excludeSwitches', ['enable-logging']) browser=webdriver.Edge(options=options,executable_path=path) url_list=[] for query in self.queries: # iterate through queries url="https://www.bing.com/search?q=%40"+str(query)+"+%22Email+Address%22" try: browser.get(url) links=browser.find_elements(By.TAG_NAME,'cite') for link in links: url_list.append(link.text) except: continue resultno=0 for results in url_list: if resultno==5: break try: resultno+=1 yield SeleniumRequest( url=results, callback=self.parse, wait_until=EC.presence_of_element_located( (By.TAG_NAME, … -
Problem with rendering objects on the template Django
I am trying to make a filter on my ecommerce website. I am taking a data using json from the user and filtering items on the views.py. There are no any errors and I can see the filtered products on the console. However, I can not render products on the template. It is not giving any errors. It's just not showing. views.py def Products(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() gender = Gender.objects.all() categories = Category.objects.all() product_types = ProductType.objects.all() try: data = json.loads(request.body) productTId = data['productTId'] productVId = data['productVId'] genderId = data['genderId'] genderId = get_object_or_404(Gender, id=genderId) productVId = get_object_or_404(Category, id=productVId) productTId = get_object_or_404(ProductType, id=productTId) filtered_products = Product.objects.filter(typeP=productTId).filter(category=productVId).filter(Gender=genderId) countFilter=filtered_products.count() print(filtered_products) print(countFilter) return JsonResponse(filtered_products, safe = False) except: None try: context = {'countFilter':countFilter,'filtered_products':filtered_products,'gender':gender,'categories':categories,'product_types':product_types,'products':products, 'cartItems':cartItems, 'order':order, 'items':items} except: context = {'gender':gender,'categories':categories,'product_types':product_types,'products':products, 'cartItems':cartItems, 'order':order, 'items':items} return render(request, 'product.html', context) html {% for product in filtered_products %} <div class="card"> <div class="card__img"> <picture><source srcset="{{product.imageURL}}" type="image/webp"><img src="{{product.imageURL}}" alt=""></picture> </div> <h6 class="card__title">{{product.name}}</h6> <div class="card__descr">{{product.description}}... <div class="card__more" onclick="More('{{product.id}}')">подробнее...</div> </div> <div class="card__func"> <a class="btn-hover card__button-buy update-cart" data-product="{{product.id}}" data-action="add">В КОРЗИНУ</a> <div class="card__right"> <div class="card__price" data-product="{{product.id}}">{{product.price}} р</div> <div class="card__changed-price card__changed-price--card"> <div class="card__changed-btn card__changed-btn--prev card__changed-btn--max increase" data-product="{{product.id}}" data-action="minus"><svg width="8" height="2" viewBox="0 0 8 2" … -
Error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' But the module is installled
I get the error above when launching my django project, I am on windows I have tried installing the module again and tried pip install psycopg2-binary as well.I also checked out other treads but they don't seem to work I need to fix it pretty soon so thank you in advance! -
Limiting amount of objects user can add in another object
I just have a quick question, I would like to limit exercises in training unit to 3-5 exercises , and limit trianing units in trainingplan to 12 training units, so the user will not add an infinite ammount of exercises,or infinite amount of training units in a plan? class TrainingPlan(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) nameoftheplan = models.CharField(verbose_name="Name of the plan",max_length=20, null=True) Squat1RM = models.PositiveIntegerField(verbose_name="100%RM in squat",default=0, blank=True, null=True) DeadliftT1RM =models.PositiveIntegerField(verbose_name="100%RM maximal repetition in deadlift",default=0, blank=True, null=True) Benchpress1RM = models.PositiveIntegerField(verbose_name="100%RM maximal repetition in benchpress",default=0, blank=True, null=True) mesocycle= models.CharField(max_length=40, choices=MESOCYCLE_CHOICES,default=MESOCYCLE_GPP) timeoftheplan= models.CharField(max_length=40,choices=TIME_CHOICE,default=TIME_WEEK3 ) def __str__(self): return str(self.nameoftheplan) class TrainingUnit(models.Model): trainingplan=models.ForeignKey(TrainingPlan, on_delete=models.CASCADE) class Exercise(models.Model): trainingunit=models.ForeignKey(TrainingUnit,on_delete=models.CASCADE) exercisename=models.CharField(max_length=100,verbose_name="Exercise",choices=EXERCISE_CHOICES) exercisesets=models.IntegerField(choices=SETSCHOICES) exercisereps=models.IntegerField(choices=REPCHOICES) -
How to calculate the values of child-tables by using ForeignKey from a parent-table
My purpose is to gain averages of values stored in child-tables depending on each parent-table. In my case, I want to gain averages of satisfaction stored in the Evaluation model (child) depending on each Professor model (parent). models.py class Professor(models.Model): college = models.CharField(max_length=50, choices=COLLEGE_CHOICES) name = models.CharField(max_length=50) def __str__(self): return self.name class Evaluation(models.Model): name = models.ForeignKey(Professor, on_delete=models.CASCADE, related_name='evaluation_names', null=True) satisfaction = models.IntegerField(choices=SATISFACTION_CHOICES) def __str__(self): return self.comment views.py class ProfessorDetail(generic.DetailView): model = Professor context_object_name = "professor_detail" template_name = "professors/professor_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['avgs'] = Professor.objects.all().evaluation_set.all().annotate(avg_satisfactions=Avg('satisfaction')) return context professors/professor_detail.html {% for evaluation in avgs %} <p>{{ evaluation.avg_satisfactions }}</p> {% endfor %} I tried following codes for views.py. context['avgs'] = Professor.objects.all().evaluation_set.all().annotate(avg_satisfactions=Avg('satisfaction')) context['avgs'] = Professor.objects.prefetch_related().all().annotate(avg_satisfactions=Avg('satisfaction')) context['avgs'] = Professor.objects.all().prefetch_related(Prefetch('evaluation_set', queryset=Evaluation.objects.all().annotate(avg_satisfactions=Avg('satisfaction')))) But, all of them do not work. -
How to use static files in the Django code
Hi there, on my Django 4.0 project, I'm implementing a profanity filter validator. So I have a file.txt with a list of profanity words. I put that file in my static folder and now need to use it in my validators.py code. But how to import it to the code for usage? I think it's a bit tricky. Please advise somehting.. -
Sending html button status to django view
I am trying to create a button the picks orders from a list of paid products to a list of unpaid or Vice versa upon clicking the pick me button. But I don’t know how to go about this problem as Iam not well vested in using JavaScript. What I want is when a user clicks the pick me button on the list of unpaid orders, the order stops showing on the unpaid orders and starts to show on the paid orders and Vice versa or rather when the click the pick me button the order goes to the myorders list in there account. I tried just filtering with jinja templates and sending the value of the button as True on a condition model field that by default I made false then sending it as post form data to the view. But this just kept blowing up in my face as it did not work when the order will be made by someone else and picked by someone else -
how to resolve eror - "django.db.utils.ProgrammingError"
' File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/mihirshah/Desktop/api/create_area_api/urls.py", line 3, in <module> from create_area_api.views import api_create_area File "/Users/mihirshah/Desktop/api/create_area_api/views.py", line 7, in <module> class api_create_area(viewsets.ModelViewSet): File "/Users/mihirshah/Desktop/api/create_area_api/views.py", line 10, in api_create_area print(queryset.get()) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 646, in get num = len(clone) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 376, in __len__ self._fetch_all() File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1866, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 87, in __iter__ results = compiler.execute_sql( File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1398, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute return super().execute(sql, params) File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute with self.db.wrap_database_errors: File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "accounts_project" does not exist LINE 1: ...."start_date", "accounts_project"."end_date" FROM "accounts_... ` I typed cmd - "python3 manage.py makemigrations" and encountered the above error, I tried several commands and tried refreshing the database too by changing it, Deleted all the .pyc in migrations and pycache folder but still … -
Django Models: How to add two lists of options in a way that one is dependent on the other
I have two models in salesnetwork application, as below. salesnetwork.models: class Provinces(models.Model): name = models.CharField(max_length=255, db_collation="utf8mb3_unicode_ci") class Meta: db_table = "provinces" def __str__(self): return self.name class Cities(models.Model): province = models.ForeignKey("Provinces", models.DO_NOTHING) name = models.CharField(max_length=255, db_collation="utf8mb3_unicode_ci") class Meta: db_table = "cities" def __str__(self): return self.name In another app named core, I have a model for a contact form as below: core.models: class ContactUsFormModel(models.Model): first_name = models.CharField(max_length=200, blank=False, null=False) last_name = models.CharField(max_length=200, blank=False, null=False) # province = Provinces //How to add Provinces? # // TODO add phone number field # phone_number = models.IntegerField(max_length=11) email = models.EmailField(blank=False, null=False) subject = models.CharField(max_length=250, blank=False, null=False) message_body = models.TextField() def __str__(self): return self.subject Whic I use this model for creating a ModelForm as below: core.forms: class ContactForm(ModelForm): class Meta: model = ContactUsFormModel fields = "__all__" widgets = { "first_name": forms.TextInput( attrs={ "class": "form-control", "placeholder": "First name", "required": "True", } ), "last_name": forms.TextInput( attrs={ "class": "form-control", "placeholder": "Last name", "required": "True", } ), "email": forms.EmailInput( attrs={ "class": "form-control", "placeholder": "email@address.com", "required": "True", } ), "subject": forms.TextInput( attrs={ "class": "form-control", "placeholder": "Subject", "required": "True", } ), "message_body": forms.Textarea( attrs={ "class": "form-control", "placeholder": "Write your message here.", "required": "True", } ), } Now the GOAL is to add a … -
what is the difference between Django and React . which is better for a new programmer in future ? HELP ME OUT
DJANGO AND REACT DIFFERENCES In future which would be more applicable. OR more scope in future . -
Data not being passed from views.py to template
I'm passing a dictionary to views.py and I want to output data from it to the site page. But instead I get pure html, no data. views.py: ` def index(request): data = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [37.62, 55.793676] }, "properties": { "title": "«Легенды Москвы", "placeId": "moscow_legends", "detailsUrl": "static/Moscow_map/places/moscow_legends.json" } } ] } return render(request, 'index.html', context=data) ` index.html: ` {{ data|json_script:"data-b" }} <script id="data-b" type="application/json"> </script> ` -
Pymongo : Ignore null input value when searching documents
In mongodb i have many document structure like this in root collection _id: ObjectId() A : "a" B : "b" _id:ObjectId() A : "c" B : "d" And then i want to find document depend on user input, for example data = request.data item_A = data.get('A', None) item_B = data.get('B', None) for item in root.find({ 'A': item_A, 'B': item_B }): print(item) but the problem is if the user just want to find document depend on A and dont have input value for item_B then item_B will be None, so that the code don't return anything. Any suggestion? -
Can't open User model using mongo db
I'm using mongo db in my django project. Whenever I try to open a record of User model in django admin, it gives me this error All the other models are working fine. But getting problem in User model and my user model is -
How to block user authorization for Django Rest Framework in custom Middleware?
Hi I am creating a custom middleware in Django for the DRF. So that when an user try to access any of the api the middleware will perform some operation and determine if the user is authorized to access the endpoint or not. My code is like below: class PermissionMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): if request.path.startswith('/admin/'): return None if request.path.startswith('/api/'): is_allowed = True if not is_allowed: return # < -- What needs to return to block the access return None My problem is what should I return from the method for disallowing access to api? I can return None, if I want to give access. But I want to disallow access and return some message from the api view so that user knows that he is not allwed. So in summery: What should I return from the middleware to block access? How can I return message to user from the view that he is not authorized? Thanks