Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using an external API in Django
I'm trying to use an external API to grab data for my project to show on the template. service.py def get_data(title, url, description, body, datePublished): url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI' params = {"autoCorrect": "true", "pageNumber": "1", "pageSize": "10", "q": "police", "safeSearch": "true" } r = requests.get(url, params=params) data = r.json() article_data = {'data': data['value']} return article_data Then I show it on views.py ... import service class IndexData(TemplateView): def get(self, request): article_data = service.get_data.all() return render(request, 'pages/home.html', article_data) but I'm getting ModuleNotFoundError: No module named 'service' Did i miss something? -
How to build this complex form in Django with multiple models?
How should I build this complex form in Django? In particular, what I would like to accomplish is to be able to send the indented information making clear that it is inside and related to the parent option. In the example, I would like to send the information that the Antivirus within Malware is checked and that Malware - Antivirus has the criticality specified in the dropdown. Malware is from class Theat, Antivirus is from class Control and Malware-Antivirus-High is from class Requirement. And everything while creating a Subcategory. -
Why does my website take so long to load to browser?
So I have added a https to a simple website ( goenigmamusic.com ) built with django and you can only connect to it with a good internet connnection. The ssl certificate was done on aws, as well as the deployment. I have a metro pcs internet connection on my phone, I use it to test my website load time. Whats interesting is that, I can load a website like cartoonnetwork.com with a decent internet connection to my browswer, but goenigmamusic.com can't even load the website to my browswer, but when connected to good wifi? Why? -
Sending user-dependent scheduled emails with celery and django?
I'd like for my web-app to send weekly / monthly emails to the users - how would I limit celery to only send scheduled emails to the users that "opt-in"? I installed django-celery-beat and I can configure a cron job in the admin interface, but not only to specific users -
Getting "Method Not Allowed: /users/update_contact/"
This my javascript function intended to update my database. However, I get two errors: Method Not Allowed: /users/update_contact/" SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data function update_contact (){ url = "{% url 'users:update_contact' %}"; git_profile = prompt("enter git profile name") phone = prompt("enter phone number") email = prompt("enter email address") const contact = { "git_profile" : git_profile, "phone_number" : phone, "email" : email }; var stringify_contact = JSON.stringify(contact); const options = { method: 'POST', body: JSON.parse(stringify_contact), mode: 'same-origin', dataType: 'json', headers : { 'content-Type' : 'application/json', 'X-CSRFToken': csrftoken, } } fetch(url, options) .then(res => res.json()) .then(res => console.log(res)) } -
Django: Display database information to match the form? ValueError: .. didn't return an HttpResponse object. It returned None instead
I am trying to query the database to display results from the form. Once I select the form drop-down fields for my wanted query e.g. Ford C-Max 2019 1.2 Petrol 1500 , from which I coded for now to display results (regardless of Make & Model as I only have one atm) , then instead of showing me the table with matched results I get this error: Request Method: POST Request URL: http://127.0.0.1:8000/data/ Django Version: 3.0.3 Exception Type: ValueError Exception Value: The view app.views.data didn't return an HttpResponse object. It returned None instead. However I do have that result in the database table named ford_cmax (ignore the average & entered columns) average entered year liter fuel mileage 9701 2020-04-08 20:59:45 2019 1.2 Petrol 1500 I did not have this problem before, the table showed all results fine before I did the tweaking for filters. My code: views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import FormView from django.db.models import Q from .models import Average, Query from .forms import QueryForm class QueryMakeModel(FormView): template_name = 'QueryMakeModel.html' success_url = '/data/' form_class = QueryForm def form_valid(self, form): return HttpResponse("Sweet.") def index(request): if request.method == 'POST': FormSite = QueryForm(request.POST) if FormSite.is_valid(): pass … -
Django the fastest way to do Query get list of items in row from table
In my app I need to do fast Query but I don't know which is faster materials = Material.objects.only('name') Or do filter this in view materials = Material.objects.all() And then use for loop to show list of items from 'name' row I think that first is better or there is better way to do this? It cant be done with filter() because it need to show all of fields in this row. -
Pass a file path as a URL parameter in Django
I'm using Django to create a webapp. When a user press on a certain button, it needs to pass a file path as parameter and a string parameter to one of my views. I can't simply use the parameter in the URL since the path contains several '/'. The way I have it setup right now is as follows: parameters.py ''' class FilePathConverter: regex = '^[/]' def to_python(self, value): value=str(value) return value.replace("?", "/") def to_url(self, value): value=str(value) return value.replace("?", "/") urls.py from django.urls import path from . import views from django.contrib import admin from django.views import generic from django.urls import path, register_converter from . import converters, views register_converter(converters.FilePathConverter, 'filepath') urlpatterns = [ path('', views.index, name='webpanel-index'), path('controlserver/<str:server_path>/<str:control>', views.index, name='controlserver'), ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Server from django.contrib.auth.decorators import login_required import subprocess def controlserver(request, server_path, control): if request.POST: subprocess.call(['bash', server_path, control]) return render(request, 'index.html') However, with this method, I get this error: Reverse for 'controlserver' with keyword arguments '{'server_path': 'rien/', 'control': 'start'}' not found. 1 pattern(s) tried: ['controlserver/(?P<server_path>[^/]+)/(?P<control>[^/]+)$'] -
Problems in multiple page form
I created a function for creating Course object.Form works but i don't know how to create Course object here.How to do that? views.py class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) def done(self, form_list, **kwargs): data = {k: v for form in form_list for k, v in form.cleaned_data.items()} instance = Course.objects.create(**data) return render(self.request, 'courses/done.html',{'form_data': [form.cleaned_data for form in form_list],}) urls.py path('create_course/',FormWizardView.as_view([CourseForm1,CourseForm2.CourseForm3,CourseForm4]),name='create_course'), -
I want request.POST[variable name] to be executed only if the variable name exists in the input of template
def sendorder(request): items = MenuModel.objects.all() if request.method == 'POST': for item in items: if request.POST['item'+str(item.id)]: print(request.POST['item'+str(item.id)]) return I have some inputs in templates with name item2,item3 etc etc, but this view counts right from the beginning item1 which gives error as no input with name item1 exists. I want to bypass if no such input name exists. -
Prefech many to many relation for one class instance
I want to limit the queries for a detail view. I want to access multiple many to many fields for one class instance. It seems prefetch_related doesn't work with get. JobInstance = Job.objects.get(pk=id).prefetch_related('cities').prefetch_related('experience_level') -
Django custom paginator fails to catch non integer value
I want to use my own Paginator in view based on ListView. The need for custom Paginator is coming from two user errors I want to catch: too big number and no number. There is no problem in catching the first issue with EmptyPage error. What I have problem with is no number error - e.g. ?page=k From documentation I would assume this can be achieved with PageNotAnInteger, or both with InvalidPage. So this is what I did: class SafePaginator(Paginator): def validate_number(self, number): try: return super(SafePaginator, self).validate_number(number) except InvalidPage: return 1 Unfortunately, still when I test ?page=k option I'm getting error: Page is not 'last', nor can it be converted to an int. ?page=last is working correctly This seems to be coming from ListView paginate_queryset as you can see on GitHub def paginate_queryset(self, queryset, page_size): """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_('Page is not “last”, nor can it be converted to an int.')) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page … -
How can I display Number in a Django Template
I have a list of Entries Generated from my Database and displayed on the template as seen below. {% for post in blog_post %} <tr> <td> S/N </td> <td><a href="{% url 'webpages:articles_detail' post.slug post.pk %}"> {{post.title}}</a></td> <td>{{post.created_on | date:"Y-m-d" }}</td> </tr> {% endfor %} How can I automatically display and increament the serial number part (labelled S_N) -
Server keep looping because of this code and I don't know why?
I want to save a second version of thumbnail field where the second version [thumbnail_low] resolution is 320 * 200 because I want my list view run faster. in creation form I accept image where the size is up to 5 megabytes and i don't want to load 5 megabytes per post. Sorry for mistakes i'm a french guy. f = BytesIO() try: copy.thumbnail((320, 200), Image.ANTIALIAS) copy.save(f, format="JPEG") b = f.getvalue() self.thumbnail_low.save("thumb", ContentFile(b)) finally: f.close() -
Error when creating an admin for the database Python (django)
1 You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). this error POPs up after 33 minutes of the tutorial: https://www.youtube.com/watch?v=zu2PBUHMEew After creating STRIPE_SECRET_KEY error when creating a superuser it was at 33 minutes approximately before that everything was fine . Help me find a solution ) -
Django/JS - Can't set default value for an already liked post
I want to check conditional on each post if the logged in user has liked it or not, accordingly I want to pass in a context which assigns the button a CSS class for the default value of color when the page loads. I don't want to use to use HTML if/else condition as I'm using JavaScript to change the color of the button when clicked. Even though I'm able to change the color once I click but I'm stuck at how to pass in the default condition of the post whenever the page loads. This is the JavaScript code : window.onload = function(){ var thumb_up = document.getElementById('thumb_up'); thumb_up.style.cursor = 'pointer'; thumb_up.onclick = function(){ var req = new XMLHttpRequest(); var id = this.getAttribute('data-id'); var url = '/api/like/'+id+'?format=json'; req.onreadystatechange = function(){ if(this.readyState==4 && this.status==200){ // var data = eval(req.responseText); data = JSON.parse(req.responseText); var likes = data.likes; document.getElementById('likes-count').innerHTML = likes+' votes'; //changing color if(data.liked=='true'){ thumb_up.className = "material-icons thumb_up_liked"; } else{ thumb_up.className = "material-icons thumb_up"; } } }; req.open("GET", url, true); req.send(); } } Also, I tried sending the default value for CSS/HTML class from backend, but I'm messing up the syntax. Can't figure out the logic to send it from backend either. … -
Configuring SSL Certificate for Django application on Apache using WAMP and mod_wsgi on Windows machine
I want to host a django web application on Apache server for which Im using WAMP server. The website is hosted and working fine but Im facing issues when Im installing SSL certificate. When I run as the intended website is shown appropriately instead it should have redirected to https://localhost and if I type https://localhost Forbidden You don't have permission to access this is shown httpd-vhosts.conf file: <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Django/my_project/my_project.error.log" CustomLog "C:/Django/my_project/my_project.access.log" combined WSGIScriptAlias / "C:/Django/my_project/my_project/wsgi_windows.py" <Directory "C:/Django/my_project/my_project"> <Files wsgi_windows.py> Require all granted </Files> </Directory> httpd.conf file: Here I have commented out these three lines Loadmodule ssl_module modules/mod_ssl.so, Include conf/extra/httpd-default.conf and LoadModule socache_shmcb_module modules/mod_socache_shmcb.so # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), … -
Django: Show posts with maximum upvotes
I am working on a project and I am a beginner in Django. In the project, the user can create product posts and other users can upvote it. On the homepage, I wanna show posts with maximum upvotes. I am using Postgresql as a backend. this is the view function for the homepage that returns products dictionary: def home(request): products = Product.objects return render(request, 'products/home.html', {'products': products}) as I am a beginner I am not getting any idea of how to do it in Django templates. -
Compare Rows with Latest in Django
I have a Django model stored in a Postgres DB comprised of values of counts at irregular intervals. Something like: WidgetCount - PK - Time - DeviceID - Count I can write a query to get me the latest count per device. I can write a query to get me the latest count per device which is over 24 hours old. I can write a query to get me the latest count per device which is over 7 days old. Is it possible to write something using the Django ORM to show me the difference between a number of values and the current latest value, across the whole table? So I can show either the absolute difference between 27 hours ago, and the latest, and 7 days ago and the latest? There's only a few hundred devices. I'd like to try not to use subqueries if possible. I realise I could write a few queries separately and compare the differences in Python but I wondered if this was possible using the Django ORM. Maybe something using annotate? Thanks! -
Django REST Framework: change the url to the .list() method only in a ModelViewSet
I'm making a registration api, and as I followed the docs, it recommended the use of ViewSets, so i used a ModelViewSet, now if i POST to the url '*/api/register/', I'll make a registration if provided valid fields (using .create() method), which is perfect for my case just what i needed. but when I want to list all the users for the admin, the request should be to the same url with a GET method, which is a bit weird to access '*/api/register/' to see the users... so I wanted to change the url for the .list() method to be something like '*/api/users/', but I can't find how to do that. here is what i'm doing until now: apis.py: class RegisterApi(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.filter(is_active=True) def get_permissions(self): if self.action == 'create': return [permissions.AllowAny()] else: return [permissions.IsAdminUser()] def create(self, request, *args, **kwargs): response = super().create(request, *args, **kwargs) if response: response.data = dict(status=True, code=1) return response urls.py: api_router = SimpleRouter() api_router.register('register', apis.RegisterApi, basename='users') extra_urls = [path('login/', apis.LoginApi.as_view()), ] urlpatterns = [ # views urls path('', views.Home.as_view(), name='home'), path('dashboard/', views.Dashboard.as_view(), name='dashboard'), path('login/', views.LoginView.as_view(), name='login'), path('register/', views.RegistrationView.as_view(), name='register'), # api urls path('api/', include(extra_urls + api_router.urls)), ] Any hints about this? -
django updating models from views.py
How can I update the models from this updateprofile function in views.py views.py def updateProfile(request): name = request.POST['name'] email = request.POST['email'] standard = request.POST['standard'] phone = request.POST['phone'] obj, created = Student.objects.update_or_create(name=User.username, defaults={'email': email, 'standard':standard, 'phone':phone}, ) if created: messages.info(request, 'Your details are Created!', extra_tags='Congratulations!') else: messages.info(request, 'Your details are updated!', extra_tags='Congratulations!') return redirect('/profile') models.py class Student(models.Model): name = models.CharField(max_length=45, null=False, unique=True) standard = models.IntegerField(null=True) phone = models.IntegerField(null=True) address = models.CharField(max_length=100, null=True) email = models.EmailField(unique=True) password = models.CharField(max_length=20, null=True) def __str__(self): return f"{self.name} class={self.standard} rollno={self.id}" I am getting 500 error each time i try to update the Student Model.... Please help me in this problem -
Invalid hook call. Hooks can only be called inside of the body of a function
I was trying to develop a login page with the Django rest framework as the backend. The backend is working perfectly whereas I can't even set up react js. I am getting an error in the Index.js file of react. It tells "Invalid hook call. Hooks can only be called inside of the body of a function component" This is what the error I get App.js import React from 'react'; import './App.css'; import Paperbase from './Layout/Paperbase' import { BrowserRouter, Route, Switch } from 'react-router-dom'; import Login from './Layout/Login/Login' import Register from './Layout/Register/Register' export function App() { return ( <BrowserRouter> <Switch> <Route path="/dashboard" render={() => <Paperbase /> } /> <Route path="/account/login" render={() =><Login />} /> <Route path="/account/register" render={() => <Register />} /> </Switch> </BrowserRouter> ) } export default App Index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import store from './store'; import { Provider } from 'react-redux'; import { render } from 'react-dom'; ReactDOM.render( (<Provider store={store}> <App/> </Provider>), document.getElementById('root') || document.createElement('div') // for testing purposes ); serviceWorker.unregister(); Login.js import React from 'react'; import Avatar from '@material-ui/core/Avatar'; import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; … -
changing "on"/"off" to True/False in views.py and saving it in database for many checkboxes
in my HTML Templates there are Checkboxes which return on/off, and django dont accept on/off it only accept true or false so how can i change on/off to true/false in views.py -
ValueError at / Required parameter name not set
I am developing a blog using Django. All is set and ready to deploy. I am using the Amazon S3 and I can't proceed because of this error ValueError at / Required parameter name not set. Please help. This is what I added to my settings.py file. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') A_KEY=os.environ.get("AWS_ACCESS_KEY_ID") A_SKEY=os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_ACCESS_KEY_ID = A_KEY AWS_SECRET_ACCESS_KEY = A_SKEY AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Full Traceback: Exception while resolving variable 'url' in template 'ecommerce/home.html'. Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 828, in _resolve_lookup current = current[bit] TypeError: 'ImageFieldFile' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 836, in _resolve_lookup current = getattr(current, bit) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\files.py", line 62, in url return self.storage.url(self.name) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\storages\backends\s3boto3.py", line 681, in url params['Bucket'] = self.bucket.name File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\storages\backends\s3boto3.py", line 385, in bucket self._bucket = self._get_or_create_bucket(self.bucket_name) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\storages\backends\s3boto3.py", line 422, in _get_or_create_bucket bucket = self.connection.Bucket(name) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\boto3\resources\factory.py", line 474, in create_resource client=self.meta.client)(*args, **kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\boto3\resources\base.py", line 119, in init 'Required parameter {0} not set'.format(identifier)) ValueError: Required parameter name not set Exception … -
How to fetch data of a particular id refrenced by foreign key django?
Following is model I have created: class Question(models.Model): title = models.CharField(max_length=255 ) description = models.TextField(max_length=300) class Quiz(models.Model): name = models.CharField(max_length=225,blank=False ) quiz_type =models.IntegerField(choices=QUIZ_TYPE,default=0) questions = models.ManyToManyField( Question, through='QuestionQuiz', related_name="quiz_question") categories= models.ManyToManyField(Category,through='CategoryQuiz',related_name='quiz_category') class QuestionQuiz(models.Model): quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) correct =models.DecimalField(max_digits=4, decimal_places=3) incorrect= models.DecimalField(max_digits=4, decimal_places=3) class Meta: unique_together = ('quiz','question') Views.py - Used django_filter package to create filter class FilterQuestionView( AddQuestionAjaxFormMixin,FormMixin,FilterView): form_class = QuestionQuizForm filterset_class = QuestionFilter paginate_by = 5 context_object_name = 'questions' This is template : {% for question in questions %} <tr> <form method='POST' id="q_{{question.id}}"> <td>{{question.title}}</td> <td>{{question.description}}</td> <td><input type="text" value="1" id="correct_{{question.id}}"></td> <td><input type="text" value="1" id="incorrect_{{question.id}}"></td> <td> <a id="btn_{{question.id}}" class="btn purple-gradient" onclick="addRemoveQuestion({{question.id}},{{quiz}})" >Add</a> </td> </form> When I click add button the question along with their scores correct get +1 and incorrect -1 are updated to the database. The corresponding quiz id is send thru the url in the form : path('filter_list/<pk>',views.FilterQuestionView.as_view(),name='filter'), What I want to achieve here is when page loads initially I want to show the scored for that corresponding question based on the quiz id passed in this for {{question.questionquiz_set.all }} but this will get all the question related to id. I want to get questions related to that quiz only.