Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Multi-Table Inheritance Performance
So I'm building a Django App that models companies with multiple levels of Organization: E.g. Company > Region > Store > Department, each represented with a separate Model. A User can be added as a Member to any one or multiple. In addition to Members, there are other Models that are related/"belong" to one of the organizational Models. I've been banging my head against my keyboard, but haven't found anything that answers the question: What's the best way to model that? The easiest way by far is to create a OrganizationalEntity Model that all of the above inherit from using Multi-Table inheritance, the Member Model using a M:1 relation with OrganizationalEntity. My research has yielded rather simpleton answers amounting to "Multi-table uses JOINs - that's bad!", with little evidence or context (is one level of inheritance super bad, or is just when you have 50 levels?). As far as I know, one level of inheritance is one JOIN - Relational DBs were kinda designed for that. Another solution (and my current one) is using a GenericForeignKey and some slightly hokey queries to achieve zero JOINs. It works, but adding Models is more than just adding a ForeignKey Field, plus it's … -
How do I resolve a type-error that int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' in polls app?
My models.py is class Question(models.Model): CATEGORY_SIZES = ( ('W', 'WORlD'), ('T', 'TECHNOLOGY'), ('S', 'SCREEN'), ('P', 'SPORTS') ) question_text = models.CharField(max_length= 100) pub_date = models.DateTimeField('Date Is Published') image = models.ImageField(upload_to="Question_Image", blank=True) category = models.CharField(max_length=1, choices=CATEGORY_SIZES) def __str__(self): return self.question_text And, I added four views in format inside views.py def world(request): latest_questions = Question.objects.filter(category='W') context = {'latest_questions': latest_questions} return render(request, 'polls/world.html',context) Then, I ran a command python manage.py makemigrations polls and set timezone.now as default for category Then, I ran another command python manage.py migrate And, I got this type error that TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' -
WSGIDaemonProcess causes 'You don't have permission error'
Hello I am trying to deploy my django application on digital ocean server. I did run the application inside a virtual environment and it all worked fine. But I want my domain to point to my application and followed this tutorial. But the problem is when the apache conf file is edited with the following code i get the error. Forbidden You don't have permission to access / on this server. This is how my directly looks +root +myproject +myproject settings.py urls.py wsgi.py +static manage.py +myprojectenv Here is my WSGI.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() Here is my Apache Default conf file 000-default.conf <VirtualHost *:80> #ServerAdmin webmaster@localhost #DocumentRoot /var/www/html Alias /static /home/user/alpha/static <Directory /home/user/alpha/static> Require all granted </Directory> Alias /static /home/root/myproject/static <Directory /home/root/myproject/static> Require all granted </Directory> <Directory /home/root/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/home/root/myproject/myprojectenv python-path=/home/root/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/root/myproject/myproject/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined I am not experience enough to find out what is causing the error. If i remove below lines in the apache conf file. I get Ubuntu home page when i try to access my server WSGIDaemonProcess myproject python-home=/home/root/myproject/myprojectenv python-path=/home/root/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/root/myproject/myproject/wsgi.py -
Could not find the GDAL library
I am unable to install GeoDjango. I am having the following error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? Try setting GDAL_LIBRARY_PATH in your settings. I tried the following the solution GeoDjango could not find GDAL library in Windows 10. But it didn't help me and I still have the same error. -
Is there a more concise notation than decorators to have a function called before any view function
All of my view functions require the django request object to pass some tests. Is there a shorter notation for this than putting a @request_passes_test(always_the_same_test) on top of each view-function? -
How can I find the locale settings with Gspread
Is there a way to find/change the locale setting of my Google Spreadsheet using Gspread? I want to import the data from multiple sheets owned by international clients and want to check the locale of each sheet before importing the data in my database. -
Display Dictionary values from python file in html page Django
I have searched alot about it but can't find the right answer. what i need to do is that in my project im running my python file which is showing me the result. Now what i need to do is that i need to show those values in my Dashboad.html page. Here is the code Dectree.py def showTree(self, dic, seperator): if(type(dic)==dict): for item in dic.items(): print(seperator, item[0]) self.showTree(item[1], seperator + " | ") else: print(seperator + " -> (", dic +")") tree = DecisionTree() tr_data, clss, attrs = tree.read_data('test.csv') tree1 = tree.create_tree(tr_data, clss, attrs) tree.showTree(tree1, ' ') right now im not using any view file for doing this. Dectree.py file is in my project folder and im trying to call it in my templates/Dashboard.html page. Kindly guide me here -
How to get jQuery range slider value into form to store in database in Django
The user have to be able to submit and save the value of the range slider 1. The purpose is that the user guesses how full an object is in real life and then can report back as part of a game the filling percentage. The user interface is in the picture below. Currently I can retrieve the data from the POST form (in the slider.html) as a preset 'value' but not the range slider value. I have looked much around, the problem is i'm not familiar enough with Javascript to implement the solution. I'm thinking one can fetch the value from the javascript function and directly tot he POST html form? Can anyone help suggesting how to do that or any other suggestions? This is the code so far, it's a bit of a mess because of many try and errors Models.py from django.db import models from django.forms import ModelForm from django import forms class Measurements(models.Model): DeviceId = models.IntegerField(blank=True, null=True) TimeStamp = models.DateTimeField(auto_now=True) Metadata = models.IntegerField(blank=True, null=True) Sensor = models.IntegerField(default=False) Button = models.IntegerField(default=False) QrUser = models.IntegerField(default=True) FillingPercentage = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True) slider_value = models.IntegerField(default=False, null=True, blank=True) def __str__(self): return str(self.DeviceId) class Meta: verbose_name_plural = "Measurements" Forms.py from django.forms … -
502 Gate Way - nginx/1.10.3 (Ubuntu) Dropplet One-Click Django Server
My Droplet One-Click Django Server respponse 502 Bad GateWay Error. Here is nginx error.log 2018/02/14 06:09:09 [error] 1486#1486: *3960 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 60.191.38.77, server: _, re$ 2018/02/14 06:12:09 [error] 1493#1493: *1 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 31.223.26.233, server: _, requ$ -
Adding forms to empty formset in HTML code
Django v1.10. How do I add forms to my formset dynamically on my webpage? Can this be done locally without using 3rd party plugins? None of the solutions for similar SO questions is working for me. -
how to send email in django
my settings in settings.py but not sending any mails to gmail account. can u please expalin me how to send confirm mail to mailenter code here EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'elearn.communication1@gmail.com' EMAIL_HOST_PASSWORD = 'kanth143' EMAIL_PORT = 587 I am getting success message in cmd but not sending email to my id def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() current_site = get_current_site(request) print(current_site) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) from_email =settings.EMAIL_HOST_USER print(from_email,"email here") # to_email = [from_email,'sridharadhi50@gmail.com'] to_email = form.cleaned_data.get('email') email = EmailMessage( subject, message, to=[to_email] ) email.send() # user.email_user(subject, message) return redirect('account_activation_sent')enter code here -
Django Cannot get media images or files
Django 2.0.2 cannot get the images or cannot show the images in media directory, also I defined them both media and static url and directory in setting.py. I don't know how to write the views.py Here is the error I am getting: (""GET /media/Cover_jDKCLdR.jpg HTTP/1.1" 404 4542") Thanks; -
How to resolve an Operational Error at /admin/polls/queston/ which says no such column: polls_queston.category_id?
I have created a class Categories in models.py class Categories(models.Model): name = models.CharField(max_length= 100) def __str__(self): return self.name And, in order to classify questions into categories, I have class Question(models.Model): category = models.ForeignKey(Categories, on_delete=models.CASCADE) def __str__(self): return self.question_text I have one category named world in views.py def world(request): category = Categories.objects.get(name='world') latest_questions = category.question_set.all() context = {'latest_questions': latest_questions} return render(request, 'polls/world.html',context) And, also I have prepared urls for each of four categories: world, technology, screen and sports and after all this when I open ...../admin/polls/question, I get an operational error. What am I supposed to modify here? -
Formset for MainClass<-ForeignKey<-OneToOneField?
I need to process applications to an amateur sports event. An event has several distances/subclasses, each of them has some restrictions (age, etc). My models are class Event(models.Model): title = models.CharField(max_length=255) # more fields class Klass(models.Model): title = models.CharField(max_length=255) capacity = models.IntegerField() event = models.ForeignKey('Event', related_name="klasses") # more fields class TeamRestrictions(models.Model): age_min = models.IntegerField() age_max = models.IntegerField() klass = models.OneToOneField(TeamRestrictions, related_name='restrict') # more fields I want to have a single page where a user creates a new event: names it, adds several subclasses into it and restrictions for every subclass. Well, without this one-to-one relationship, for just Event with several Klasses, I could use FormSet. Of course, I could move all TeamRestrictions fields to Klass, but that looks ugly for me. What should I use for this more complex structure? -
How to add a dynamic form in django form wizard
I am using django-formtools to split the registration form. I have a BaseUserProfileForm and three seperate form for different user models. At step 0, form is BaseUserProfileForm. I want to add the next form based on the value of request.user.userprofile.role. I have tried overriding get_form_list. def get_form_list(self): self.form_list = OrderedDict({'0': BaseUserProfileForm}) if self.request.user.userprofile.role == CUSTOMER: self.form_list.update({'1': CustomerForm}) elif self.request.user.userprofile.role == SELLER: self.form_list.update({'1': SellerForm}) elif self.request.user.userprofile.role == OTHER: self.form_list.update({'1': OtherForm}) for form_key, form_class in six.iteritems(self.form_list): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: self.form_list[form_key] = form_class return self.form_list Now I am getting error in get_form method. Also I am having seperate templates for these three forms. -
How to send image file without saving in database using django framework
I'm a novice in Django an am stuck in Django views.py am two field in forms.py 1st CharField 2nd ImageField my CharField is successfully rendered but ImageField does not render how solved this I want to send image file with tweet without saving in database please me to solved this problem thanks my files are here- forms.py from django import forms class HomeForm(forms.Form): tweet = forms.CharField() img = forms.ImageField(label='Select a Image file',) Views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import * from django.views.generic import TemplateView class Texting(TemplateView): Template_name = 'app_temp/xyz.html' def get(self, request): form = HomeForm() return render(request, self.Template_name, {'form': form}) def post(self, request): access_token = 'XYZ' access_token_secret = 'PQR' consumer_key = 'LMN' consumer_secret = 'ABC' api = TwitterAPI(consumer_key, consumer_secret , access_token , access_token_secret ) form = HomeForm(request.POST , request.FILES) if form.is_valid(): text = form.cleaned_data['tweet'] img = form.request.FILES['img'] r = api.request('statuses/update_with_media', {'status':text}, {'media[]':img}) return render(request,'app_temp/new_page.html') html {% extends 'login_base.html'%} {% block content %} <div class="container"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Tweet</button> </form> <h1>{{img}}</h1> <h1>{{text}}</h1> </div> {% endblock %} -
Django viewflows - Defining an API flow
I've an API endpoint, /api/create/. This creates a new entry in the DB depending upon the payload received from the client. Payload - { 'field1': 'value1`, 'field2': 'value2`, 'field3': 'value3`, 'field4': 'value4`, 'type': 'A' } Now depending on the type, I've a specific workflow. For eg:- Type A needs to perform certain tasks before saving the data, Type B has its own set of operations. I don't have any UI, just the requests coming over the POST request. How can I use django-viewflows for such a use-case? -
Django raise not getting called
//forms.py : //This is the forms part of my app. from django import forms from django.contrib.auth import ( authenticate, login, get_user_model, logout, ) User=get_user_model() class UserLoginForm(forms.Form): username=forms.CharField() password=forms.CharField(widget=forms.PasswordInput) def clean(self): username=self.cleaned_data.get('username') password=self.cleaned_data.get('password') user=authenticate(username=username,password=password) if not user: raise forms.ValidationError("This user does not exist") if not user.check_password(password): raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is no longer active") return super(UserLoginForm,self).clean() // views.py : //views part where in , i used the UserLoginForm created in the form. from django.shortcuts import render from django.contrib.auth import ( authenticate, login, get_user_model, logout, ) from .forms import UserLoginForm def login_view(request): if request.method=='POST': form=UserLoginForm(request.POST or None) if form.is_valid(): username=form.cleaned_data.get("username") password=form.cleaned_data.get("password") return render(request,"accounts/home.html") else: form=UserLoginForm() return render(request,"accounts/login.html",{"form":form}) def register_view(request): return render(request,"form.html",{}) def logout_view(request): return render(request,"form.html",{}) //login.html : //login.html which opens up as home page. <div> <form method='POST' action=''>{% csrf_token %} <input type="text" name="username" placeholder="Username"/> <input type="password" name="password" placeholder="Password"/> <input type="submit" value="Login"/> </form> </div> There are no errors, but neither the raise errors show up on invalid //stuff nor the page redirects to home.html on valid user. Please help me fix the problem. I am unable to find the problem. -
How to get selected radio button choice in django form?
I've a form class ScoreUpdateForm(forms.Form): answer_id = forms.IntegerField() given_score = forms.FloatField() CHOICES = [('calculated_score', 'Calculated Score'), ('given_score', 'Given Score')] final_score = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) I want to get values of the selected choice in my view after the post. -
Accessing data in GET form and posting to results page (Django)
I'm trying to create a form that takes inputs and uses these inputs to create an output that's posted to a results page. I've searched everywhere and can't understand how to post the data (in the case below, 'country' and 'culture') to the results_view. # view.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from form.forms import InputForm def get_list(request): if request.method == 'GET': form = InputForm(request.GET) if form.is_valid(): country = form.cleaned_data['country'] culture = form.cleaned_data['culture'] return results_view(form) else: form = InputForm() return render(request, 'form/index.html', {'form': form}) def results_view(form): text = form.restaurant c = {'output' : text} return render(form, 'form/results.html', c) and # forms.py from django import forms class InputForm(forms.Form): country = forms.CharField(label='country', max_length=100) cuisine = forms.CharField(label='cuisine', max_length=100) How can I access the inputs and use them as the text in 'results_view'? Additionally, if I want to pass these results as an input argument for another python function (say a function that maps country name to latitude and longitude), how can I incorporate this into views.py? Thanks a lot! -
How do I display the views output on my template in tabular rows?
I am using Django as my web framework. I have written a views function like this.. to fetch a list of all items under the keys UserId and AccountNum from an AWS DynamoDb table : def dsctbl2(request): dynamodb=boto3.client('dynamodb', region_name='us-west-2') response = dynamodb.scan( TableName='User-Account') filtered = response['Items'] length = len(filtered) for k in range(length): accnum = filtered[k]['AccountNum']['S'] uid = filtered[k]['UserId']['S'] f = dict(AccountNum=accnum,userID=uid) rows = [] for k,v in f.items(): rows.append(k) rows.append(v) return render(request,'useradd.html',{"rows": rows}) The rows variable yields a set of lists like this : ['AccountNum', '873627867348', 'userID', 'abc'] ['AccountNum', '873627867348', 'userID', 'def'] ['AccountNum', '038683828978', 'userID', 'ghi'] ['AccountNum', '581889263266', 'userID', 'jkl'] ['AccountNum', '581889263266', 'userID', 'mno'] ['AccountNum', '581889263266', 'userID', 'pqr'] ['AccountNum', '581889263266', 'userID', 'stu'] ['AccountNum', '977201296795', 'userID', 'vwx'] ['AccountNum', '232686542773', 'userID', 'yza'] I need to display these values in my table in my HTML template. The HTML table snippet is below : <div class="mytable"> <table style="width:96%" class="table table-responsive"> <thead id="head" class="mdb-color lighten-4"> <tr> <th></th> <th class="th-lg">Account #</th> <th class="th-lg">User Id</th> </tr> </thead> <tbody> <tr> <th scope="row"></th> <td>{{rows.AccountNum}}</td> <td>{{rows.UserId}}</td> </tr> </tbody> </table> </div> But when I hit that html page in my browser , I can see only the table headings 'UserId' and 'AccountNum'. Why aren't the UserId and AccounNum values getting … -
Python Django error : version GLIBC_PRIVATE not defined
I have a python Django project. When I run its manage.py script as manage.py unserver, I get following import error. ImportError: /home/xxxxx/Projects/Dev/yyyy/ENV/new_env/lib/python2.7/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference What may be the reason? -
Keeping a computed model field up-to-date via QuerySets
Preface: Let's assume we are working on a DB that stores issues of magazines. Those issues usually do not have a 'name' per se; instead a whole bunch of attributes (release year, serial number, release months, etc.) will contribute to the name the user may later on identify the issue with. Depending on the attributes available per issue, this name will be calculated based on a pattern. For example: an issue from the year 2017 with number 01 will get the name: 2017-01. An issue from the years 2000 and 2001, and the months Jan and Feb will get the name 2000/01-Jan/Feb. The attributes can be changed at any time. It is expected that the user can also do queries based on this name - so simply displaying the computed value (through __str__) is not enough. What I have done so far: For a long time, I actually calculated the name every time __str__ was called on the issue's instance. It was the quick and dirty (and slow) way. Querying for the name was very slow and rather complicated and unreliable as it required 'reverse-engineering' the __str__ method and guessing what the user was trying to search for. Then I … -
jwt rest framework returning user id with token
I'm using jwt-rest-framework for user authentication, and I would like to return a user_id with token. There are some examples on how to do it when using django-rest-framework, so according to this example I've tried to override ObtainJSONWenToken jwt view and did the same thing from rest_framework.authtoken.models import Token from rest_framework.response import Response from rest_framework_jwt.views import ObtainJSONWebToken # Create your views here. class CustomObtainJSONWebToken(ObtainJSONWebToken): """ Return user id with token """ def post(self, request, *args, **kwargs): response = super(CustomObtainJSONWebToken, self).post(request, *args, **kwargs) token = Token.objects.get(key=response.data['token']) return Response({'token': token.key, 'id': token.user_id}) But the Traceback is pointing out to the token it self: Traceback: File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.5/contextlib.py" in inner 30. return func(*args, **kwds) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in dispatch 489. response = self.handle_exception(exc) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "/home/copser/Documents/iToucan-BackHand/iToucan/itoucan/rest_auth/views.py" in post 15. token = Token.objects.get(key=response.data['token']) The question is what is the proper way of returning user_id with the token, … -
Is there any module in python for converting markdown to pdf
In my application, I want to give the response in PDF format. Tried one module markdwon2pdf, that didn't work