Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to submit Post request with form and getting error __init__() takes 1 positional argument but 2 were given
I keep getting the error: TypeError: init() takes 1 positional argument but 2 were given when I submit this form, it seems form = dashboardview(request.POST) is the problem but I cant figure the issue. class dashboardview(TemplateView): templatename='fitness/dashboardcomp.html' def get(self, request): form = MyForm() posts= Post.objects.all() args= {'form': form, 'posts':posts} return render(request,self.templatename,args) def post(self, request): form = dashboardview(request.POST) if form.is_valid(): form = dashboardview() args={'form':form, 'text':text} return render(request,self.templatename,args) -
ng-click not working on button (angularjs-django)
I am new to angularjs and unable to figure out why ng-click on a button is not working. I am pasting code below. I am using a django server to render the page. HTML CODE: <body ng-controller="myController"> <div class="container-fluid" > <table class="col-xs-12-ls-12 mfPortfolioTable" width="100%"> <tbody> <tr ng-repeat="x in records"> <td class="search_table_cell col-xs-1-ls-1">{% verbatim %}{{ x.units | number:3 }}{% endverbatim %}</td> </tr> <tr> <td><button class="btn btn-primary" ng-click="updateMfPortfolio()" id="updateFolio">Update</button></td> </tr> </tbody> </table> </div> <script src="{% static 'script.js' %}"></script> </body> CONTROLLER CODE: var app = angular.module('searchApp', []); app.controller('myController', function($scope, $http) { $http.get('/somelink/').then(function(response){ $scope.records = response.data.data; }); //This is the function which I expect to get triggered by ng-click $scope.updateMfPortfolio = function(){ console.log('Updating MF Portfolio...'); $http.get('/somelink/').then(function(response){ console.log('Code reached here...'); $scope.records = response.data.data; }); }; -
Using custom class view in django get me error
I'm learning django and i'm trying to create my own custom class in a views.py file This class i would use have to method, one for classical HTML rendering, and another for json response my class in views.py class myListView(): context = {} def __init__(self, request): request = request context['PageTitle'] = 'Contacts' context['people'] = People.objects.all() def htmlRender(self, *args, **kwargs): context['children_template'] = 'people/list.html' return render(request,'base.html',context) def jsonRender(self, *args, **kwargs): return HttpResponse(json.dumps(self.context['people']), content_type="application/json") my urls.py path('list', login_required(myListView.htmlRender()), name='list'), path('list/json', login_required(myListView.jsonRender()), name='list'), Here is the error sended by debugger : TypeError: htmlRender() missing 1 required positional argument: 'self' I don't have any idea how to solve this, maybe i'm dreaming about using custom class in view ? Thanks'you -
Django modelform submission with relational data
I have a django modelform that creates a new listing in my post app, I would like to associate this with a company id, which is an account type in my account app. The account_company db table (postgresql) has a user_id field which is the pk of User. the post_listing table will have a company field which I think should be the pk of account_company. As I am attempting to use modelforms for all forms, I am having an issue with making this association. # models.py class Listing(models.Model): title = models.CharField(max_length=200) company = models.ForeignKey(Company, on_delete=models.CASCADE) ... # forms.py class newListingForm(forms.ModelForm): class Meta: model = Listing fields = ('title'...) def __init__(self, user, *args, **kwargs): super(newListingForm, self).__init__(*args, **kwargs) self.fields['company'].queryset = Company.objects.filter(pk__user_id=user.id) # above i am trying to filter the AutoField to the `company pk` where `user_id` is equal to `request.user.id` # views.py def post(request): if request.method == 'POST': form = newListingForm(request.user, request.POST) if form.is_valid(): listing = form.save(commit=False) listing.user = request.user listing.save() else: form = newListingForm(request.user) return render(request, 'post/post.html', {'form': form}) -
Django urls with https behind nginx proxy
I have django rest framework behind nginx proxy and some frontend on vue js. The problem is that I have urls with "http" but I need it to be "https": "images": [ { "id": 2, "image": "http://localhost:8000/media/documents/2019/02/26/d59b9c8d-bb36-4461-97ad-7455f19637b8/FVbJkfww_Sk.jpg" }, { "id": 1, "image": "http://localhost:8000/media/documents/2019/02/26/902e5729-f7fd-480b-bf39-bca65a83038e/%D0%B4%D0%B6%D0%B5%D0%BA%D0%B8-%D1%87%D0%B0%D0%BD-%D0%BC%D0%B5%D0%BC-%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD.jpg" } ] nginx is configured like that: server { listen 8443 ssl; server_name backend.beautyology.net; client_max_body_size 3200m; proxy_connect_timeout 3000; proxy_send_timeout 3000; proxy_read_timeout 3000; send_timeout 3000; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE_ADDR $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://localhost:8000; } My django config os below: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True USE_X_FORWARDED_HOST = True -
ReactJS and Django with Axios - CSRF tokens and form data with POST requests
I've read through multiple examples and tried all of the code - for some strange reason none of it is working with my current project. If I use postman I can add users without problem. When I try to replicate my postman requests in React, it goes through just the same but no user details are saved to my Django database. I've tried Django rest, researching and reading threads for two days. Django Settings """ Django settings for demo_project project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # 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/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '58u29^u@wy%90)%ni=u5muf1h(g@*el*o$q%nvnxji3*yg!1hl' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'users', 'pages', ] # custom user model AUTH_USER_MODEL = 'users.CustomUser' 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', … -
Nginx with Daphne gives 502 Bad Gateway
I decided to replace uwsgi with daphne since I was having issues with Django Channels and uwsgi. After following this tutorial. I configured my nginx this way in sites-enabled. Most of the other examples I have come across are not using daphne so I could not relate to them. server { # the port your site will be served on listen 80; server_name .MyDomain.com; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { # your Django project's media files - amend as required alias /home/ec2-user/MyDomainVenv/MyDomainWeb/media; } location /static { # your Django project's static files - amend as required alias /home/ec2-user/MyDomainVenv/MyDomainWeb/static; } location / { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } I started Daphne using this way daphne main.asgi:channel_layer and a worker thread using python manage.py runworker This is my asgi.py import os from channels.asgi import get_channel_layer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") channel_layer = get_channel_layer() any suggestions on what might be going wrong ? I tried accessing my website and this is what i got ==> /var/log/nginx/error.log <== 2019/03/23 07:13:21 [error] 22191#0: *4 connect() … -
Redirect after saving the model form in django cbv
what i am looking for is similar to Django admin action while adding a new item. When we add an item in Django admin, if a required item is not in foreign key, there is a link given there itself to add the required foreign key item, when clicking the link another pop up window appears and we can save the required item there and can go back to the main form and continue the job there. Similar to this, i have done everything except the redirect it back to the previously filled form. So how i can go back to there. My view is as follows views.py I have tried to redirect it back to the main form but it comes up without any previously filled data class IsoCreateView(LoginRequiredMixin, PassRequestMixin, SuccessMessageMixin, CreateView): model = Iso form_class = IsoCreateForm template_name = 'forms/pefs_form.html' success_url = reverse_lazy('data') -
How do i solve Social Login Problem in Django
I'm using django all auth library. After get permission from the provider it shows the following error. -
handling large queryset in django view to render it on webpage using streaminghttpresponse or some other alternative
I have written a view in django that queries a database and returns the output to requested page using django's return render() But when the queryset have thousands of rows it takes alot of time for a webpage to give response and since i have also hosted this on heroku, by the time i get the response, heroku request timeout occurs. Is there some way to send data in small chunks to the webpage continuously till all the data is received by the webpage. view.py ... queryset = Announcement.objects.filter(....) context_data = { ... "query_set":query_set, ... } return render(request,"index.html",context_data) Expected result is that as soon as the request is made the requested page gets a response with partial result of queryset and incrementally continues to load all data. -
Django - MongoDB - referring to wrong model
I have 3 models, A, B and C. Model C have 2 reference fields, one is pointing to A and another to B. There are 3 update APIs, for each of the model tables. There is a 4th API that will retrieve data from table C and related data in table A and B. Sometimes during fetching the data in 4th API, we face issue where the variable pointing to model B is said to be pointing to model A and hence fail to get the field which is in B and not in A. This sometimes happen for variable pointing to model A as well. This happen on and off and it get resolved on its own. I am not sure where to start looking for the issue. Can someone please help me? -
sending notification to one user using Channels 2
I want to send notification to specific authenticated user using Channels 2. In below code i am sending notification as a broadcast instead of that i want to send notification to a specific user. from channels.generic.websocket import AsyncJsonWebsocketConsumer class NotifyConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("gossip", self.channel_name) print(f"Added {self.channel_name} channel to gossip") async def disconnect(self, close_code): await self.channel_layer.group_discard("gossip", self.channel_name) print(f"Removed {self.channel_name} channel to gossip") async def user_gossip(self, event): await self.send_json(event) print(f"Got message {event} at {self.channel_name}") -
Django: How do I combine a list and a queryset, paginate both of them and iterate through them in the template?
I'm finishing up my leader-board. I currently return the top 100 leaders for a given category. I need to attach the current rank to the results. At first I tried the forloop.counter variable in the template, but since the results are paginated by 10 results at a time, each new page reset the counter. def leaderboard(request): stats = Leaderboard.objects.all().order_by('-most_hits')[:100] rank = list(range(1, 101)) paginator = Paginator(stats, 10) page = request.GET.get('page') results = paginator.get_page(page) context = {'results': results, 'rank': rank} currently returning wrong rank on page 2,3 etc -
How to redirect a user from django.contrib.auth.urls if he already logged in?
I want to redirect a user from my login page, if he already logged in. I knew that I can do redirect_if_logged_in = True but how to set it for all the views in path('account/', include('django.contrib.auth.urls')), ? Or how to set it only for login view? urlpatterns = [ path('admin/', admin.site.urls), path('', IndexView.as_view(), name='main_page'), path('account/', include('django.contrib.auth.urls')), path('account/register', RegisterView.as_view(), name='register') ] class IndexView(TemplateView): template_name = "index_page.html" redirect_if_logged_in = True redirect_to = 'itdoesnotwork.com' class RegisterView(FormView): template_name = 'registration/register.html' form_class = UserCreationForm success_url = reverse_lazy('login') redirect_if_logged_in = True redirect_to = 'itdoesnotwork.com' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.save() messages.add_message(self.request, messages.INFO, 'Hey, you just registered an account, login please :)') return super().form_valid(form) -
How to give API key to Django model
I have to build web service using Django. Employer provided me with description of models and json file with api methods (here). So, I need to create api. I decided to use django rest framework, but this is first time me working with api, so one field in described model is bothering me. It's api_key = models.CharField(...) #access key to api. As I understand this key needs to be given by me to model object (in my case it is model for Printer that prints checks for client and kitchen) and then it must be used for accessing this objects to api (methods /new_checks/ and /check/). But how do I create this keys? Should I just use random api key generator or there is some instrumental in Django Rest framework that I didn't find yet? -
How to Django visitor file upload to new sub-directory and directory name should be session name?
I am creating django Apps. It has only one model class and that is file uploading. It has no user login and registration system. I need when someone visits the webpage and upload a file, it should create a new directory inside "/media" directory. and the directory name should be unique and the name should be session name. Read Carefully: It should be When the visitor visit page and upload file, it should create a new directory automatically and even when the visitor reloads the page and upload again new file, it should create another new directory and store that season uploaded file on that directory. My model.py from django.db import models # Create your models here. class ImageForExtractText(models.Model): image = models.FileField() and my form.py from django import forms from .models import ImageForExtractText class UploadImage(forms.ModelForm): class Meta: model = ImageForExtractText fields = [ 'image', ] and view.py from .forms import UploadImage from django.shortcuts import render, redirect def upload(request): form = UploadImage(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return render(request, 'home.html', {'form': form}) And my setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media") Hope you got this issue and let me know if you don't get … -
How to give django action url dynamically onclick without jquery
I have list view and on button click of each object it opens up a form that is previously rendered (outside for loop ,single form in that page) for time being have given args id as 0 in url and changes the id onclick using jquery ,how to use django to change this url -
How to upload raster file to RasterLayer without using admin
I have a model: class classificationRaster(models.Model): raster = models.RasterField() name = models.TextField() I wounder how to upload a raster file(.tif) with help of model to django database (I'm using django-raster) -
Bootstrap tabs don't function properly inside a modal
I am using Bootstrap to display nav-tabs inside a modal, shown when a button is clicked. The issue is that when a tab is clicked its content is not shown. Below you can see a simple example: {% load static %} {% load rest_framework %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="{% static "myapp/js/modal.js" %}"></script> </head> <body> <button type="button" class="btn btn-secondary" id="show-modal">Show modal</button> {% include "myapp/modal_test.html" %} </body My js script: $(document).on("click", "#show-modal", function () { $("#exampleModalCenter").modal('show'); }); The modal code I am talking about: <div class="modal fade" id="exampleModalCenter" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="pills-home-tab" data-toggle="pill" href="#pills-home" role="tab" aria-controls="pills-home" aria-selected="true">Home</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-profile-tab" data-toggle="pill" href="#pills-profile" role="tab" aria-controls="pills-profile" aria-selected="false">Profile</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-contact-tab" data-toggle="pill" href="#pills-contact" role="tab" aria-controls="pills-contact" aria-selected="false">Contact</a> </li> </ul> <div class="tab-content" id="pills-tabContent"> <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">0</div> <div class="tab-pane fade" id="pills-profile" … -
How to save user session data which is appended list in django?
The problem is that I cannot seem to assess saved user data. I am trying to save user session data on their HTTP requests, but am unable to find that data in the Sessions or SessionStore. How do I correctly save this data. It should be an appended list object. Here is some code on what I have already tried: from django.contrib.sessions.models import Session request.session.modified = True object_save = list(_objs.values('service__code')) if not 'result' in request.session or not request.session['result']: renderequest.session['result'] = [object_save] request.session.save() else: result_list = request.session['result'] result_list.append(object_save) request.session['result'] = result_list request.session.save() I'd expect this to be able to save and I can look at the searches in python manage.py shell. When I try to pull all the session data with s = Session.object.all() and s['result'] I get nothing. s has no attribute 'result' is the error. -
Changing int 10 to int 11 using DDL
What would be the DDL syntax for changing a MySQL column name from int(10) to int(11)? I've done a number of searches using DDL, int(10) and int(11) like this but I've not found any syntax examples. The current migration is failing because an int(11) is being used as a foreign key referencing an int(10) I realise I can do this in a GUI. I'm looking to push this change into a migration script for Django. -
Heruku app.json not working in continus delivery
I am working in a Django project. Its just work fine in local computer. Its also work fine when i deploy this to heroku. Its even work fine when i create heroku staging and production app. But its not working when i create app.json using heroku automatic commend. -
Why does my crispy form not load until I click the View Image/View PDF button?
Upon loading, it looks like the image above. In the middle, there is an upload file form done through crispyforms. This is how I want it to look like upon loading the website. Instead, I need to click a button before this upload part of the form shows up. <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4" >tul.ai</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button name = "upload_image" class="btn btn-outline-info" type="submit">View Image</button> <button name = "upload_pdf" class="btn btn-outline-info" type="submit">View PDF</button> </div> </form> Above is the HTML with the crispyform. from django import forms from .models import Photo, PDF class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ['image'] class PDFForm(forms.ModelForm): # file = forms.FileField() class Meta: model = PDF fields = ['file'] Above is the code for the forms themselves. from django.db import models from PIL import Image class Photo(models.Model): image = models.ImageField(upload_to='imgs') def save(self): super().save() img = Image.open(self.image.path) if self.image.height > 2200 or self.image.width > 1700: output_size = (1700, 2200) img.thumbnail(output_size) img.save(self.image.path, quality = 100) class Meta: verbose_name = 'photo' class PDF(models.Model): file = models.FileField(upload_to='pdfs') def save(self): super().save() class Meta: verbose_name = 'pdf' This is the models.py file. -
Displaying list element attributes on template [Python, Django]
I am trying to access specific attributes from elements of a list of data I pass to a template page. An example of what one of my lists my look like would be: mylist = [{'id': '346110', 'name': 'jimmy', 'desc': 'jim is cool'}, {'id': '730', 'name': 'bobby', 'desc': 'bob is cooler'}] return render(request,'../templates/myview.html',{"list": mylist}) So, for example how would I display "bob is cooler"? My html: <p> {% for item in list.items %} <tr> <td> {{ item }}</td> </tr> {% endfor %} </p> -
NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name
help please! sorry about my english , i'm weak in english I try to visit this page "192.168.56.102 / project / BP / 4", it shows me this msg error! the same configurations of urls and views with other page it works Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://192.168.56.102/project/BP/4 Django Version: 2.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. urls.py : path('BP/<int:id_project>', views.tb_project , name='tb_project'), path('delete/p/<int:id_project>',views.delete_project , name='delete_project'), views.py : def tb_project(request,id_project): template ="project/bord_project.html" context = {} prj = get_object_or_404(project ,id = id_project) context["prj"] = prj return render(request, template ,context) page.html <a href="{% url 'tb_project' element.id %}"> <!-- element.id = 4 --> the link is displayed correctly in the page : 192.168.56.102/project/BP/4 but when I click to go to bord_project.html , error msg