Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Authentication Form Customize, Doubles Field
The Goal is To Customize Form, Then Pass it to LoginView. I am using AuthenticationForm after Customizing it, but i see it repeats extra one input, I guess it is for username, i need only two inputs, E-Mail and Password. any advice. Forms: class AccountSignInForm(AuthenticationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'E-Mail..'}), label='E-Mail') password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password..'}), label='Password') class Meta: model = Account fields = ['email', 'password'] Views: class AccountLoginView(LoginView): template_name = 'accounts/login.html' form_class = AccountSignInForm success_url = 'HomePageView' URLS: app_name = 'accounts' urlpatterns = [ path('sign-in', views.AccountLoginView.as_view(), name='login'), ] HTML: <h1>Login Form</h1> <form method="POST"> {% csrf_token %} {% for field in form %} <div>{{ field.label }}</div> <div>{{ field }}</div> {% endfor %} <input type="submit" value="Login" /> </form> enter image description here Any Ideas,. -
Get url kwargs in class based views
I need to retrieve the value of the pk written in the url in my class based view : path('<int:pk>/data/', views.DataView.as_view(), name='data'), However, what I saw everywhere was the pk retrieved in the definition of methods like get or post. What I want is to be able to use it to define my class variables, because I need to do get the same value from this pk in every method inside my class, like below : class DataView(ContextMixin, UpdateView): pk = get_pk_from_url ... value = ... def get(self, request, *args, **kwargs): value = self.value # Do something with value def post(self, request, *args, **kwargs): value = self.value # Do something with value I got an idea while writing this question, which is to define a method that will do what I need, then calling this method in my other methods. class DataView(ContextMixin, UpdateView): def get_value(self): self.pk = self.kwargs['script_id'] ... self.value = ... def get(self, request, *args, **kwargs): self.get_value() value = self.value # Do something with value def post(self, request, *args, **kwargs): self.get_value() value = self.value # Do something with value However, I don't know if there's another way, which is why I still wanna ask my question. Hope this was … -
How to get id of ENUM object in views.py django
I'm writing first django project and I need create a view for my model. I try to write get method, and it should return me json, where there is the id of level field (not name and not value, I need id) from enum import Enum class Level(Enum): A1 = 'Beginner' A2 = 'Elementary' B1 = 'Intermediate' B2 = 'Upper-Intermediate' C1 = 'Advanced' C2 = 'Proficiency' class Theme(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) level = models.CharField(max_length=30, choices=[(lev.name, lev.value) for lev in Level], blank=True, null=True) How to get id of enum object in views.py: class ThemeView(View): def get(self, request): qs = Theme.objects.all() items_data = [] for item in qs: items_data.append({ 'id': item.id, 'category': item.category.id, 'level': item.level.id, # here I need id object, but it's doesn't work 'name': item.title, }) data = { 'items': items_data, } return JsonResponse(data) -
Displaying recently used apps in django
i have 10 applications and one project in django. every application name and description and url is stored in database now my task is to show recently used apps based on user basis is there any possibility to show recently used apps when user used particular application/s we need to get the history and diplay the names if need any change in models.py or suggesting to create new database is ok with me -
pyest does not detect fixtures in separate folder
I have a Django application and am writing tests using pytest and pytest fixtures. All the tests are in their respective Django apps but I wrote the fixtures in a different folder as a module. Project structure: Proj. | +apps: - core -tests -test_core.py - users -tests test_user.py | +fixtures: - __init__.py - core.py - users.py | +conftest.py I have the different fixtures in their separate files which correspond with the app names they are to be used. Am having problems with pytest detecting the fixtures I have tried creating a conftest.py file in the root of the project and importing the fixtures file as a plugin. conftest.py > pytest_plugins = [ "apps.fixtures",] I have also tried removing the coftest.py file and placing the fixtures file in the apps folder and still pytest does not detect the fixtures. Any help here would be helpful. -
how include links from main urls.py file to model urls.py file?
I am trying to include links from a 'Post/urls.py' file, to 'blog/urls.py' (admin file) but I get an error message Do you hope to help solve this problem? #Post/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.all_posts, name='all_posts'), url(r'^(?P<id>\d+)$',views.post, name='post'), ] blog/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('Post.urls', namespace ='blog')), ] Error msg: from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (C:\xampp\htdocs\django\blog\lib\site-packages\django\conf\urls_init_.py) -
I have problem with Django + Docker + Celery
I am try to learn some deploy moments. I tried to deploy my django application on my linux debian server using Django+ Nginx + PGSQL + Celery, wrapping it all in Docker containers. But when I run django and celery separately (via build: .), I encounter the problem that celery stalks returns, for example, "no such column account_user" when accessing the database, although I have users. If you deploy django via "build: .", and specify "image: celery" to celery, then the problem arises that celery does not see django (it usually returns either "no module named "django" or "no module named "celery_app"). I don't know how clear my question is, but is there any way to deploy Django + Celery so that everything works and celery has access to the database and to the Django environment? docker-compose.yml version: "3.8" services: django: build: . restart: on-failure command: bash -c "python manage.py collectstatic --noinput && python manage.py migrate && gunicorn angelina.wsgi:application --bind 0.0.0.0:8000" volumes: - static:/home/web/home_page/static - .:/home/web/ ports: - "8000:8000" env_file: - ./.env.dev depends_on: - db - redis db: image: postgres:13 restart: on-failure volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=dalorevacation - POSTGRES_PASSWORD=*UHBytr7 - POSTGRES_DB=db nginx: image: nginx restart: on-failure build: ./deploy/nginx ports: … -
share query results in django among logged in users
I have a table linked and getting data from Zapier. The records come 200rows per minute. Logged-in users are supposed to be picking these data and working on them. The problem is that there has been some confusion as to know which record has been worked on and which one has not been worked on. I have built a table to help show records which have been worked on by ticking the Treated tab Table structure. I hope I can divide the records equally amongst the logged-in Users so as not to underwhelm or overwhelm any of the users. -
Django Model become huge
In my project few models has many fields like more than 25. Like i have a model name PeriodOfStay. and it field like date_of_entry i94_number port_of_entry city ....etc (please check the image for all field) also it has many boolean fields . in one form user can multiple options. so i am confused should i put all the fields in one model. Is it best practice. I don't want split one model to more and use OneToOne Relation cause in that case i need to break up many models cause most of the models in my project are like this also i need to send all data at once in a single request. I just need to save data and show data to user. in some case i need to search by some field . Like in this form i need to search by i94_number. Is using JsonField is ok for this problem cause i need to search & filter in some case. I appreciate any help. Advance Thanks For Help. -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'snp.routing'
ASGI_APPLICATION = 'snp.routing.application' routing.py: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter ({ 'websocket': AuthMiddlewareStack( URLRouter ( chat.routing.websocket_urlpatterns ) ) }) i'm having this error while imporing ASGI_APPLICATION, how can i fix it raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'snp.routing' -
Mocking time.sleep will cause the test to fail
I wrote this test, but in order not to delay the test, I mock the time.sleep and the test will encounter an fail. from unittest.mock import patch @patch('time.sleep', return_value=None) def test_wait_for_db(self): """Test waiting for db""" with patch('django.utils.connection.BaseConnectionHandler.__getitem__') as gi: gi.side_effect = [OperationalError] * 5 + [True] call_command('wait_for_db') self.assertEqual(gi.call_count, 6) By commenting on this second line(@patch), the program will run properly. -
Django and and Nginx not adding all domain name
I have a project with Django running on a Linux machine. The project was working very well. but after we changed the domain name from "http://myservername:port/" to "https://myservername/projectname/", it doesn't work anymore. If I click on the URL, I am redirected to "https://myservername/" but not to "https://myservername/projectname/", which gives me a 404 error. And if add manually the "projectname" into the URL in the browser, it is working fine. my URLs in Django look like this: urlpatterns = [ path('', include('pages.urls')), path('dashboards/', include('dashboards.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), path('admin/', admin.site.urls), ] # and pages url: urlpatterns = [ path('', views.index, name='index-pages'), # re_path(r'^culture-crawler/$', views.index, name='home'), # # path('culture-crawler/register/', views.register_page, name='register'), re_path(r'^login/$', views.login_page, name='login'), re_path(r'^logout/$', views.logout_user, name='logout'), ] # and dashboards urlpatterns = [ path('dashboard/', views.dashboard, name='dashboard') ] The Nginx file: upstream culture_crawler_app { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/webapps/culturecrawler/run/gunicorn.sock fail_timeout=0; } server { listen 127.0.0.1:100; server_name hammbwdsc02; client_max_body_size 4G; access_log /home/webapps/culturecrawler/logs/nginx-access.log; error_log /home/webapps/culturecrawler/logs/nginx-error.log; location /static/ { alias /home/webapps/culturecrawler/culture_crawler/static/; } location /media/ { alias /home/webapps/culturecrawler/culture_crawler/media/; } location / { # an HTTP header important enough to … -
Django still shows home page rather than the page that I want
I am learning django now for the first time and I am stuck a bit at start please help me out here. I created new project through django and created a blog page inside my project through terminal(cmd). Directory was also formed for both in my pc. When I runserver, localhost also shows "Installed worked Successfully"(attached). Now for 2nd step was to include blog page in there. So I have made changes in "views.py", "urls.py" in both Project and blog directory(attached). Now as of the tutorial I am following, now when I run my local host, it should not show same "Installed Successfully" page but rather should give Error 404 of page not found(attached). And in my address bar when I give "localhost:8000/blog", then it should show blog page. But for me it still shows "Installed Successfully" page. I tried this twice seperately, maybe I missed something but can't figure out. Thanks. -
Redirect hostname/endpoint to api.hostname/endpoint in django
I have my api built with this pattern: api.hostname/endpoint. However there is a plugin to my app that uses hostname/endpoint pattern. I would like to solve it on the backend side by adding redirection to api.hostname/endpoint. I tried to experiment with adding urls or paths to urlpatterns, but it didn't help me. How can I achieve it? Any ideas? Regards, Maciej. -
How to create in gjango self with DEFAULT_AUTO_FIELD uuid4?
DEFAULT_AUTO_FIELD = 'core.custom_auto_field.UID4AutoField' from django.db.models.fields import AutoFieldMixin, UUIDField from uuid import uuid4 class UID4AutoField(AutoFieldMixin, UUIDField): def get_internal_type(self): return 'UID4AutoField' def rel_db_type(self, connection): return UUIDField().db_type(connection=connection) -
How to change language in django?
i'm making a form in django and i would like to be able to change the language of the errors to spanish, for example, if i enter a wrong date, instead of "Enter a valid date." that says "Ingrese una fecha valida" but when i make the modifications, it's still the same, is there something i'm doing wrong? PD: i'm noob in python SETTING.PY LANGUAGE_CODE = 'es' TIME_ZONE = 'America/Argentina/Buenos_Aires' USE_I18N = True USE_L10N = True USE_TZ = True I would really appreciate the help -
`AccessDenied` on files uploaded to private S3 bucket with Cloudfront
I'm an AWS noob setting up a hobby site using Django and Wagtail CMS. I followed this guide to connecting an S3 bucket with django-storages. I then added Cloudfront to my bucket, and everything works as expected: I'm able to upload images from Wagtail to my S3 bucket and can see that they are served through Cloudfront. However, the guide I followed turned off Block all public access on this bucket, which I've read is bad security practice. For that reason, I would like to set up Cloudfront so that my bucket is private and my Django media files are only accessible through Cloudfront, not S3. I tried turning Block all public access back on, and adding this bucket policy: "Sid": "2", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity XXXXXXXXXXXXXX" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-s3-bucket/*" The problem I'm encountering is that when I have Block all public access turned on, I receive AccessDenied messages on any new images I upload from Wagtail to S3. I know the new images are being uploaded and stored in my bucket because I can see them when I browse the objects in my account. But the only images I can view are … -
Django starts primary key from 1 when there is already data in database
I have a pg database created by migrate with Django, all the tables have been created successfully and are empty at the start. Now I have to fill one of the tables from a database backup created by pgdump. This database has a table transactions which contains data (consider no FK, and the schema of the table is same), so using pgrestore, I restored only that transaction table from the database backup. Everything restored and data is shown in the Django web app as well. But Now when I create a new entry in that table using django web app, the django starts assigning the primary key from 1 to the newly created entry, but as the table is restored from a database backup, that id already exists, if I try again, django will try to assign PK 2, then 3 and so on. But those transactions have already been restored from DB backup How to tell Django the last transaction id so that it can start assigning from there? -
.objects.all() returns nothing
its my first time to ask hope I can find solution to my problem. Am trying to display the courses in an html page using objects.all() but it returns nothing and the page remain empty, even though records do exist in the database. I tried the same method for other pages and it worked, idk what am doing wrong here :( in view.py def viewCourse(request): corlist = Course.objects.all() #print(muffin) #course.count() context = {'corlist':corlist} return render(request, 'LogInApp/ViewCourse.html', context) in model.py class Course(models.Model): COURSES = ( ('Data Structure','Data Structure'), ('Computer Network','Computer Network'), ('Web Design','Web Design'), ('Internet of Things','Internet of Things'), ('Artificial Intelligence','Artificial Intelligence'), ('Artificial Intelligence-Tut', 'Artificial Intelligence-Tut'), ) course_id = models.AutoField(primary_key=True) course_name = models.CharField(max_length=100, null=True, choices= COURSES) fk_lecturer_id = models.OneToOneField(Lecturer, on_delete=models.CASCADE) # foreign key date = models.DateField(max_length=20, null=True) time = models.TimeField(max_length=20, null=True) def __str__(self): return '{} {}'.format(self.course_id, self.course_name) @property def lecturerid(self): return self.fk_lecturer_id.lecturerid in ViewCourse.html <table border="1" class="table"> <tr> <th>Course ID</th> <th>Course Name</th> <th>Course Lecturer</th> <th>Date</th> <th>Time</th> <th width="100px"> </th> </tr> {% for co in corlist %} <tr> <td> {{ co.course_id }} </td> <td> {{ co.course_name }} </td> <td> {{ co.fk_lecturer_id }} </td> <td> {{ co.date }} </td> <td> {{ co.time }} </td> </tr> {% endfor %} </table> -
Is there a way to not display my model in the template?
I want to know if it is possible not to show/load my Product model when viewing a template. Instead, I want to display my model on click a button that filters the results before displaying them. I have more than 30,000 records in my Product model and that is why I don't want them to show/load when viewing my template, I know that the paginate_by = '100' method exists, but I find it more useful to filter the records before displaying them Note: I already have the function and class to filter my Product model records class barcodeview(ListView): template_name = "barcode/table.html" paginate_by = '500' model= Product context_object_name = 'product' # Queryset for filtering product model def get_queryset(self): queryset = Product.objects.barcode_filter( filtr = self.request.GET.get("filtr", ''), ) return queryset -
How to use a credential file without pushing it to repository
I am building a Django web app that is deployed on GCP (google cloud platform). I need to use the google cloud storage bucket to store files generated from the app, So I added the code to settings.py os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.join(BASE_DIR, 'credential.json') In the code, credential.json is referred to. Currently, I put the credential file in the project directory on my computer and it works fine. But now I need to push the project to a public repository for project handoff and I can’t push the credential file because it contains the private key to the cloud storage bucket. What should I do to make the program run normally without pushing the credential file to the repository or the file being accessible by other people? -
Auth0 token is not RS256
I have created an Auth0 application and then used it in my ReactJS project using the @auth0/auth0-react module. Post logging in, I am trying to get the access token by using the getAccessTokenSilently() function. I have observed that the obtained token has empty payload and the "alg" is "dir" instead of "RS256". How can I resolve this? ReactJS Code: function App() { const { loginWithRedirect, user, isAuthenticated, isLoading, getAccessTokenSilently, } = useAuth0(); useEffect(async () => { if (isAuthenticated && !isEmpty(user)) { let token = await getAccessTokenSilently({ audience: process.env.AUTH0_AUDIENCE, }); console.log('token', token); } }, [isAuthenticated, user]); if (!isLoading && !isAuthenticated) { return loginWithRedirect(); } if (isLoading || !apolloClient) { return ( <> <p>Loading...</p> </> ); } return ( <> <p>APP</p> </> ); } function AppWrapper() { return ( <Provider store={store}> <BrowserRouter> <Auth0Provider domain={process.env.AUTH0_DOMAIN} clientId={process.env.AUTH0_CLIENT_ID} redirectUri={window.location.origin} audience={process.env.AUTH0_AUDIENCE} > <Alerts /> <App /> </Auth0Provider> </BrowserRouter> </Provider> ); } ReactDOM.render(<AppWrapper />, document.getElementById("root")); Sample JWT: eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9ldmVyeXRoaW5nLWFwcC1kZXYudXMuYXV0aDAuY29tLyJ9..2g3_tIZTJwJrV9Jd.oiSiOjaiyts4iUCQkv0akvlBjTVdJ5UnCpu0r6sacsAE1Jnz2VEMVr9oTMssfjkMwOdmiWwsWc3t9y014VdvsXsf2U67i-mTWgK93J2vEMh_TxTUICIkSdG4Wp01E4bPiNqv_1qbaOvpIff60qSKB0YYc4o5OdllrTLvn0ZcIIOwSwRdY7aGrWrQc3ix85NfR25NiQZHixeD7qSk6hvJj5YAag9VBfAV4YSeehklsYkOlrdUtLFTypQENBfVwFTBRTJipqtW5vQ6Y1z8uWt0OnL1t3QRrgX7odZMUTqWjQOPbDJkoaiiv17nqJknBbvFydjTgbpq_ubUgcanJ3M.Pj0IqHAeZvUqptPCdu9vOg Screenshot from jwt.io: Screenshot of Auth0 application settings: I intend use this access token when making backend API calls. I am using Django backend and I have followed this article to setup the backend. As per the code snippet from that article, I should be getting kid in the … -
I coded to redirect to login page when requesting home page. Whenever I tried to click home from other page it leads to login even after logged in
view def index(request): response=redirect('/login') return response login.views from django.shortcuts import render, redirect from register.models import reg def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = reg.objects.filter(username=username, password=password) if user: user_details = reg.objects.get(username=username, password=password) id = user_details.id username_user = user_details.username request.session['id'] = id request.session['username'] = username_user return render(request,'index.html') else: return render(request,'register.html') else: return render(request, 'login.html') -
Using 2byte filename for StreamingHttpResponse attachfile
def iter_csv(rows, pseudo_buffer): yield pseudo_buffer.write(codecs.BOM_UTF8) writer = csv.writer(pseudo_buffer) for row in rows: yield writer.writerow(row) def download_csv(queryset=None, filename=None, column_names=None): writer = csv.writer(Echo()) rows = [column_names] rows.extend(queryset) filename = "テスト.csv" # this setting is ignored. filename = "test.csv" # it works return StreamingHttpResponse( (iter_csv(rows, Echo())), #(writer.writerow(row) for row in rows), content_type='text/csv', headers={ 'Content-Disposition': f'attachment; filename={filename}'} ) I want to use 2byte character for filename. When I set filename = "test.csv", download filename is test.csv When I set filename = "テスト.csv", somehow this setting is ignored and download filename is {urlname}.csv -
Unable to make API request
I'm trying to test an API from django app to ensure it is working but I'm totally lost on how to make the API request. I have spent several days trying to figure it out myself but it is obvious that I need help because I keep HAVING ERROR such as TypeError: list indices must be integers or slices, not str. It is an API to create order of selected item. Here is the code: views.py def create_order(request): user = request.user data = request.data orderItems = data['orderItems'] if orderItems and len(orderItems) == 0: return Response({'detail': 'Order item was not provided'}, status=status.HTTP_400_BAD_REQUEST) else: # (1) Create order order = Order.objects.create( user=user, paymentMethod=data['paymentMethod'], #totalPrice=data['totalPrice'] ) # (2) Create shipping address shipping = ShippingAddress.objects.create( order=order, address=data['shippingAddress']['address'], city=data['shippingAddress']['city'], postalCode=data['shippingAddress']['postalCode'], country=data['shippingAddress']['country'], ) # (3) Create order items adn set order to orderItem relationship for i in orderItems: product = Product.objects.get(id=i['product']) item = OrderItem.objects.create( product=product, order=order, name=product.name, qty=i['qty'], price=i['price'], image=product.image.url, ) # (4) Update stock product.countInStock -= item.qty product.save() serializer = OrderSerializer(order, many=False) return Response(serializer.data) How do I represent the Above django view.py in json format to test. Where the issue I'm having is that diffent steps are involved in the view.py file above. Here is …