Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app : "URL not found" error when i run my server
I have begun to learn web dev using django. I my first app I am not able to see my web page when I run the command : python manage.py runserver Here is my code snippet: #view.py(in app folder) from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello World!") #urls.py (in project folder) from django.contrib import admin from django.urls import path from first_app import views urlpatterns = [ path('^$',views.index,name='index'), path('^admin/', admin.site.urls), ] I have created the environment and activated it also. Here's the output on my web page screen. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order: ^$ [name='index'] ^admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
while submiting login button nothing happens in my webpage
my HTML is <form method="POST" action="{% url 'lawyerdash' %}"> {% csrf_token %} username<input type="text" name="userl"><br> password<input type="password" name="passl" ><br> <input type="button" value="sign in" > my view is def lawyerdash(request): if request.method == 'POST': if Lawyer.objects.filter(username=request.POST['username'], password=request.POST['password']).exists(): lawyer = Lawyer.objects.get(username=request.POST['username'], password=request.POST['password']) return render(request, 'lawyerpage.html', {'lawyer': lawyer}) else: return HttpResponse("<h1>Not found.........</h2>") my URL is url(r'^lawyerdash/$',views.lawyerdash,name="lawyerdash"), after clicking sign in it should go to the following page(lawyerpage.html) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>welcome {{lawyer.name}}</h1> </body> </html> -
Django using MinLengthValidator removes zero in begin of text
i want to validate national_code, it is exactly 10 digit and maybe starts with zero, like 0********* or 00********, so i wrote in my model: national_code = models.CharField(max_length=11, validators=[MinLengthValidator(10)]) but when storing 0012345678, it raises error telling length should be 10 and it is 8! why? -
How to use template from project in another app?
I'm thinking in organizing all my templates in inside the project: scolarte. But I need to call it from another app. The view is called but getting error: TemplateDoesNotExist at /cuentas/ingreso/ scolarte/templates/scolarte/registration/signup.html I even tried to put the full path to the template in project folder: roles/views.py: class SignUpView(TemplateView): template_name = 'scolarte/templates/scolarte/registration/signup.html' roles/urls.py: from django.urls import include, path from .views import SignUpView, SellerSignUpView, ClientSignUpView urlpatterns = [ path('ingreso/', SignUpView.as_view(), name='signup'), ] scolarte/urls.py urlpatterns = [ path('', include('core.urls')), path('cuentas/', include('roles.urls')), path('admin/', admin.site.urls), ] My app is orgnized like this: roles |_migrations |_templates ... |_urls.py |_views.py scolarte #project name |_templates |_scolarte |_registration |_signup.html |_setting.py |_urls.py -
Reading DICOM file in JavaScript
Can someone please give me examples on how to read DICOM file in JavaScript? I want to retrieve data like instanceNumber, pixelArray, UID etc. I want to retrieve this data and especially the pixel array (i.e. the image) to send it to a Django server to store it and undergo some processing. Thanks a bunch. -
Django with DRF and OAUTH2.0
I'm trying development a system with Django and Django Rest Framework, since i started i found out two problem, first for authentication second for permissions, i want use OAuth2.0 to make it possible, and django-oauth-toolkit. Now, i wanna know how i authenticate a user and give the right for his, if he is admin or normal user? -
How to change value ID to model attribute in Queryset
Django QuerySets return the PK of the associated objects but I need the attribute name. For example Sitting.objects.filter(complete=True).values('user') would return a QuerySet like: <QuerySet[{'user':2}, {'user':3}]>. How do I easily convert the 2 to user.get_full_name() or such? To give an idea of what I was trying: tests_taken = Sitting.objects.filter(complete=True).values('user') for test in tests_taken: try: tests_taken[test]['user'] = Employee.objects.get(pk=test['user']) except TypeError: pass print(tests_taken) It just seems really inefficient... -
django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
Please help! File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" My settings are local all all @authmethodlocal@ It's like I can't get into my user "postgres" or "ladonna". I was running python3 manage.py runserver local host, 5432, etc are default -
i am creating a post method in django and written a def in vie but it is not printing in consele. i think prog is not able to get in IF condition
def post1(request): form = EmployeeForm() if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): eid = form.cleaned_data['eid'] ename = form.cleaned_data['ename'] ecity = form.cleaned_data['ecity'] employer = form.cleaned_data['employer'] print(eid, ename, ecity, employer)## it is not printing on the cnsole. return render(request, "app1/post1.html", {'form' : form}) Is there any mistake.this is the post method i am creating and there is a employee form and what i want if i filll data in the field it will show in the command prompt. -
Why Form Assets (the Media class) does not render in template?
I want to add js for my widget: class GenPasswordInput(forms.widgets.PasswordInput): class Media: js = ('my_auth/js/random_password.js',) class CustomConfirmedUserCreationForm(forms.ModelForm): password1 = forms.CharField( widget=GenPasswordInput, help_text=render_gen_password_html() ) password2 = forms.CharField(label="Confirm password", widget=forms.PasswordInput) class Meta: model = CustomConfirmedUser fields = ('username', 'email',) But on page no any script tag with this js file if i use just {{ form }} or {[ form.as_p }}, so i need manually add in template {{ form.media }} to render script tag. -
Get current time zone (Django)
I currently have TIME_ZONE = 'UTC' set in my settings. In my DebitCard model expiration_date field, I store the date as a unixtime. For instance 01/10/2020 @11:25pm (UTC) is 1578698708. The problem is: Let's say the expiration_date is January 15th, 2010 at 00:00 or (1263513600). I want to block users from making a transaction when the current time is greater than the expiration_date. However, if the user is in LA (8 hours before UTC), the current_time will be off by 8 hours. Question: How do I grab the user's current time wherever they are? Because I want to grab this time and compare it to their debit card expiration_date -
templatetags vs context in django
after working with django, I see that there seems to be 2 ways of passing data to the html page. Like if I had a model called Products, I can either do views.py context = { 'products' : Products.objects.all() } return render(request, 'products/product_page.html', context) product_page.html {% for post in posts %} //do stuff with {{post}} {% endfor %} or I can do product_tags.py register = template.Library() @register.simple_tag def get_Products(): return Products.objects.all() product_page.html {% load product_tags %} {% get_Products as elections %} //do stuff with {{elections}} Is one way better than another? -
Save .docx file django for specific user
I'm creating a docx file with user input in django. For now when the submit button is clicked the download link generates and users can download the file. However I want to save the file in file store and create a template where the user can see all the docx files (or a hyperlink) that he has created in the past. "Somewhat like a database" views.py f = io.BytesIO() worddocument.save(f) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename = quicktimetable.docx' worddocument.save(response) return response How can I save the files which are generated and show all the files related to that user on a different a template. I have a FileField in my models.py but no idea how to make use of it. I got a suggestion to regenerate file whenever users ask for it but I have no idea about that as well. -
FileField Django 1.6 Back-slash in the name is being replaced by forward-slash when try to read()
I have a Django App (1.6), I'm using a model called Books and this has a field called data which is a FileField that has the upload_to parameter pointing to an S3 bucket directory. I have a Book item with this path inside data field media_books/today/MyFirst\Book.pdf the file name should be MyFirst\Book.pdf so the S3 url should be called like this: 'https://bookstore.s3.amazonaws.com/media_books/today/MyFirst%5CBook.pdf' but the code returns me this: >>> book.data.name u'media_books/today/MyFirst\Book.pdf' >>> part.data._get_url() 'https://bookstore.s3.amazonaws.com/media_books/today/MyFirst/Book.pdf' so that last URL does not match with the S3 URL so this is what the code returns to me trying to fetch it: >>>book.data.read() raise IOError('File does not exist: %s' % name) IOError: File does not exist: /media_books/today/MyFirst/Book.pdf I was thinking maybe to create my own FileField but wondering what method should i overwrite to fix the problem? Another idea is creating a Script that fix all the non-quoted names in the DB and creating a solution for feature entries. anyone has another idea? -
Refresh ALL VALUES model from database
I update a table called "transaction_transactionprofiling" linked to a model called "transactionprofiling", according to new values/query that can vary. When the values are updated "transaction_transactionprofiling" is well updated if I print the values on my cmd everything looks fine, but the model doesn't change when I look on the html template. I had a look on the solutions proposed but it always take into consideration only 1 added value. As I completely change my table according to the values selected by the user, I do not find how to do that! thank you for your help @csrf_exempt def register(request): type_list=request.POST.get('selected_type').split("&") from_date=request.POST.get('start_date').replace("&","") to_date=request.POST.get('end_date').replace("&","") amount=request.POST.get('amount') filtertype.objects.all().delete() n = 0 for item in type_list: n = n + 1 add = filtertype(id=n, transaction_type=item) add.save() filterdate.objects.all().delete() add = filterdate(id=3, start_date=from_date,end_date=to_date) add.save() filteramount.objects.all().delete() add = filteramount(id=3, amount=amount) add.save() print(type_list,from_date,to_date,amount) os.system('python transaction\querytable.py') #update de table in the database profiling = transactionprofiling.objects.all() #send values to html templates tmpl = loader.get_template("table/index.html") cont = {'profiling': profiling} return HttpResponse(tmpl.render(cont)) -
Heroku Deployment Error 503 for Django Blog App
I am trying to deploy my django app on heroku and yet i keep get a 503 error, my log errors: 2020-01-10T19:59:23.904041+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=django-blogapp.herokuapp.com request_id=4b76e716-46cf-40c7-975c-b8626285da19 fwd="207.23.170.92" dyno= connect= service= status=503 bytes= protocol=https 2020-01-10T19:59:24.611790+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=django-blogapp.herokuapp.com request_id=1669e416-0224-4b8d-a14a-bff26314ca63 fwd="207.23.170.92" dyno= connect= service= status=503 bytes= protocol=https I have migrated my code using heroku run python3 manage.py migrate, and it worked properly This is what my settings.py file contains: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['https://django-blogapp.herokuapp.com/'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES … -
TemplateSyntaxError when adding dynamic argument in django
I have a small problem with dynamic arguments. I need to change innerHTML of one div according to the name of category clicked and replace the element in object.element with it. The below solution generates the mentioned issue: Could not parse the remainder: '%s' from 'object.%s' $(function(){ $(".navbar-nav li a").each(function(){ $(this).click(function(){ let category_name = this.innerText.toLowerCase() let final = "{{object.%s}}", category_name change(final) }) }) }); function change(category){ $('.content-movie').children().html(category) } -
Adding custom functionality to django router methods
I'm trying to add custom functionality to django router methods. This is my router that exposes the standard methods on an user. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [BasePermission] I'm validating the user using serializer validation methods. class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) MOBILE_ERROR = 'Mobile number should be 10 digits long and only contain numbers.' EMAIL_ERROR = 'Incorrect email format' USERNAME_ERROR = 'Username must be at least 6 characters long and contain only letters and numbers.' class Meta: model = User fields = '__all__' def validate_mobile(self, value): regexp = re.compile(r'^[0-9]{10}$') if regexp.search(value): return value raise serializers.ValidationError(self.MOBILE_ERROR) def validate_email(self, value): if validate_email(value): return value raise serializers.ValidationError(self.EMAIL_ERROR) def validate_username(self, value): regexp = re.compile(r'^[a-zA-Z0-9]{6,}$') if regexp.search(value): return value raise serializers.ValidationError(self.USERNAME_ERROR) And this is my route. router = DefaultRouter(trailing_slash=False) router.register(r'user', UserViewSet), urlpatterns = router.urls I want to add a method send_activation_code if the user is created successfully. How do I do this? -
python3 manage.py runserver is not returning anything
I'm trying to start a server for django on my local machine using win10 CMD. python3 manage.py runserver [Enter] C:\Users\dog\Desktop\wordcount> [output] I get no error or anything, it just returns my directory to C:\Users\dog\Desktop\wordcount> I'v cheeked DIR and everything seems to be in place the files and django is installed. -
Is there a way to get a referring view without HTTP_REFERER?
I am currently using the following function to get a referring view: def get_referer_view(request, default=None): referer = request.META.get('HTTP_REFERER') if not referer: return default # remove the protocol and split the url at the slashes referer = re.sub('^https?:\/\/', '', referer).split('/') if referer[0] != request.META.get('SERVER_NAME'): return default # add the slash at the relative path's view and finished referer = u'/' + u'/'.join(referer[1:]) return referer If I redirected the view as a result of programmatic logic, e.g... return HttpResponseRedirect('dashboard') ...is there a way to get the referring view without using HTTP_REFERER so that I can use that variable in the redirected view? This is not always set in the headers of the browser. -
GET /static/css/base.css HTTP/1.1" 404 1660 from Django for Beginners
Hi there I'm extremely new to programming/python/django in general and I'm following the django for beginners book and the part where we add in CSS has got me super confused because I'm getting this error "GET /static/css/base.css HTTP/1.1" 404 1660. I've copied the code from the book 1 to 1 and can't get it to work. Here's the relevant settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] Here's the base.html I'm adding the css to {% load static %} <html> <head> <title>Django blog</title> <link href="{% static 'css/base.css' %}" rel="stylesheet"> </head> ... And here's the directory info I saw people asking about this in other questions C:. ├───blog │ └───migrations ├───blog_project ├───static │ └───css └───templates -
Django Okta Integration
I have a few questions about integrating Okta with Django. I've noticed that it is quite easy to setup authorization and authentication in Flask Applications by using OpenID Connect (a library already defined in Flask) and Okta. 1)Is there something similar in Django? (i.e. an OpenID Library built in or easily added) 2) Are there any other ways to integrate Okta with Django besides using OpenID? I've looked at all of the available get github repositories and post regarding this and they're either: outdated or not working correctly. -
CSS static file is not loading in Django
I am learning Django and i tried to implement a blog app . i am getting an error while using the static files inside project.i know, There are lot of questions with the same title. But i tried every way, still its not rendering the css file on the browser. Folder structure: firstBlog is the project name. blog is the app inside firstBlog. allstaticfiles is the STATIC_ROOT location. static is the folder for stroing the static contents. templates for storing the respective app's templates. Here are some of my codes : settings.py STATIC_URL = '/static_files/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/Django/projects/project1/project1/firstBlog/static', ] #print(os.path.exists(os.path.join(BASE_DIR,'static'))) ----------------TRUE STATIC_ROOT=os.path.join(BASE_DIR, "allstaticfiles") Base.html i have used the {% load static %} and for laoding the css i have set the href attribute as below. <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' % }"> Few things to consider : when i am viewing my page on browser, its giving me error on console which is probably due to some path issue. 127.0.0.1/:1 Refused to apply style from 'http://127.0.0.1:8000/blog/%7B%%20static%20'blog/main.css'%20%%20%7D' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. When i am viewing the style from the localhost link i.e, http://127.0.0.1:8000/blog/static_files/blog/main.css, … -
Prevent repeated button clicks in a web page
I am currently building a Django application and there are two functionalities I have implemented so far. 1) Submit user data in a form 2) Read data from the google sheet and display it on the web page. there is a refresh button on this page when clicked the data in the DB gets updated. Issue:- When the user clicks the submit button multiple times lets say 5 times, the same data gets inserted 5 times which is a huge problem. and in the case of the refresh button when clicked many times, I get an error like "duplicate key value violates unique constraint " So, please suggest me a way to make the button not perform multiple times to prevent duplication and handle any corner cases. -
Create related model with Djoser
I am trying to override default user creation in Django. I am using Django Rest Framework and Djoser. I found very good tip for implementing it here: https://stackoverflow.com/a/49096275/9123009 but I have custom profile model, called: Userprofile that has OneToOneField relation to my custom User model. Here is my serializer: class UserRegistrationSerializer(serializers.ModelSerializer): usr_profile = UserprofileSerializer() email = serializers.CharField() password = serializers.CharField(write_only=True, style={'input_type': 'password'}) class Meta: model = get_user_model() fields = ('email', 'password', 'usr_profile') When I try to make following POST request to /auth/users/ endopoint: { "email": "adnan@test115.se", "password": "xxxxxx", usr_profile: { "first_name": "adnan", "last_name": "erkoc", "cell_no": "23233" }, } I keep getting an error that User.profile has to be Userprofile instance.