Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
@csrf_protect in django services
I'm trying to use @csrf_protect in my services by following Cross Site Request Forgery protection article but it is not working for me. This is my settings file MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'CB_Core_App.customMiddleWare.middleWare.IPValidationMiddleWare', ] and this is how I'm Acquiring the token var csrftoken = Cookies.get('csrftoken'); And this is how I'm configuring the $http provider with the cookie and header names: $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; But when I call any service, it returns 403 forbidden error. Any Idea what I'm missing or doing wrong? Any kind of help will be appreciated. -
How to add description to Django command?
In argparse, the description is passed into the ArgumentParser ctor like so: import argparse parser = argparse.ArgumentParser(description="Print a number") parser.add_argument('-n', dest='number', action='store', type=str, help="The number to be printed") args = parser.parse_args() When doing a similar thing using a Django command, how does one add the description="Print a number" given that the ArgumentParser has already been constructed? from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-n', dest='number', action='store', type=str, help="The number to be printed") -
Django reserve foreign key in views
I have a reverse query in a template that working on two tables connected together with Foreign Key. That query is giving result what I want for now but in the future, it is clear will cause me serious problems about query optimization. I am sending the query to the database for all pictures related with the table that I am working with than I am showing only one of them. I cannot adapt to the view function the reverse query that I wrote in HTML template. Here are my working codes: in models.py class EtkinlikModel(models.Model): ... class FotografModel(models.Model): etkinlik = models.ForeignKey(EtkinlikModel, on_delete=models.CASCADE) in views.py def EtkinlikView(request): etkinlikler = EtkinlikModel.objects.all().order_by("-olusturulma_tarihi")[:4] template = “…” context = { "pageName": title, "etkinlikler" : etkinlikler } return render(request,template,context) in template.html {% for etkinlik in etkinlikler %} {{ etkinlik.etkinlik_adi }} {% for foto in etkinlik.fotografmodel_set.all|slice:":1" %} {{ foto.foto }} {% endfor %} {% endfor %} codes for decreasing query loads views.py def EtkinlikView(request): etkinlikler = EtkinlikModel.objects.all().order_by("-olusturulma_tarihi")[:4] for etkinlik in etkinlikler: foto = etkinlik.fotografmodel_set.all() template = “…” context = { "pageName": title, "etkinlikler" : etkinlikler, "foto":foto } return render(request,template,context) in template.html {% for etkinlik in etkinlikler %} {{ etkinlik.etkinlik_adi }} {{ etkinlik.id }} {% for f … -
How to hide admin users from django admin site
By default django admin shows all users on the admin site. I am working on a app where client wants to show only that users which are registered from mobile or web, not admin users. How to apply query on django admin site for this? Please help. Thanks in advance. def queryset(self, request): if not request.user.is_superuser: return User.objects.all() return User.objects.filter(is_superuser=False) -
Check if an object is a QuerySet
I have an object variable obj. Is it possible to check whether its a Queryset or not? (Couldn't find any posts on this on searching) -
How can logger.removeHandler(logger.handlers[0]) throw ValueError: list.remove(x): x not in list?
I'm trying to debug an exception in someone else's Python code, and I am not an expert in Python. The code tries to flush and remove all handlers on a standard Python Logger: def restart_logging(logger_id): logger = logging.getLogger(logger_id) while logger.handlers: handler = logger.handlers[0] handler.flush() logger.removeHandler(handler) init_logging(logger_id) This raises an exception: File "/usr/lib64/python2.6/logging/__init__.py", line 1208, in removeHandler self.handlers.remove(hdlr) ValueError: list.remove(x): x not in list I've reviewed StackOverflow's other "x not in list" questions, and they all fit in these two categories: removing the same item more than once (usually because of doing for x in list: list.remove(x) rather than while list: list.remove(list[0])) remove an item that was never in the list I don't see how either applies here. Firstly, a while loop is used: while there are still handlers, take the first one (which succeeds or there'd be an IndexError), flush it, remove it. Even if that removed more than one entry in the list, it's a while loop testing if the list still has entries, not a for loop iterating over (potentially removed) objects. Looking at the logging module source, it only calls remove() once, and it even checks the handler is in the list immediately before calling remove(): def … -
Reorder Django QuerySet by dynamically added field
A have piece of code, which fetches some QuerySet from DB and then appends new calculated field to every object in the Query Set. It's not an option to add this field via annotation (because it's legacy and because this calculation based on another already pre-fetched data). Like this: from django.db import models class Human(models.Model): name = models.CharField() surname = models.CharField() def calculate_new_field(s): return len(s.name)*42 people = Human.objects.filter(id__in=[1,2,3,4,5]) for s in people: s.new_column = calculate_new_field(s) # people.somehow_reorder(new_order_by=new_column) So now all people in QuerySet have a new column. And I want order these objects by new_column field. order_by() will not work obviously, since it is a database option. I understand thatI can pass them as a sorted list, but there is a lot of templates and other logic, which expect from this object QuerySet-like inteface with it's methods and so on. So question is: is there some not very bad and dirty way to reorder existing QuerySet by dinamically added field or create new QuerySet-like object with this data? I believe I'm not the only one who faced this problem and it's already solved with django. But I can't find anything (except for adding third-party libs, and this is not an … -
msi creation needs using cx_freeze in python
Suppose, I have written a code in python 2.7 . let's say i am using vlc player in my script and now i have created a msi file for my code so how to install "vlc player" in user's system during installation of msi file of my python code. Please give the example of setup file of cx_freeze package which installs all the dependent softweare (like VLC) in the user's system during installation of msi of python code. I just want to know where to add these dependencies (for installation) in setup file of cx_freeze. -
How to remove an object from another object in django? - python
I have a queryset that created by Profile.objects.all(). I want to print it in template except just one of its rows. How can I do it in template? or if it's not possible in template, how can I do it in view? -
Django: How to show user owned data in Admin forms
Following are the models of my app: class Store(models.Model): store_owner = models.ForeignKey(User, null=False, verbose_name='User') store_name = models.CharField(max_length=200, null=False, verbose_name='Store name') store_address_line_1 = models.CharField(max_length=200, null=False, verbose_name='Address line 1') store_address_line_2 = models.CharField(max_length=200, null=False, verbose_name='Address line 2') store_city = models.CharField(max_length=200, null=False, verbose_name='City') store_state = models.CharField(max_length=200, null=False, verbose_name='State') store_zip_code = models.CharField(max_length=200, null=False, verbose_name='Zip/Pin Code') store_country = models.CharField(max_length=200, null=False, verbose_name='Country') store_phone = models.CharField(max_length=12, verbose_name='Phone') store_email = models.EmailField(verbose_name='Email') store_website = models.URLField(verbose_name='Website') class StoreDepartment(models.Model): store = models.ForeignKey(Store, verbose_name='Store') department_name = models.CharField(max_length=200, null=False, verbose_name='Department name') department_description = models.TextField(max_length=250, null=False, verbose_name='Description') +++++++++ I am using only the dfault Admin provided by django framwork. I have 2 users, For both users I have created Stores. But when I try to create StoreDepartment, I see the list of all the stores in the Select box created for "Store" foreign-key field in StoreDepartment model. How to customize the default form so that user can see only the Stores created by them in the selectbox. -
Why I can't get the custom header from Django request.META
When use .\curl.exe -v -H 'HTTP_TEST:A17041708' http://127.0.0.1:8000/api/test open the url. I print the request.META,but i can't find my custom header in it -
Can we use Django signals on cassandra models
Please someone help me on how to use Django-signals on Cassandra models? I want to migrate my table(A) to table(B),so best solution i came up is to write django signals on old table and update new one.As old tables are being updated from multiple servers. -
Basic Django form response
I am new to Django and looking to build a quick form with a response. I am trying to build a form which would ask the user to input his name when the user clicks submit the page should reload and just say "Hello . urls.py class Question1Form(forms.Form): n = forms.CharField(max_length=100, widget=forms.TextInput( attrs={'placeholder': 'Number', 'class': 'form-control'})) views.py def home(request): if request.method == 'POST': form = Question1Form(request.POST) if form.is_valid(): result = [Question1Form.ans()] return HttpResponse(Question1Form.n) else: form = Question1Form() return render(request, 'index.html', {'form': form}) index.html <form action="" method="post" class="form"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row form"> <div class="col-sm-4"> {{ form.n.errors }} {{ form.n }} </div> <input class="btn btn-primary" type="submit" value="Submit" /> </div> </form> So how the code s -
How can I check model's data is connected accurately?
I wanna check whether model's data is connected accurately or not. models.py is class User(models.Model): trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regist_date = models.DateTimeField(auto_now=True) user_id = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area',null=True, blank=True) class Area(models.Model): name = models.CharField(max_length=20, verbose_name='Area', null=True) class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='Prefecture') area = models.ForeignKey('Area', null=True, blank=True) class City(models.Model): name = models.CharField(max_length=20, verbose_name='City') prefecture = models.ForeignKey('Prefecture', null=True, blank=True) class Price(models.Model): upper1000 = models.CharField(max_length=20, verbose_name='u1000', null=True) from500to1000 = models.CharField(max_length=20, verbose_name='500~1000', null=True) under500 = models.CharField(max_length=20, verbose_name='d500', null=True) city = models.ForeignKey('City', null=True, blank=True) Model's data means Area&Prefecture&City&Price,so I wanna know these data is connected accurately with User.How can I check this?I cannot find it to see db.sqlite3 by using DB Browser for SQLite .How can I print the answer in terminal? -
Create Word Document and then Attach it to Email Django
I'm currently using python_docx in order to create Word Documents in Python. What I'm trying to achieve is that I need to create Document File in Django and then attach it to an email using django.core.mail without having to save the file on the server. I've tried creating the Word File using this (taken from an answer also within StackOverflow): def generate(self, title, content): document = Document() docx_title=title document.add_paragraph(content) f = BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response And then here is where I experimented and tried to attach the response to the email: def sendmail(self, name,email,description,location): message = EmailMessage('Custom Mail', 'Name: '+str(name)+'\nEmail: '+str(email)+'\nDescription: '+str(description)+'\nLocation: '+str(location), 'test@gmail.com',to=['testreceiver@gmail.com']) docattachment = generate('Test','CONTENT') message.attach(docattachment.name,docattachment.read,docattachment.content_type) message.send() Is what I'm trying to achieve even possible? -
What do I have to do for the continuous conversation of watson chatbot?
I want to have a continuous conversation with watson chatbot. current situation : The chatbox does not remember the status of the conversation you previously sent. I installed the Django framework on the server and created a watson.py file to load the workspace and work with KakaoTalk, a Korean chat application. The chatbot's conversation flow that I want is as follows. User: I want to make a reservation Chatbot: When is the meeting date? User: tomorrow Chatbot: How is your meeting time? User: 14:00 We need your help very much. watson.py import json from watson_developer_cloud import ConversationV1 from .models import Test from . import views import simplejson conversation = ConversationV1( username = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxxxxxxxxxxx", version = '2017-05-26' ) workspace_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' #workspace def test(return_str): result = '' except Exception as err: pass response = conversation.message( workspace_id = workspace_id, message_input = {'text': return_str}, ) for i in range(len(response['output']['text'])): result += response['output']['text'][i] +'\n' return result views.py import json from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import Jidum, Test from . import watson # Create your views here. def keyboard(request): return JsonResponse({ 'type':'text', }) @csrf_exempt def message(request): message = ((request.body).decode('utf-8')) return_json_str = json.loads(message) return_str … -
Django asset manager for Views or template tags?
I come to Django having used the Yii2 PHP framework. One of the good features about that is it allows you to create asset files for CSS and JS which are then loaded into the base layout file at runtime. This allows you to keep the base template clean of CSS and JS markup within the head and at the bottom of the HTML document. The CSS and JS files you specify in the asset file are automatically placed in the correct position in the document and you can also specify dependencies if needed. At the moment, with Django I am having to edit the base.html file manually which is not ideal. I know you can use the Media class for forms, and in admin.py, which does a similar job. However, what I would like to do is to something like this (for example) in inclusion template tags or in a class based view perhaps. Is this possible? Many thanks! -
How to get session with suds-jurko
I'm trying to get the sessionID so I can do SOAP requests. To day I can do POST hardcoded requests. But I want to use Suds This is how I can do a POST hardcoded requests today: def GetSession(IP): request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' request = request + ' <soapenv:Body>' request = request + '<login>' request = request + '<UserName>username</UserName>' request = request + '<Password>password</Password>' request = request + '</login>' request = request + '</soapenv:Body>' request = request + '</soapenv:Envelope>' request = u"""""" + request + """""".format() encoded_request = request.encode('utf-8') headers = {"Host": ""+ IP +"", "Content-Type": "text/xml; charset=UTF-8", "Content-Length": str(len(encoded_request)), "SOAPAction": ""} response = requests.post(url="http://"+ url +"/Service", headers=headers, data=encoded_request, verify=False) return response.content I have been trying to do the sessionID request this way. But with out any luck. def status(request): from suds.client import Client from suds.transport.http import HttpAuthenticated t = HttpAuthenticated(UserName='username', Password='password') url= 'http://ip.ip.ip.ip/Service?wsdl' client = Client(url) return HttpResponse(client) I don't know if I'm doing this correctly. In the hardcoded example, I have the login, username and password in the body. And not sure if that is the same way as HttpAuthenticate? Help much appreciated =) -
Webpack TypeScript and xgettext translations
I have a Django app and am using Django's i18n module to help translating my strings. For translating JavaScript, I run python manage.py makemessages -d djangojs which adds all marked strings to a .po file. This works quite well for all my boring .js files in my static folder. However, we are starting to use webpack to pack some typescript (.tsx files) into a bundle.js file. This file is copied to the static folder after building, so I expected Djangos makemessages to pick up the strings from it as well. However, it seems that the strings are not parsed correctly, because most of the code in bundle.js is simply strings wrapped in eval(). I believe this means that I need webpack to - in addition to the bundle.js file - create a .js file for each .tsx file without all of the eval() nonsense, so that django's makemessages can parse it properly. I have no idea how to do this, however. My current config looks like this var path = require("path"); var WebpackShellPlugin = require('webpack-shell-plugin'); var config = { entry: ["./src/App.tsx"], output: { path: path.resolve(__dirname, "build"), filename: "bundle.js" }, devtool: 'source-map', resolve: { extensions: [".ts", ".tsx", ".js"] }, module: { … -
How can I pass the request if I redirect and then render the template
I have a requirement, from login page jump to the admin page, you know the URL address should change to the admin page. If I only use render to admin page, the URL address will not change, so in this post I get the OptimusCrime's good answer. But if I redirect and then render template, I can not pass the request from login page to the admin page. in the login page's views.py: ... return redirect('/app_admin/index/') in the admin page's views.py: ... return render(request, 'app_admin/index.html') # there the request is None. How can I pass the request to the admin page's views.py? -
Separate the values in dictionary into two column. Python and Django
I've one program which will read the data from text file. There is 3 type of data that I read from text file. 1.visual id 2.time 3.tname_pb Problem Supposed I have 3 column and separate the output with a different column. But, visual id is working perfectly, while time and tname_pb are combined together. CLICK HERE TO LOOK AT THE PICTURE Question How if I want to separate time output and tname_pb output into two different column. Current views.py based on the picture with open(path) as input_data: for line in input_data: if line.startswith('2_visualid_'): visual_key = line.lstrip('2_visualid_').rstrip() data.update({visual_key: []}) if 'time' in tokens: if search_time in line and visual_key in data: data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip()) if 'tname_pb' in tokens: if tname_pb in line and visual_key in data: data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip()) Current template based on the picture <div class="input-group" align="center" style=" left:10px; top:-110px; width:99%"> <table class="table table-bordered"> <thead class="success" > <tr> <th class="success"> <b>Visual ID</b> </th> <th class="success"> <b>Time Delay Index</b> </th> <th class="success"> <b>Tname PB</b> </th> </tr> {% for key, values in output.items %} <tr class=""> <td rowspan={{ values|length|add:1 }}><b>{{ key }}</b></td> {% for value in values %} <tr class=""> <td ><b>{{value}}</b></td> </tr> {% endfor %} </tr> {% endfor %} </thead> </table> </div> NOTE I have … -
Redirection issue using PK
I Have a very strange phenomenon In my app the user Create a project and is redirected to that project detail using its pk. On that project detail page he is asked to create a team and when the team is created he is redirected again to the project detail page but to the wrong pk for example: I just created a project and I got redirected to .../project/24. I was asked to create a team, I created it but got redirected to ../project/17 any idea why and how to redirect my page to the right URL ? model.py: class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk}) def __str__(self): return self.team_name class TeamMember(models.Model): user = models.ForeignKey(MyUser) team = models.ForeignKey(Team) def __str__(self): return self.user.first_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk}) def __str__(self): return self.name -
Edit list of pictures that has foreign key to model
I have the following two models: class Profile(AbstractUser, CommonInfo): ... pictures = models.ManyToManyField(Picture, blank=True) and class Picture(CommonInfo): picture = models.ImageField(upload_to='gallery/', blank=True, null=True) What is the best way to display those pictures in a custom template/form/view. I want to display them all and to delete several of them and add new. -
Simple Search Function in Django
I'm using Q lookup for simple search Functionality. Here's the code taken from view, if query: object_list = Post.objects.filter( Q(title__icontains=query) | Q(content__icontains=query) ).distinct() But I have another model "Question", I wants to filter out questions in the search as well along-with Post. How can I use Q lookup for 2 separate models i.e. 'Post' & 'Question' together in one variable i.e "object_list". Please help me with this code! -
user_logged_in signal with REMOTE_USER_BACKEND
i' m using AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.RemoteUserBackend'] which is coming from Apache2 (and ldap). It works well, however i' d like to set a session variable when the user logs is. I could use the from django.contrib.auth.signals import user_logged_in signal if it' d be an application side authentication, but is there any possibility to use it with REMOTE_USER ? How? Python: 3.4.2 Django: 1.9.2 .