Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run an url in views in Django?
I have a PDF uploading form. When a user sends this form I want to trigger a URL in my views. I want the invoked URL address to be opened only once in the backend. The user cannot view this page. The reason I want this is that the API I call from here enables me to do another process. How can I run an URL in my views backend? views.py def upload_pdf(request, id): if request.method == 'POST': customer = get_object_or_404(Customer, id=id) form = PdfForm(request.POST, request.FILES) if form.is_valid(): new_pdf = form.save(commit=False) new_pdf.owner = customer new_pdf.save() name = new_pdf.pdf.name.replace(".pdf", "") url = 'https://api..../perform/{0}'.format(name) return redirect('ocr', id=new_pdf.id) else: form = PdfForm() customer = get_object_or_404(Customer, id=id) return render(request, 'upload_pdf.html', {'form': form, 'customer': customer}) -
How to add custom Header in Authlib on Django
I would need some of your help adapting Authlib with Django. I'm trying to develop a Django app using OpenId and Authlib to connect my users and facing an issue with the access token, the issue invalid_client occurs. Using Postman I found out that the OpenId provider needs some parameters in the Header like 'Content-Length' or 'Host'. When the Header param is defined in client.py, it works like a charm. However, I'd like to pass the custom header from views.py (mostly to avoid defining the Host directly in the package), but authorize_access_token doesn't allow multiple arguments, def auth(request): token = oauth.customprovider.authorize_access_token(request) Maybe the "Compliance Fix for non Standard" feature might help, but I wasn't able to adapt it for Django and the Header parameter https://docs.authlib.org/en/stable/client/oauth2.html#compliance-fix-oauth2 from authlib.common.urls import add_params_to_uri, url_decode def _non_compliant_param_name(url, headers, data): params = {'site': 'stackoverflow'} url = add_params_to_uri(url, params) return url, headers, body def _fix_token_response(resp): data = dict(url_decode(resp.text)) data['token_type'] = 'Bearer' data['expires_in'] = int(data['expires']) resp.json = lambda: data return resp session.register_compliance_hook( 'protected_request', _non_compliant_param_name) session.register_compliance_hook( 'access_token_response', _fix_token_response) Does anyone know a way to pass a custom Header to Authlib or defining it using the Compliance Fix and Django? Thank in advance ! -
Selenium automated testing error: selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
I am using Selenuium to test a Django website. When I run my test, I get the following error: TypeError: 'WebElement' object is not callable Here are the relevant snippets of my code: base.py import os import sys from pathlib import Path from selenium import webdriver from selenium.webdriver.remote.remote_connection import LOGGER as SELENIUM_LOGGER, logging as selenium_logging from webdriver_manager.chrome import ChromeDriverManager sys.path.insert(0, str(Path(os.path.dirname(__file__)).parent.absolute()) ) from django.urls import reverse from django.test import TestCase from django.contrib.auth import get_user_model User = get_user_model() TESTING_URL_ROOT = os.environ.get('TESTING_URL_ROOT', 'http://127.0.0.1:8000') # https://stackoverflow.com/questions/23407142/how-do-i-reduce-the-verbosity-of-chromedriver-logs-when-running-it-under-seleniu SELENIUM_LOGGER.setLevel(selenium_logging.WARNING) # https://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class class BaseTestCases: class BaseTest(TestCase): def setUp(self): chrome_options = webdriver.ChromeOptions() chrome_options.headless = True chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("disable-infobars"); # disabling infobars chrome_options.add_argument("--disable-extensions"); # disabling extensions chrome_options.add_argument("--disable-gpu"); # applicable to windows os only chrome_options.add_argument("--disable-dev-shm-usage"); # overcome limited resource problems chrome_options.add_argument(f"user-data-dir={str(Path.home())}") # https://stackoverflow.com/questions/31062789/how-to-load-default-pro chrome_options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36") self.browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options) # ... def tearDown(self): self.browser.quit() # For Django client object, which can work with relative URLs def get_relative_url_from_route_name(self, route_name): route_name = route_name.strip() return f"{reverse(route_name)}" # for selenium, which requires FULL URL def get_full_url_from_route_name(self, route_name): route_name = route_name.strip() if not route_name: return TESTING_URL_ROOT else: return f"{TESTING_URL_ROOT}{reverse(route_name)}" # Default is set to True, because Selenium provides better UI testing # e.g. Javascript … -
Issue with static files when deploying Django app to Heroku
My project folder looks this: ├── Procfile ├── core │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ └── views.cpython-39.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── inspirationSources.txt ├── manage.py ├── package-lock.json ├── package.json ├── react-frontend │ ├── README.md │ ├── build │ │ ├── asset-manifest.json │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── logo192.png │ │ ├── logo512.png │ │ ├── manifest.json │ │ ├── robots.txt │ │ └── static │ ├── package-lock.json │ ├── package.json │ ├── public │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── logo192.png │ │ ├── logo512.png │ │ ├── manifest.json │ │ └── robots.txt │ └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── assets │ ├── components │ ├── hooks │ ├── index.css │ └── index.js ├── requirements.txt ├── spotify │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── admin.cpython-39.pyc │ │ ├── apps.cpython-39.pyc │ │ ├── cluster.cpython-39.pyc │ │ ├── credentials.cpython-39.pyc │ │ ├── models.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ ├── util.cpython-39.pyc │ │ └── … -
Django File Based Caching
In Django File Based Caching, if I create an entry, does it create individual entries for each individual process? I am creating the entry from settings.py file. Thank you -
Selenium automated testing error: TypeError: 'WebElement' object is not callable
I am using Selenuium to test a Django website. When I run my test, I get the following error: TypeError: 'WebElement' object is not callable Here are the relevant snippets of my code: base.py import os import sys from pathlib import Path from selenium import webdriver from selenium.webdriver.remote.remote_connection import LOGGER as SELENIUM_LOGGER, logging as selenium_logging from webdriver_manager.chrome import ChromeDriverManager sys.path.insert(0, str(Path(os.path.dirname(__file__)).parent.absolute()) ) from django.urls import reverse from django.test import TestCase from django.contrib.auth import get_user_model User = get_user_model() TESTING_URL_ROOT = os.environ.get('TESTING_URL_ROOT', 'http://127.0.0.1:8000') # https://stackoverflow.com/questions/23407142/how-do-i-reduce-the-verbosity-of-chromedriver-logs-when-running-it-under-seleniu SELENIUM_LOGGER.setLevel(selenium_logging.WARNING) # https://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class class BaseTestCases: class BaseTest(TestCase): def setUp(self): chrome_options = webdriver.ChromeOptions() chrome_options.headless = True chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("disable-infobars"); # disabling infobars chrome_options.add_argument("--disable-extensions"); # disabling extensions chrome_options.add_argument("--disable-gpu"); # applicable to windows os only chrome_options.add_argument("--disable-dev-shm-usage"); # overcome limited resource problems chrome_options.add_argument(f"user-data-dir={str(Path.home())}") # https://stackoverflow.com/questions/31062789/how-to-load-default-pro chrome_options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36") self.browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options) # ... def tearDown(self): self.browser.quit() # For Django client object, which can work with relative URLs def get_relative_url_from_route_name(self, route_name): route_name = route_name.strip() return f"{reverse(route_name)}" # for selenium, which requires FULL URL def get_full_url_from_route_name(self, route_name): route_name = route_name.strip() if not route_name: return TESTING_URL_ROOT else: return f"{TESTING_URL_ROOT}{reverse(route_name)}" # Default is set to True, because Selenium provides better UI testing # e.g. Javascript … -
Django-Channels: dictionary update sequence element #0 has length 0; 2 is required
I am working on a Django project who uses Django channels for notifications and private messages. Everything works perfectly fine when a user is connected. But when no user is connected (login and register page) I get this error: dictionary update sequence element #0 has length 0; 2 is required There is no sockets code on the anonymous page (register/login). Does anyone know the issue? Environment: Request Method: GET Request URL: http://127.0.0.1:8000/users/login/ Django Version: 3.1.5 Python Version: 3.7.3 Installed Applications: ['wall.apps.WallConfig', 'users.apps.UsersConfig', 'notifications.apps.NotificationsConfig', 'sockets', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'channels'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 339, in thread_handler raise exc_info[1] File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 38, in inner response = await get_response(request) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 263, in _get_response_async response = await sync_to_async(response.render, thread_sensitive=True)() File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 304, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\asyncio\tasks.py", line 388, in wait_for return await fut File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 343, in thread_handler return func(*args, **kwargs) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) … -
Initialise and increment counter with pagination notb working in django
I have a set of results that I fetch from the database and I use pagination to display 3 per page. I want the results to be formatted in a table where I get the post saying number 1 per row. Then when I hit next, it should be number 4, 5 and 6 listed in the table. However, it is not working if I use a counter. Can you guys help please? Thank youu xoxo Here is my code snippet for the template: {% with count=1 % } {% for internship, skills, emp_steps in posts %} <tr style="background-color: #F0F8FF"> <td>{{ count|add:"1" }}</td> <td>{{internship.internship_title}}</td> <td>{{ internship.posted_date }}</td> <td align="center" > <a href="{% url 'edit_internship' internship.id %}" class="btn btn-success btn- sm">Edit <i class="fa fa-pencil" aria-hidden="true"></i></a>&nbsp;&nbsp;</td> </tr> {% endfor %} {% endwith %} -
Is there a way to display the extra forms at the top when using django InlineModelAdmin instead of the bottom after all the existing forms?
Am using inlines(InlineModelAdmin) in my django Admin interface to make it easier to edit the models of the Parent model. However, by default, the extra forms for models appear at the bottom. The problem is that there may be a lot of previous records such that you have to scroll to the bottom to add a new record. Is there a way to change this default behavior such that the new extra forms appear at the top? -
user_id = getattr(user, api_settings.USER_ID_FIELD) AttributeError: 'str' object has no attribute 'id
I am trying to authenticate a user through their email using DRF but so far it's only errors i've been getting. This is the class that handles the email verification class VerifyEmail(GenericAPIView): def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) # Decodes the user token and the secret key to get the user ID print(payload) user = User.objects.get(id=payload['user_id']) # Gotten the user ID if not user.is_verified: # Runs an if statement to see if the user has been verified already user.is_verified = True user.save() data = {"confirmation_message": "Your account has been verified"} return Response(data, status=status.HTTP_200_OK) except jwt.ExpiredSignatureError as identifier: error = {"expired_activation_link": "The activation link has expired"} return Response(error, status=status.HTTP_400_BAD_REQUEST) except jwt.DecodeError as identifier: error = {"invalid_token": "The token is invalid request a new one"} return Response(error, status=status.HTTP_400_BAD_REQUEST) and this is the error i keep getting Internal Server Error: /auth/register Traceback (most recent call last): File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 469, … -
Can't load css and js files from static directory. was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
My project was working perfectly fine, i don't know what happened. I didn't even make any changes to front end, i was working on back end. On reloading my website to check a feature, suddenly all of my css disappeared. On checking the console, there were messages like: The resource from “http://127.0.0.1:8000/static/events/css/profile.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). 127.0.0.1:8000 The resource from “http://127.0.0.1:8000/static/events/css/nav.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). .......... Some cookies are misusing the recommended “SameSite“ attribute 2 The resource from “http://127.0.0.1:8000/static/events/css/events.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). 127.0.0.1:8000 Loading failed for the <script> with source “http://127.0.0.1:8000/static/events/src/navbar.js”. 127.0.0.1:8000:276:1 The resource from “http://127.0.0.1:8000/static/events/src/navbar.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff) I am giving all the resources in an obvious way: {% load static %} {% extends 'app/base.html' %} <link rel="stylesheet" type="text/css" href="{% static 'events/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'events/css/events.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'events/css/post_form.css' %}"> <script type="text/javascript" src="{% static 'events/src/navbar.js' %}"></script> ........ I have no idea what went wrong all of a sudden Can someone please help me with this!! -
Django ImageField Default Image
In my project I want to allow users to upload profile picture. I am using imagefield but the default option is not working and hence I am getting an error. **models.py** class Profile_Pic(models.Model): user = models.OneToOneField(User,null=True,on_delete=models.CASCADE) profile_pic = models.ImageField(null=True,blank=True,default='images/logo.png',upload_to='images') @property def default(self): if self.profile_pic: return self.profile_pic.url else: return 'logo.png' class Meta: db_table = 'Profile_Pic' **views.py** @login_required def profile(request): user = request.user.profile_pic form = Photo(instance=user) context = {'photo': form} return render(request, 'datas/profile.html', context) **settings.py** STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'admin_car/static/media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'admin_car/static/images') ] **profile.html** <div style="text-align: left;position:absolute;top:50px;left:16px;float: left"> <img class="image" src='{{ user.profile_pic.profile_pic.url }}' style=" height: 200px; width: 200px" alt="logo.png"> <style> img { border-radius: 50%; } </style> Is there any way where I can add a default picture whenever a new user is created? Any help would be appreciated. -
django2.1,Use mysql to custom login,MySQL: "Field 'id' doesn't have a default value"
I try to custom login Django2.1 with Mysql,and I got this error: Field 'id' doesn't have a default value.But I had set ID is 'auto_increment' and 'not null': Where am I wrong?By the way, it is OK with sqlite3.So weird. This is my models.py: from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.contrib.auth.models import AbstractUser @python_2_unicode_compatible class AliUser(AbstractUser): userid = models.CharField(max_length=20, default='') # user Id empid = models.CharField(max_length=100, default='') sso_token = models.CharField(max_length=36) # SSO Token token_time = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name Here is my backends.py: from django.contrib.auth.backends import RemoteUserBackend from naxxramas.models import AliUser as User class AliSSOUserBackend(RemoteUserBackend): def authenticate(self, request, userId, empId, first_name='', last_name='', email=''): if not userId or not empId: # not my company user return None user = None try: user = User.objects.get(empid=empId) self.create_unknown_user = False except User.DoesNotExist: pass if self.create_unknown_user: user, created = User.objects.update_or_create( empid=empId, defaults={ 'username': email.split('@', 1)[0], 'empid': empId, 'userid': userId, 'first_name': first_name or last_name or '', # first_name may be null 'last_name': last_name or '', 'email': email, }) if created: user = self.configure_user(user) return user if self.user_can_authenticate(user) else None And this is my views.py,i found it may wrong at "auth_login": from django.conf import settings from django.contrib.auth import authenticate, … -
UniqueConstraint and ignore case sensitive
I would like to use this code: constraints = [ models.UniqueConstraint(fields=['name', 'app'], name='unique_booking'), ] but name and app (both of them) should not check case sensitive so "FOo" and "fOO" should be marked as the same app. How to do it? -
Is there a way to run django constantly on the server to update a database based on live data
I am developing a virtual stock market application on django and came upon the following problem. In any stock market application, there is an option of limit buy, stop loss and target sell. This essentially means to buy a share if it ever touches a price which is lower than the current price, to sell a share if it touches a very low price and to sell a share if it touches a high price respectively. For this, the server needs to constantly monitor the live data coming in from the API of a particular stock and perform the action if it happens. However, during this time no one may be making any requests on the site so how do I get django to monitor the prices of the stocks every 5 seconds or so to check if the order needs to be executed or not? -
How to redirect to another page after admin login (Django)
I'm working on an administration page in Django and I want to redirect an user to another page than the basic one, for example : localhost:8000/admin/my-app/table/ instead of localhost:8000/admin/. How can I do that ? Thanks for your help. -
Django how to pass a dictionary as a value to the Response of a GET request and make sure that the Django Rest Web App for API still works
I have an application and want to pass a dictionary as a value to the response of a GET request when the user does a GET request on /inventory/item_mast/. The response that the user should get is: { pk:1, item_name: "laptop" item_cat_name: {id:1,name:"techonology"} } The model that I have is: class Item_Mast(AbstractBaseModel): pk = models.AutoField(primary_key=True) item_name = models.CharField(max_length=50) item_cat_mast = models.ForeignKey("inventory.Item_Cat_Mast", on_delete=models.SET_NULL, null=True) def __str__(self): return self.item_name The serializer I have is: class Item_Mast_Serializer(serializers.ModelSerializer): item_cat_mast = IdNameField(id_field='pk',name_field='item_cat_name', queryset=Item_Cat_Mast.objects.all()) class Meta: model = Item_Mast fields = '__all__' I have written a Custom Serializer to return data for ForeignKey fields in the format {id:"some_id",name:"some_name"}. The code for it is: class IdNameField(serializers.RelatedField): def __init__(self, *args, **kwargs): id_field = kwargs.pop('id_field', None) name_field = kwargs.pop('name_field', None) super(IdNameField, self).__init__(*args, **kwargs) self.id_field = id_field self.name_field = name_field def to_representation(self, obj): return { 'id': getattr(obj,self.id_field), 'name': getattr(obj,self.name_field), } def to_internal_value(self, data): try: if(type(data) == dict): try: return self.get_queryset().get(**{self.id_field:data["id"]}) except KeyError: raise serializers.ValidationError('id is a required field.') except ValueError: raise serializers.ValidationError('id must be an integer.') else: return self.get_queryset().get(**{self.id_field:data}) except: raise serializers.ValidationError('Obj does not exist.') The view is: class Item_Mast_ListView(mixins.ListModelMixin,GenericAPIView): queryset = Item_Mast.objects.all() serializer_class = Item_Mast_Serializer This works and the response of the GET request is the desired data, however … -
copy .sql file data into postgresql database table my_table in python and Django
In my project folder I have somedata.sql file and I want to insert data from that somedata.sql file into table mytable in postgresql database. So, How can I insert somedata.sql file data into mytable in postgresql database. somedata.sql INSERT INTO public.mytable( id, webservice_id, name, alias, enabled, "Logo", "Link", "SEOName", cashback, addeby, addedon, advertiser_id) VALUES (6, 4, 'Newegg', 'Newegg', 1, 'http://www.some.com/', 'http://www.some.com/', 'Newegg.com', '1', 0, '2019-05-03 16:30:35.000000', '1'), (8, 3, 'HobbyTron.com', 'HobbyTron.com', 1, 'http://www.some.net/', 'http://www.some.com/', 'HobbyTron', '2', 0, '2019-05-03 16:30:35.000000', '1'); mytable is model in models.py class mytable(models.Model): webservice_id = models.IntegerField() name = models.TextField(max_length=128) alias = models.TextField(max_length=64) enabled = models.IntegerField() Logo = models.TextField(max_length=2000) Link = models.TextField(max_length=200) SEOName = models.TextField(max_length=200) cashback = models.IntegerField(null=True, blank=True) addeby = models.IntegerField() addedon = models.DateTimeField(editable=False) advertiser_id = models.TextField(max_length=50) -
I have an issue that how can I convert flask to django by following condition
I am doing this project first time. I have to manage a multithreaded queue in my django app. User sends request to app will automatically added(append) to queue. If user is at first location then 30 seconds time is alloted to that first user and it will redirected to main page while other users are waiting in queue (other page will showing you are in queue) till first user will terminate his session. After terminating first user, second user automatically getting to first and alloted 30 seconds and redirected to main page. exited user will redirected to exit page. Please help me to solve this problem in django -
How to set read only property to entire Django forms based on session user
I have created a form that can be used to update/create/view records. When a user selects a record that record data is rendered in the form. So that user will able to view/edit the form. The problem statement here is that if a record is created by some other user then the session user will not able to edit (only the creator should have access to edit). I am thinking to write a logic so that when the record is created by the session user then only he/she will edit. Otherwise, the user will just view the record using the same form. Below is my view file current_blog = Blog.objects.get(pk=blog_id) init_dict = { "blog_title": current_blog.blog_title, "blog_description": current_blog.blog_description, "last_modified": current_blog.last_modified } form = NewBlog(initial=init_dict) return render(request, "myblog/blog.html", {"new_blog": form}) form.py class NewBlog(forms.Form): blog_title = forms.CharField(label="Form Title", max_length=250, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Enter title here"} )) blog_description = forms.CharField(label="Blog Description", widget=forms.Textarea( attrs={"class": "form-control", "placeholder": "Enter blog Description"} )) blog.html {% for field in new_blog %} <div class="col-sm-12"> <fieldset> {{ field.label }} {{ field }} <div class="text-danger">{{ field.errors }}</div> </fieldset> </div> {% endfor %} -
Implementing Djoser and JWT in Django for user authentication
I am implementing user authentication in my first Django app. I decided to follow a tutorial from here. I just finished the implementation, and it happens that when I add the following route path('api/app', include('app.urls')),to the url.py, I get the following error, which crashes t he platform: .... File "/Users/frankydoul/opt/anaconda3/lib/python3.8/site-packages/django/urls/resolvers.py", line 123, in _check_pattern_startswith_slash if regex_pattern.startswith(('/', '^/', '^\\/')) and not regex_pattern.endswith('/'): RecursionError: maximum recursion depth exceeded while calling a Python object Removing it let the platform running. Is anybody familiar with the error please ? -
zappa deployment : [ERROR] CommandError: Unknown command: 'create_pg_db'
I followed the tutorial on https://romandc.com/zappa-django-guide/walk_database/ and pip installed the package, added the value to installed apps, configured the aws aurora postgres then when I do zappa manage project_name create_pg_db I get [ERROR] CommandError: Unknown command: 'create_pg_db' Traceback (most recent call last): File "/var/task/handler.py", line 609, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 243, in lambda_handler return handler.handler(event, context) File "/var/task/handler.py", line 408, in handler management.call_command(*event['manage'].split(' ')) File "/var/task/django/core/management/init.py", line 105, in call_command raise CommandError("Unknown command: %r" % command_name)[END] did I miss anything, what can I do to fix this? -
Django/Daphne, got NotImplementedError calling asyncio.create_subprocess_exec( under WINDOWS
I am using Django 3.2 with Daphne 3.0.2, Python 3.8.9 under Windows 10. Trying to call proc = await asyncio.create_subprocess_exec( python_exe, bridge_script, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, ) Gives me following error: Exception Type: NotImplementedError Exception Location: c:\python\python38\lib\asyncio\base_events.py, line 491, in _make_subprocess_transport When serving Django/ASGI with daphne. Under Linux everything runs fine. Serving under Windows with Python runserver also everything fine, Just daphne & windows gives me the error. Thanks for any help. -
Python and markdown I can't print inside html
I'm using Django and this is my python code import markdown def link(request): output = markdown.markdownFromFile('entries/CSS.md') print(output) this is my html code ` Encyclopedia <h1>All Pages</h1> {{ link }} below is inside CSS.md I want it to print inside my html page inside {{ link }} `CSS CSS is a language that can be used to add style to an HTML page.` > [![I'm having this message][1]][1] -
ngrok: DJango and nodejs: how to add multiple ports
How can i add multiple ports I have nodejs and django application webapp: image: "python-node-buster" ports: - "8001:8000" command: - python manage.py runserver --noreload 0.0.0.0:8000 networks: - django_network node: image: "python-node-buster" ports: - "3000:3000" stdin_open: true networks: - node_network ngrok: image: wernight/ngrok:latest ports: - 4040:4040 environment: NGROK_PROTOCOL: http NGROK_PORT: node:3000 NGROK_AUTH: "" depends_on: - node - webapp networks: - node_network - django_network networks: django_network: driver: bridge node_network: driver: bridge Assuming i get the url for node at http://localhost:4040/inspect/http http://xxxx.ngrok.io and in my nodejs application, i want to access http://xxxx.ngrok.io:8001 for apis How to configure this