Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The compressed avatar image getting "rotate" in Python
I have added the image compression code for Avatar in my application. But sometimes it saving the uploaded image as "rotate". Please check the below code, import Image, ImageFile pic = "pic/goes/here.jpg" im = Image.open(pic) width, height = im.size if width > 1000 or height > 1000: width = width*.7 height = height*.7 im = im.resize((int(math.floor(width)), int(math.floor(height))), Image.ANTIALIAS) try: im.save(pic,optimize=True,quality=70) except IOError: ImageFile.MAXBLOCK = width * height im.save(pic,optimize=True,quality=70) Do i need to update something or Any other alternative method to resize the image upload for AVATAR ? -
Is it good approach not to use Database in Django
We are developing website with Django as front-end & Salesforce NPSP as the back-end. We are asked not to use any of the Database like SQLite or MYSQL & data management will be completely handled by Salesforce. a) Is it good idea to do the above? b) You want certain pages to be access only by logged-in users, I was planning to use decorators @login_required (which work only with DB at the back-end) How to achieve this functionality with Salesforce as back-end? c) I need to share user data between several pages, directly approach would have been to use the User object but with no DB i will be forced to use session variables. Is any other was possible to achieve this? Any other suggestions in the above area are welcomed. -
file uploading Django code not working from /var/www/
def upload(request): print(request.FILES) if request.POST and request.FILES: files = request.FILES print(files) for file in files: data = files[file] with open('/tmp/%s' % data.name, 'wb+') as dest: for chunk in data.chunks(): dest.write(chunk) return render(request, "create.html") return HttpResponse("Failed to Upload") Above code works from when Django project is in root folder. but when I push the code to /var/www/ folder the same code not working. for request.FILES I am not getting the files uploaded in the output. Not able to understand where code is missing. can anyone help me out finding out what is the issue -
deleting the parent (primary) values when deleting the inline value django admin?
when i am trying to delete the values in inlines using django admin , the primary key objects are deleting,please solve my problem.Thanks in advance. -
How to get just list of ids in ManytoMany Field
class Task(models.Model): title = models.CharField(max_length=80) asignee = models.ManytoManyField(User) Is there an efficient way of getting just the 'id's of the users assigned to a task? I dont want to use this - task.asignee.valueslist('id', flat=True) The asignees will be from a limited list and already available. So there is no need to get to the user level. But I need the ManytoMany relation for reverse lookups. TIA -
Using python 3.6 on azure app services - not working despite it is installed as extension
I've got a challenge with deploying Django app (wagtail to be precise) to Azure Web Services using external Git repo (Bitbucket). I want to use Python 3.6.1, therefore I followed instructions at Managing Python on Azure App Service manual I have python 3.6.1 extension installed and in place I created web.config file in root directory of my app (I checked and it is uploaded to the server) However, deploy fails with message Detecting Python runtime from runtime.txt Unsupported runtime: python-3.6.1 Supported runtime values are: python-2.7 python-3.4 An error has occurred during web site deployment. \r\nD:\Program Files (x86)\SiteExtensions\Kudu\66.61008.3066\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd" My web.config file <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="PYTHONPATH" value="D:\home\site\wwwroot"/> <!-- Django apps only --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()"/> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/> </appSettings> <system.webServer> <handlers> <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python361x64\python.exe|D:\home\python361x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> </system.webServer> </configuration> Paths are ok, below is ls from Kudu console D:\home\python361x64>ls DLLs Lib Scripts __pycache__ python.exe python3.dll python36.dll pythonw.exe sitecustomize.py vcruntime140.dll wfastcgi.py It looks like the deployment process is not taking into account the web.config file that I have, or the python version that I've installed via extensions is not visible. Could you please tell me where the possible issue could be? Best regards, Konrad -
Can I run django server ingnore part of the project in Django?
Can I run django server ingnore part of the project in Django? I have a Django project with several apps, and one of the apps is need to import openstacksdk(because it relay on many linux libs, in Mac env is very troublesome ), so I must work in the Linux operate system. but now I have done that app which must import openstacksdk. Now I cloned the project from Linux to my mac, there will report error which related to openstacksdk. This is the directory of my project: So, is there a way only to debug the apps that do not contain the openstacksdk-related app? -
How to get values of choicefield using raw query from Django?
I am trying to get values of choicefield from table of database using raw query but it doesn't work with notification 'NameError was unhandled by by user code' What was wrong? Here is forms.py class SearchForm(forms.Form): validflg = forms.ChoiceField(label=("Names:"), choices = names(), widget = forms.Select({'class':'form-control'})) def get_names(): cursor = connection.cursor() get_query = str("SELECT distinct name from T_STUDENT") cursor.execute(get_query) results = cursor.fetchall() names = [] i=0 for row in results: names[i]=row[0] i+=1 return names def names(): data = get_names() i=0 names= [] for key,value in data: names.append(('i',value)) i+=1 return names -
httpd and mod_wsgi ran with wrong python version
I am deploying django project with httpd on RHEL7. And changed the system default python version to python3.4. But after I restarted the httpd, it still used python2.7. I searched a lot and it mostly because of mod_wsgi was built under wrong python version. However, I checked that mod_wsgi was installed under python 3.4. May I know how to make it run under the correct python version? Not too sure if httpd has default python version... Thanks very much for your help! enter image description here -
Forbidden (CSRF token missing or incorrect.) - even though it's included
I keep getting the above error even though I have included a csrf_token already. I've used the same csrfmiddlewaretoken for my other ajax calls and it works fine but here im getting the forbidden error. Any idea why? Here's my form: <form method="post" enctype="multipart/form-data" id="profileImageForm">{% csrf_token %} <label for="id_banner_image" class="change_profile_img">change <input id="id_banner_image" type="file" name="image" /> </label> <input type="submit"> </form> Here's my JS: $(document).on('submit', '#profileImageForm', function(e){ e.preventDefault(); var form_data = new FormData(); var image = document.getElementById('id_banner_image').files[0].name; form_data.append('file', image); $.ajax({ type:'POST', url: '/change_banner_image/', data : { form_data: form_data, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, cache: false, contentType: false, processData: false, success: function(response){ console.log('Success'); }, }); }); -
get access to serializer validated data DRF
all the django rest framework docs assume your going to instantly save the data. But what if I want access to the serializer data? What if I want to do something with it. Or if the serializer contains info other than what I need to save in a model? is the validated_data attribute what we need? So validatedData = serializer.validated_data userid = validatedData.get('id') would work right? -
DJango CreateView not setting DB Key with Class-Based Views
I am using CreateView from DJango to save data to the DB. To do this, I am following the instructions here: Form handling with class-based views According to my understanding, after the data is saved to the DB, the control is to be passed to a type of "success screen" - in this case, for my scenario, control is to be passed to a "details page". The details page is represented by the following URL: url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(), name='owner-contact-details'), Below (in the class Mstrstoreheadcontact) the "details page" is being called by the get_absolute_url function (which is part of the Mstrstoreheadcontact model) from the models.py file class Mstrstoreheadcontact(models.Model): tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True) contactid = models.BigIntegerField(primary_key=True, default=0) genderid = models.BigIntegerField(blank=True, null=True, default=0) firstname = models.CharField(max_length=20, blank=True, null=True) lastname = models.CharField(max_length=20, blank=True, null=True) officephoneno = models.CharField(max_length=20, blank=True, null=True) cellphoneno = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'MstrStoreHeadContact' def get_absolute_url(self): return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid}) For me the code: return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid} is supposed to take the control to the "details page" that will display the new record that has been added to the DB. The problem When the code above is executed, the variable self.contactid is set … -
How develop django or python3 payment in china?(wechat pay and alipay)
I'm the new guy with the python django framework developer , I don't know how to connect or get the China payment in my django -
Django rendering a db field in the template
Could anyone correct my code? Background: The user, once on the 'start.html' template, will enter their name and press submit. Then on the next template, 'game.html', there should be a paragraph tab that contains that users name. Problem: I must be writting something incorrectly because the user's name does not render on the 'game.html' template. Or, I could also be storing it wrong. Any suggestions or corrections would be very appreciated! models.py - fp from django.db import models class User(models.Model): #first player name fp_name = models.CharField(max_length=30, default='') forms.py - I'm not sure if this is actually needed...? from django import forms class PlayerInfo(forms.Form): fp_name = forms.CharField(max_length=30, label='First player name') views.py - from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, render_to_response import os from .forms import PlayerInfo from .models import User def index(request): return render(request, 'index.html') def start(request): if request.method == 'Post': form = PlayerInfo(request.POST) if form.is_valid(): obj = User() obj.fp_name = form.cleaned_data['fp_name'] return HttpResponseRedirect('/') else: form = PlayerInfo() return render(request, 'start.html') def game(request): return render_to_response('game.html', {'obj': User.objects.all()}) start.html - Meant to submit player one's name {% extends 'base.html' %} {% block botRow %} <form method="post"> {% csrf_token %} <label for="fp_name">First Player Name</label> <input id="fp_name" type="text" name="fp_name" maxlength="30" required /> … -
Saving Blog in Django with figure, Space, paragraph, link
I am from embedded field but trying to learn web development and using Django for this purpose and using Postgresql as a back-end database. Questions can be silly but please understand that my level is beginner. I am making one website in which user can write new blog entries. For this purpose, I am using Textarea to let user write the blog entry. My questions are 1) Is there any good text editor which i can embed in my website and let user write their entries. Right now, i can only write text but can't choose the font, upload pic, or format the text. 2) I am thinking to store the link to figure in the database and uploading the pic to the google drive or dropbox. is this good practice? can you recommend some other method? 3) How can i let the text saved in the database to know when to start a new paragraph? HTML tag will be enough, or do i need to use some other method? -
Is it possible to trace back 403 error during ajax request in Django Rest Framework?
I'm trying to make an ajax call with DRF and each time receive: [20/Oct/2017 13:35:24] "OPTIONS /test/ HTTP/1.1" 403 82 I can't understand the reason of this error(I disable csrf by decorators and by middleware). Is it possible to raise exception instead of 403 response in Django to find out which middleware and and which code line return 403 error? -
Error trying to create Generic Relation
Hi I'm trying to create a GenericForeignKey Relation to link a reviews model to a set of location classes of different types of locations.. So I class museum, restaurant, park, industry, zoo, etc. which all inherit from an abstract class 'Location' and i want to be able to submit reviews for all the different locations saved for these types.. This is what I have so far in models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation class Location(models.Model): name = models.CharField(max_length=50) lat = models.FloatField() lng = models.FloatField() address = models.CharField(max_length=80, unique=True) city = models.ForeignKey(City, on_delete=models.CASCADE) email = models.EmailField(blank=True) # Below the mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: abstract = True class Reviews(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.CharField(max_length=200) reviews = GenericRelation(Location) def __str__(self): return self.name class College(Location): departments = models.CharField(max_length=200, blank=True) def __str__(self): return self.name class Industry(Location): type = models.CharField(max_length=50, blank=True) class Meta: verbose_name_plural = 'Industries' def __str__(self): return self.name class Hotel(Location): phone = models.CharField(max_length=15, blank=True) def __str__(self): return self.name I want to create a character text field in the reviews class (and use that for … -
How to save an array of object in DRF
I have this type of json: { "word" : "world", "days" : [1, 3, 7] } And DRF gives me this error: 'days': [{'non_field_errors': ['Invalid data. Expected a dictionary, but got int.']}, This is my days serializer: class DaysSerializer(serializers.ModelSerializer): class Meta: model = Days fields = ('day') And this my top level serializer: class WordsSerializer(serializers.ModelSerializer): days = DaysSerializer(many=True) class Meta: model = Words fields = ('word', 'days') I read that I need to use bulk serializers. Is that the route that is recommended today? Or there is a simpler way? If I need to use the bulk serializer library, I don't understand from their example how do I use that library for my purposes? Namely to (bulk) save the many to many entries (the Days) in one of the records (the Word). -
View error "str is not callable" with ModelChoiceField
I want to add Select field to form for field with type ForeignKey and use for this ModelChoiceField. But this form doesn`t rendering and throw error "'str' object is not callable" on the line " {{ form_ord.all_users}} {{ form_ord.pay_method }} {{ form_ord.pay }}" in order_add.html file. What can I use to create form for model with ForeignKey field? order.py class Order(models.Model): PAY_METHOD_CHOISES = ( ('CASH', 'cash'), ('CREDIT', 'credit card'), ('CHECK', 'check'), ) pay_method = models.CharField(max_length=15, choices=PAY_METHOD_CHOISES, default='cash') user_id = models.ForeignKey(UsersData) pay = models.BooleanField(default=False) @property def __str__(self): return self.user_id.user_name def pay_or_not(self): if self.pay: result = 'paid' else: result = 'not paid' return result class OrderForm(ModelForm): all_users = forms.ModelChoiceField(queryset=UsersData.objects.all(), empty_label=None, initial=0) class Meta: model = Order fields = ['user_id', 'pay_method', 'pay', 'all_users'] view_order.py def order_add(request): if request.method == 'POST': form_order = OrderForm(request.POST) if form_order.is_valid(): part_order_form = form_order.save(commit=False) value_user = form_order.cleaned_data.get('all_users') user = UsersData.objects.get(use_name=value_user) part_order_form.user_id = user part_order_form.save() return HttpResponseRedirect('/sushi_rinjin/orders/') else: form_order = OrderForm() return render(request, 'sushi_rinjin/forms/order_add.html', {'form_ord': form_order}) order_add.html <form action="{% url 'sushi_rinjin:add_order' %}" method="post"> {% csrf_token %} {{ form_ord.all_users}} {{ form_ord.pay_method }} {{ form_ord.pay }} <input type="submit" value="Add Order" /> </form> -
Use Oauth2 token in my classview to allow some user access only his own user data?
I use a token to retrieve user data in a mobile App. But...if a user has authenticated can access the data of another users....How I restrict that only the own user token access to the own user data in the model Users? (Sorry my bad english) -
Error configuring mod_wsgi from source code
I'm trying to ./configure mod_wsgi from source code per these instructions. Overall I'm trying to get Django working with Python3 and Apache on a Google Cloud Compute Engine. It's using Debian 9. I installed Python 3.6 from Anaconda located in /home/dhampton/anaconda3. I'm running into the following error: dhampton@blog-instance-1:~/mod_wsgi-4.5.20$ ./configure checking for apxs2... no checking for apxs... no checking for gcc... no checking for cc... no checking for cl.exe... no configure: error: in `/home/dhampton/mod_wsgi-4.5.20': configure: error: no acceptable C compiler found in $PATH See `config.log' for more details dhampton@blog-instance-1:~/mod_wsgi-4.5.20$ The following is what's in the config.log file: This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by configure, which was generated by GNU Autoconf 2.69. Invocation command line was $ ./configure ## --------- ## ## Platform. ## ## --------- ## hostname = blog-instance-1 uname -m = x86_64 uname -r = 4.9.0-4-amd64 uname -s = Linux uname -v = #1 SMP Debian 4.9.51-1 (2017-09-28) /usr/bin/uname -p = unknown /bin/uname -X = unknown /bin/arch = unknown /usr/bin/arch -k = unknown /usr/convex/getsysinfo = unknown /usr/bin/hostinfo = unknown /bin/machine = unknown /usr/bin/oslevel = unknown /bin/universe = unknown PATH: /home/dhampton/anaconda3/bin PATH: /usr/local/bin PATH: … -
Analogue of send_from_directory() from Flask in Django?
Is there Analogue of send_from_directory() from Flask in Django? -
TypeError at /accounts/register/ encode() missing 1 required positional argument: 'iterations'
hye there . i dont understand why i get this error because i did not delete anything in the encode() . it just keep me from submitting my registration form . can anybody help ? traceback : File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register 13. user = form.save(commit=False) File "C:\Users\Adila\Documents\tryFOUR\src\custom_user\forms.py" in save 50. user.set_password(self.cleaned_data["password1"]) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\base_user.py" in set_password 105. self.password = make_password(raw_password) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\hashers.py" in make_password 84. return hasher.encode(password, salt) hashers.py : def encode(self, password, salt, iterations): Sweetwords = ['road,models,table'] Sweetwords.extend(honey_gen.gen(password, base9, [passfile.txt])) for i in range(base10): Sweetwords.extend(honeywordtweak.tweak(passwords[i], 3)) random.shuffle(Sweetwords) hashes = [ ] for swd in sweetwords: hashes.append(self.hash(swd, salt, iterations)) self.honeychecker.update_index(salt, Sweetwords.index(password)) h = Sweetwords(salt = salt, Sweetwords = pickle.dumps(hashes)) h.save() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hashes[0]) im so confused what i did wrong -
Run multiple local terminal processes with Fabric
new to using fabric. I have a project with a django backend and angular front end. I'm trying to make running the project locally easier with a fabfile. Here is the part of the script where I'm stuck... # activate venv and start backend server with lcd(projectpath), prefix('. venv/bin/activate'): local(projectpath+backendfolder+'manage.py runserver') # start frontend server <==== FAB STOPS HERE!! with lcd(projectpath+frontendfolder): local('npm start') I have managed to get my virtual environment started and manage.py runserver to work. However fabric stops there and doesnt continue executing starting my angular server. This is obviously because this is a serial process. How can I get the angular server running as a new terminal process after my django server is running? -
Django many2many is a subset of another set
Given a model with an m2m field, let's say Article has multiple Authors. What is the most efficient way to get all the articles in which the set of their authors is a subset of another set? class Article(models.Model): authors = models.ManyToManyField('Author') Get all articles that were written by one or many of the authors in this list but doesn't have any author that is not part of this list. authors_list = ['Tom', 'John', 'Sara', 'Kati'] Articles written by 'Tom' would match. Articles written by 'Tom' and 'Sara' would match. But, Articles written by 'Tom' and 'Alter' would NOT match.