Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Docker container Django not connecting to postgresql
I am having trouble starting up the django app. It seems to freeze when it prints out "System check identified 6 issues (0 silenced)." I believe this is because django is not connected to the postgresql database. I am really unsure of what the problem could be because it was working fine a year ago, and when I am starting it up now it is broken. Here is the output for postgresql from the docker container log /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/* 2022-06-13 03:35:26.151 UTC [48] LOG: received fast shutdown request waiting for server to shut down....2022-06-13 03:35:26.155 UTC [48] LOG: aborting any active transactions 2022-06-13 03:35:26.156 UTC [48] LOG: background worker "logical replication launcher" (PID 55) exited with exit code 1 2022-06-13 03:35:26.156 UTC [50] LOG: shutting down 2022-06-13 03:35:26.204 UTC [48] LOG: database system is shut down done server stopped PostgreSQL init process complete; ready for start up. initdb: warning: enabling "trust" authentication for local connections You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb. 2022-06-13 03:35:26.273 UTC [1] LOG: starting PostgreSQL 14.3 (Debian 14.3-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit 2022-06-13 03:35:26.273 … -
How to style model form in django with CSS?
I have been using simple forms in Django since I started with python and now I've switched over to model forms, right now I'm wondering how to style the form. I tried to use the widgets code but it is behaving a little funny, If I understand correctly the widgets are to style the form itself (such as input fields) and I can use regular html/css styling on any other elements I have? My desired Is this correct? Here is my code incase there are errors: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css/tripadd.css' %}"> <title>Document</title> </head> <body> <!-- <div class="form-container"> <h4>Add a Trip</h4> <form action="/createTrip" method="post" class="reg-form"> {% csrf_token %} <p><input class="field" type="text" name="city" placeholder="City" id=""></p> <p><input class="field" type="text" name="country" placeholder="Country" id=""></p> <p><textarea name="description" id="" cols="30" rows="10"></textarea></p> <p><input class="field" type="file" name="photo" placeholder="Photo" id=""></p> <input class="form-btn" type="submit" value="submit"> </form> </div> --> {% block content %} <div class="trip-form"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit">submit</button> </form> </div> {% endblock %} </body> </html> @import url('https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800,900&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body{ display: flex; justify-content: center; align-items: center; } … -
Python Django Admin editable field
Is there any way to edit a field in models.py page by entering to admin page without put that field in list_diplay=[] ? -
How do I specify the Django view action decorator for an endpoint with multiple parameters?
For the view and endpoint below with multiple parameters, how should url_path be specified for the action decorator? urls.py: router.register('utils', views.TableColumnViewSet, basename='TableColumn') views.py: @action(detail=False, url_path=r'???') def table_meta(self, request, catalog=None, schema=None, table=None) -
CSS Not Showing Up in Django with NGINX and uWSGI
This is my first real Django project and I am trying to configure it for production using NGINX and uWSGI. It is running on a Digital Ocean Ubuntu server. Everything is set up and working besides serving static CSS files. The strange thing about this is that its serving static images and JavaScript files fine, the only thing that isn't being served is the CSS. This is what my site configuration file for NGINX looks like ('nebula' is the Ubuntu User and the name of the Django project): # configuration of the server server { server_name example.com www.example.com; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/nebula/nebula/media; } location /static { alias /home/nebula/nebula/assets; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/nebula/nebula/uwsgi_params; } } This is what my Settings.py file looks like: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/assets/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, "assets/") STATICFILES_DIRS = ( os.path.join(BASE_DIR,'media/'),) This is what my base directory looks like (assets and static are the same, I duplicated it in an attempt to solve the issue): assets demo.py media nebula.sock static … -
Should I use Comand Prompt or Vs Code terminal for installing modules, running projects ...etc?
I've seen many videos using Comand Prompt to start with a project. Why they use it when you can do it in thier respective IDE's terminal ? -
Django models exclude objects which in self referencing many to many relationship
So in short I have this model: class Post(SoftDeleteModel, TimeStampedModel, models.Model): title = models.CharField(max_length=200) body = models.TextField() image = models.ImageField(upload_to="post_images", blank=True) owner = models.ForeignKey(to=get_user_model(), on_delete=models.CASCADE) comments = models.ManyToManyField(to="self", symmetrical=False, blank=True) having each comment as a post of itself, so comments could have comments and so on, And I want to declare a static method that returns posts only such that they are not in the second column (to column) anywhere in the new auto-generated table from the ManyToMany field, like so: @staticmethod def get_posts_only(): return Post.objects.exclude() what should I exclude or if there is a way with the filter method also. Edit: I got this info about ManyToMany Field from the Django website If the ManyToManyField points from and to the same model, the following fields are generated: id: the primary key of the relation. from_id: the id of the instance which points at the model (i.e. the source instance). to_id: the id of the instance to which the relationship points (i.e. the target model instance). https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ManyToManyField:~:text=If%20the%20ManyToManyField,target%20model%20instance).