Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I inherit another model after creating one with models.Model, [(models.Model) ---> (BaseModel)]
Earlier I created a model like this. class BloodDiscard(models.Model): timestamp = models.DateTimeField(auto_now_add=True, blank=True) created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True) blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True) blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True) quantity = models.FloatField() But now I need to apply inheritance to my model, like this. [(models.Model) ---> (BaseModel)] class BloodDiscard(BaseModel): timestamp = models.DateTimeField(auto_now_add=True, blank=True) created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True) blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True) blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True) quantity = models.FloatField() BaseModel is another model I have created before but forgot to inherit it in my current model. class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status_master = models.ForeignKey(StatusMaster,on_delete=models.SET_NULL,default=3,null=True, blank=True) I applied "python manage.py makemigrations" after changing (models.Model) ---> (BaseModel) and got this... (venv) G:\office\medicover\medicover_bloodbank_django>python manage.py makemigrations You are trying to add the field 'created_at' with 'auto_now_add=True' to blooddiscard without a default; the database needs something to populate existing rows. 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value. The datetime and django.utils.timezone modules are available, so you can … -
pygraphviz cannot be installed in heroku PLEASE HELP ME (HEROKU)
I am trying to deploy django projects using heroku. I set all the dependencies in requirements.txt however, when I push the project to heroku one of the dependency (pygraphviz) keep throws error just like below. I believe that the path is not setted but I do not know how to set the path in heroku Please help me. I believe I need to do something with graphviz/cgraph.h..... remote: [pipenv.exceptions.InstallError]: 2711 | #include "graphviz/cgraph.h```` remote: [pipenv.exceptions.InstallError]: × python setup.py bdist_wheel did not run successfully. remote: [pipenv.exceptions.InstallError]: │ exit code: 1 remote: [pipenv.exceptions.InstallError]: ╰─> [57 lines of output] remote: [pipenv.exceptions.InstallError]: running bdist_wheel remote: [pipenv.exceptions.InstallError]: running build remote: [pipenv.exceptions.InstallError]: running build_py remote: [pipenv.exceptions.InstallError]: creating build remote: [pipenv.exceptions.InstallError]: creating build/lib.linux-x86_64-cpython-39 remote: [pipenv.exceptions.InstallError]: creating build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/testing.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/agraph.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/__init__.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/scraper.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/graphviz.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: creating build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_edge_attributes.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_attribute_defaults.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_graph.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_string.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/__init__.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_scraper.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_readwrite.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_layout.py … -
How do you crawl a url that has Slug in google search console and social media crawling
is anybody who can tell me how to crawl my url that has slug in google search console and social media crawling system like facebook and twitter: this is the url that I want it to be crawled: path('ViewQuestion/<slug:slug>/', views.viewQuestion, name='view-Question'), this is the template of this url: <meta charset="UTF-8"> <title>Question Page</title> <!--Used by Facebook, Pinterest, Google --> <meta property="og:title" content="Question Page"> <meta property="og:url" content="https://www.borinati.com/ViewQuestion"> <meta property="og:image" content="https://res.cloudinary.com/drivemetech/image/upload/v1655308776/ygnvjkbw8tzeqaxhuwxl.jpg"> <meta property="og:site_name" content="Borinati"> <!--Used exclusively by Twitter --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="View-Question Page"> <meta name="twitter:url" content="https://www.borinati.com/ViewQuestion"> <meta name="twitter:image" content="https://res.cloudinary.com/drivemetech/image/upload/v1655308776/ygnvjkbw8tzeqaxhuwxl.jpg"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> when i try to crawl it on facebook under Sharing Debugger: Bad Response Code URL returned a bad HTTP response code. og:title Not Found is any body who can help please ? -
how to upload custom font w/ django project
I am working on a project w/ Django and I am having trouble with fonts. I am able to see the uploaded font on my computer but not on my phone. This is my file path: static | interface | main.css folsom-black.otf This is my code for my html file <style> @font-face { font-family: 'Folsom'; src: url("{% static 'interface/folsom-black.otf' %} format('otf')"); } </style> This is the code for my css file @font-face { font-family: 'Folsom'; src: url('../interface/folsom-black.otf') format('otf'); } -
Showing error after writing command "pip install mysqlclient" for connecting mysql with django framework
As a beginner, I try to connect mysql with django framework. For connecting mysql with django, I changed the settings.py file of "My_First_Porject" project file after creating a database named "my_first_django" in phpmyadmin - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_first_django', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } After that I write "pip install mysqlclient" command to connect mysql with django. Then when I try to migrate by writing "python manage.py migrate", it shows the following error - Traceback (most recent call last): File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "F:\web-development\django-projects\My_First_Porject\manage.py", line 22, in <module> main() File "F:\web-development\django-projects\My_First_Porject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 401, in execute django.setup() File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in … -
Django changes not reflecting AWS Nginx and got CSRF Failed: CSRF token missing while post a request
I hosted my Django app on AWS with Nginx, gunicorn and Postgres. Now I got 3 issues Django changes not reflecting Style not working CSRF Failed: CSRF token missing while post a request Style not working I added STATIC_URL = '/static/' , STATIC_ROOT = os.path.join(BASE_DIR, 'static') on settings.py and + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) on urls.py. CSRF Failed: CSRF token missing while post a request And I'm not using Django rest framework default authentication But I'm using just my own logic. Here is it @csrf_exempt @api_view(['POST']) def student_login(request): if request.method == 'POST': name = request.data['name'] password= request.data['password'] try: user_obj = Admission.objects.get(name = name, password = password) return Response({"Token": user_obj.student_token}, status=status.HTTP_200_OK) except Admission.DoesNotExist: return Response({"Error": "Invalid username or password!"}, status=status.HTTP_400_BAD_REQUEST) return Response({"Error": "Somthing went wrong!"}, status=status.HTTP_400_BAD_REQUEST) -
checkbox django return all false
My checkbox always return False value my model ho_so_giu=models.BooleanField(default=False) my form ho_so_giu = forms.BooleanField(label="Hồ sơ giữ", widget=forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'ho_so_giu_text', 'name': 'ho_so_giu_text',}),required=False) in my html template <div class="form-check form-switch"> {{form.ho_so_giu}} <label class="form-check-label" for="ho_so_giu_text">Hồ sơ giữ</label> </div> in my view, print(form.cleaned_data["ho_so_giu"]) ## return False print(request.POST.get("ho_so_giu")) ## return None print(request.GET.get("ho_so_giu")) ## return None if I try to print ho_so_giu_text it show errors print(form.cleaned_data["ho_so_giu_text"]) KeyError: 'ho_so_giu_text' I am using ajax to return my value from code ho_so_giu =$('#ho_so_giu_text').val() //return on Thanks for reading anh help me -
Validating List Object in Python API Request from JSON Schema
I have defined the schema for validating django rest api request : { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "required": [ "vmname", "os_env", "topology_id", "boot_type" ], "properties": { "failed_devices_list": { "type": "list", "default": [] }, "os_env": { "type": "string", "description": "Name of environment" }, "vmname": { "type": "string", "description": "Name of the VM" }, "topology_id ": { "type": "integer", "description": "Topology Request ID" }, "boot_type": { "type" : "string", "enum": [ "X", "Y" ], "description": "Type of authentication" } } } Its validating perfectly to all the parameters, except failed_devices_list. Its an optional request argument, which has to be empty by default or should have string objects like : failed_devices_list = ["VM001","VM002"] Not sure, how to do it. Any help, is appreciable. Thank you. -
Celery error when getting settings file through environment variable
In my manage.py file I'm getting the name of the settings file through an environment variable: default = os.environ.get('DJANGO_SETTINGS_MODULE_DEFAULT', 'mysite.settings.base') os.environ.setdefault('DJANGO_SETTINGS_MODULE', default) And then I'm setting DJANGO_SETTINGS_MODULE_DEFAULT to a relevant value in each environment, like mysite.settings.dev1 for a certain developer, mysite.settings.staging for our staging server or mysite.settings.production for production. This has been working fine with our Gunicorn server, launched with Supervisor. But with celery, I'm getting the following error both in the worker and beat logs: django.db.utils.OperationalError: FATAL: role "root" does not exist The full stack trace being: Traceback (most recent call last): File "/home/scheduler/scheduler/mysite/manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "/home/scheduler/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/scheduler/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/home/scheduler/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/scheduler/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/scheduler/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/scheduler/scheduler/mysite/notifications/models.py", line 25, in <module> class TeamAssignmentNotification(ChangeNotification): File "/home/scheduler/scheduler/mysite/notifications/models.py", line 48, in TeamAssignmentNotification def send(self, site=Site.objects.get_current()): File "/home/scheduler/local/lib/python2.7/site-packages/django/contrib/sites/models.py", line 60, in get_current return self._get_site_by_id(site_id) File "/home/scheduler/local/lib/python2.7/site-packages/django/contrib/sites/models.py", line 39, in _get_site_by_id site = self.get(pk=site_id) File "/home/scheduler/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/scheduler/local/lib/python2.7/site-packages/django/db/models/query.py", line 328, in get num = len(clone) File "/home/scheduler/local/lib/python2.7/site-packages/django/db/models/query.py", line … -
Django channels with redis
I am trying to make a chat app in Django with channels. I did it from this video. But the way that is used in the video to make the app is with InMemoryChannelLayer that should not be used for production. Then I tried to make the exact same thing that made from channel docs but it didn't work. The only thing that I didn't write in the tutorial of the docs was the docker run -p 6379:6379 -d redis:5. Am I doing something wrong? Please write me an answer of how to do it. Thanks. -
Authorization flow for Microsoft graph API in django and react
I am trying to integrate Microsoft Graph API with my Django backend application. I want to be able to read, manage and send emails on behalf of users. The frontend is built with React My issue now is how the authorization flow will work. I want users to authorize the app(prolly using Oauth) on the frontend after which I will get some kind of access code that I can save on the backend and subsequently use to make requests to the graph APIs on the user's behalf Pls, how do I achieve this flow ?? Any help will be appreciated. I have been scrambling through the docs all day, need someone to point me in the right direction -
Best way to use Oauth2 (for Google Ads API) in Django (Python)
I'm a Django/Python beginner and I want to use the Google Ads API. To access that API, I need to use Oauth2. I've tried following this official example: https://developers.google.com/google-ads/api/docs/client-libs/python/oauth-web But it doesn't work for me and they say it's just a basic implementation (probably not good for production). They mention another doc (https://developers.google.com/identity/protocols/oauth2/web-server#python), but I get lost there and I'm afraid that even if I could create something that works, I would create code that is buggy or insecure (and I guess authentication is an important part to get the security right). I've seen that there are a lot of Django packages for Oauth and I guess they could be a great option for me: https://djangopackages.org/grids/g/oauth/ But I don't know which packages are better. After reading their descriptions, I'm not even sure of which ones can be used for accessing the Google Ads API using Oauth (what I want) and which ones are for creating your own Oauth authentication system (not what I want). Can you give me some recommendations or at least articles/guides to read about this? Thanks a lot! -
How to open django login form in a modal window?
How can i open dJango modal form in a modal popup window? from django_base.forms import User_registration_form def login_view(request): if request.method == 'POST': form = AuthenticationForm(request, data = request.POST) -
Certbot, Apache, Django - Current configuration does not support automated redirection
I want to add ssl certificate for my domain, let's call it "domain.net" I have VPS on Bluehost, Django on Apache and wanted to add certificate using Certbot. During the installation, I got these messages: Deploying certificate Successfully deployed certificate for domain.net to /etc/apache2/conf/httpd.conf Successfully deployed certificate for www.domain.net to /etc/apache2/conf/httpd.conf Failed redirect for domain.net Unable to set the redirect enhancement for domain.net. NEXT STEPS: The certificate was saved, but could not be installed (installer: apache). After fixing the error shown below, try installing it again by running: certbot install --cert-name domain.net Unable to find corresponding HTTP vhost; Unable to create one as intended addresses conflict; Current configuration does not support automated redirection Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details. How to solve this error? Not sure if that will help but here is a 'apachectl -S' out VirtualHost configuration: 127.0.0.1:80 is a NameVirtualHost default server server.domain.com (/etc/apache2/conf/httpd.conf:300) port 80 namevhost server.domain.com (/etc/apache2/conf/httpd.conf:300) port 80 namevhost proxy-subdomains-vhost.localhost (/etc/apache2/conf/httpd.conf:663) wild alias cpanel.* wild alias whm.* wild alias webmail.* wild alias webdisk.* wild alias cpcalendars.* wild alias cpcontacts.* 127.0.0.1:443 is a NameVirtualHost default server server.domain.com (/etc/apache2/conf/httpd.conf:771) port 443 … -
Dockerize Django + mySql app: (2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)") error
I'm trying to dockerize my Django app which uses mySql but I'm facing some problems. It's the first time I use Docker so there may be something basic which I don't understand. Following some online tutorials, this is my Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD . /code/ RUN pip install --upgrade pip && pip install -r requirements.txt RUN pip install mysqlclient COPY . /code/ And this is my docker-compose: version: '3' services: db: image: mysql:8 ports: - '3306:3306' environment: MYSQL_DATABASE: 'database_name' MYSQL_USER: 'django' MYSQL_PASSWORD: 'django-password' MYSQL_ROOT_PASSWORD: 'password' volumes: - .setup.sql:/docker-entrypoint-initbd.d/setup.sql web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE', 'mysql-db'), 'USER': os.environ.get('MYSQL_USER', 'mysql-user'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'mysql-password'), 'HOST': os.environ.get('MYSQL_DATABASE_HOST', 'db'), 'PORT': os.environ.get('MYSQL_DATABASE_PORT', 3306), } } And .env: MYSQL_DATABASE=database_name MYSQL_USER=django MYSQL_PASSWORD=django-password MYSQL_ROOT_PASSWORD=password MYSQL_DATABASE_HOST=db MYSQL_DATABASE_PORT=3306 To dockerize the app, I'm using Docker desktop in Windows 10. After I run: docker-compose up -d I see both containers (db and web) are running, however in the web container I see that django is not able to connect to mySql, as it gives me the error: django.db.utils.OperationalError: (2002, "Can't … -
How to retrieve and map through items of a specific category with Django and react
I'm trying to fetch items of a particular category that then map through the category in react app. I created an API with Django restframework that returns items of such category but using a post request. Here is the code: class ProductCategoryView(APIView): serializer_class = ProductSerializer permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = Product.objects.order_by('-dateCreated').filter(category__iexact=category) serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) For instance, let's say I have 3 categories of items in the database(textbooks, journals and novels). In the react frontend app, I want to retrieve only the textbooks, map through the array of textbooks and display each textbook without displaying any item from other categories. But I have challenges implementing it since I'm using post request. By passing a specific category to the body of the request I get items in that category returned. Is it possible to use get request and filter the items from the database such that I get only the items under the category called textbook? -
Django admin label style
I am trying to apply style on a calculated field in Django. I am able to change the color of the field but I do not know how to apply styles to the related label I am using the following code and I want to style "Total Cash" label @property @admin.display(description="Total Cash") def bar_total_cash(self): return format_html('<span style="color: red; font-weight: bold;">{}</span>', formats.localize(round(self.bar_cash_initial + self.bar_cash_dop + self.bar_cash_usd * self.usd_dop_rate + \ self.bar_cash_eur * self.eur_dop_rate + self.bar_cash_propina - self.bar_credit, 2), use_l10n=True)) -
QuerySet in Django by keywords
I need to display all hashtags that are similar in a QuerySet. But unfortunately, each tag has its own id and is tied to a separate article, but I can’t display information about whether there are articles with the same hashtag (lack of experience) tell me pls views.py class tags(DetailView): model = NewsDB template_name = 'navigation/tags.html' context_object_name = 'News' def get_context_data(self, *, object_list=None, **kwargs): articles = super(tags,self).get_context_data(**kwargs) articles['post'] = Hashtags.objects.filter(Hashtag=self.kwargs['pk']) return articles urls.py path('tags/<str:pk>',views.tags.as_view(),name='tag') models.py class NewsDB(models.Model): title = models.CharField('Название',max_length=300) text = models.TextField('Текст статьи') img = models.ImageField('Фото',upload_to='News',null='Без фото') avtor = models.ForeignKey('Journalist', on_delete=models.PROTECT) date = models.DateField('Date', null=True, blank=True) time = models.TimeField('Time',null= True) def __str__(self): return self.title class Hashtags(models.Model): News=models.ForeignKey('NewsDB',on_delete=models.PROTECT) Hashtag=models.CharField('Хештег',max_length=30,null='Без темы') def __str__(self): return self.Hashtag -
Is it possible to implement when a person scans the qr code he automatically logged into the account on the web site
How can this be done? if possible. I'll be glad if you can tell me. I roughly understood how to create a qr code. But automatic registration via qr code don't know -
How to fix django-admin version 4.0.4 NOT detecting my migrations?
I am working with django-admin version 4.0.4 recently I delete all files and folders inside my migration folder and use makemigrations and migrate command. that works fine. But after that when I try to make changes add models OR change, makemigrations NOT detecting my changes. -
Project architectures differences for Django + Vuejs (or other) integration
I'm currently looking at project setups for a Django + Vuejs project (though I guess the question is likely just as valid for other frontends, react, svelte etc.). It seems that there are mainly 2 approaches that come up often, resulting in the following project structure: The frontend embedded within the Django project (perhaps as a git submodule): root ├── djangoapp ├── djangoproject ├── manage.py ├── requirements.txt ├── static ├── venv └── vueproject ├── node_modules ├── package.json ├── public └── src Another approach is to have them at the same level from project root, as 2 seperate projects actually (or I guess both could be git submodules to a "wrapper" project), so essentially: root ├── djangoproject │ └── <django files & folders> └── vueproject └── <vue files & folders> With the 2nd approach, it seems you basically just see Django as an API. Stuff like collectstatic does not (?) come into play. In development, you need a server up to serve Django's api, and a dev server for the vue frontend. With the 1st approach (if I understand correctly), seems that you build the Vue static files, and then manage all of that with Django's collectstatic/static files management. Seems the … -
Django post request for initial view
In Django I have a function def foo(): #(Here I want to call url: helloWorld with post request args) #I know there is libraries like Requests, but are there any django quicker methods? return HttpResponse("ok") and url: path('/path/to/url/', views.foo, name='helloWorld') -
django search human readable values
I am trying to write a query that searches the human readable values of an option list. class Book(models.Model): title = models.CharField(max_length=256) authors = models.CharField(max_length=256, default=None) GENRE = [ ('0', 'None'), ('1', 'Action-Adventure'), ('2', 'Autobigraphy'), ('3', 'Biography'), ('4', 'Classic'), ('5', 'Drama'), ('6', 'Fantasy'), ('7', 'Fiction'), ('8', 'Historical'), ('9', 'Mystery'), ('10', 'Non-Fiction'), ('11', 'Romance'), ('12', 'Science-Fiction'), ] genre = models.CharField(max_length=2, choices=GENRE, default='0') book_cover = models.ImageField(upload_to='covers/', default=None) description = models.TextField(default=None) added_by = models.CharField(max_length=256, default=None) date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.title and here is my search view. def search_books(request): if request.method == 'GET': query = request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups = Q(title__icontains=query) | Q(authors__icontains=query) | Q(genre__icontains=query) | Q(added_by__icontains=query) results = Book.objects.filter(lookups).distinct() context = {'book_list': results, 'submitbutton': submitbutton} return render(request, 'books/book_list.html', context) else: return render(request, 'books/book_list.html') else: return render(request, 'books/book_list.html') Is there any way to search the values of genre, such as 'Action-Adventure' instead of the numeric value? -
Error the current path match any of these
Whenever i try to load login,register page its showing Using the URLconf defined in loan.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] register [name='register'] logout [name='logout'] form [name='form'] predict [name='predict'] The current path, register/, didn’t match any of these How can i solve this issue from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('login', views.login, name="login"), path('register', views.register, name="register"), path('logout', views.logout, name="logout"), path('form', views.form, name="form"), path('predict', views.predict, name="predict"), ] from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth from .models import Prediction import joblib import pandas as pd from sklearn.preprocessing import scale from sklearn.impute import SimpleImputer res = 'X' # Create your views here. def index(request): return render(request, "index.html") def login(request): if request.method == "POST": name = request.POST['username'] pas = request.POST['password'] user = auth.authenticate(username=name, password=pas) if user: auth.login(request, user) print(user.is_authenticated) return redirect("/") else: messages.info(request, "User does not exist") return redirect("login") else: return render(request, "login.html") def register(request): if request.method == "POST": fname = request.POST['first_name'] lname = request.POST['last_name'] email = request.POST['email'] uname = request.POST['username'] pas1 = request.POST['password1'] pas2 = request.POST['password2'] if pas1 == pas2: if User.objects.filter(username=uname).exists(): messages.info(request, "Username already exists") return render(request, "register.html") elif User.objects.filter(email=email).exists(): messages.info(request, … -
Does Google App Engine allow file caching (using Django)?
I am seeing a problem that Django's file-based caching is not functional in Google App Engine. Ideally I want to use commands such as below to read/write from a Google Cloud Storage Bucket. output = cache.get(cacheKey) #or cache.set(cacheKey, output, timeout = 60*15) I have seen some articles on memcaching, but that is not what I need. Is it possible to combine Django's file-based caching with Google Cloud Storage? How do I perform this (and what permission settings are required?)