Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - get file from db by its url
I am trying to implement a secure access to files. This is my view serving static files: class ServeStatic(LoginRequiredMixin, View): login_url = reverse_lazy("login") def dispatch(self, request, *args, **kwargs): if request.user == Document.objects.get(url=self.kwargs["path"]).owner: return serve(request, kwargs["path"], kwargs["file_root"]) else: return HttpResponseNotFound() The point is that I cannot get the condition to work. Is it even possible to get a file by its URL, or I need to choose a very different approach of serving files? Thanks for your ideas! -
twitter-like PUSH / data stream server side implementation?
I'm trying to implement a live data stream feature (similar to Twitter's stream API) into a django 1.9 web app that I've made. After looking at the streaming portions of Python-Twitter library in Python, in twitter/api.py, I had a couple of questions about how the server-side of this implementation works. It seems that the stream request is a just a normal GET/POST request to a normal URL. However, this URL sends asynchronous data back to the client. It doesn't appear that there is any kind of persistent connection between this API and the twitter stream servers. Ie, no tcp socket, no WebSocket, nothing like that. I've tried using StreamingHttpResponse but that seems to just build a queue of data to be flushed all at once to the client instead of piece-wise. I've gotten this to work over typical tcp sockets, but this needs to work in a very similar fashion to the Python-Twitter library. If someone were to try to recreate something like this (in Python), how would they? This seems like black magic to me at this point. Is there a way to just send HTTP data back to a client over and over again without requiring a new … -
How to retrieve a GET variable with a hash in it
I have the following variable that is passed in a url: http://localhost:8000/diff/?Platform=Comcast&PlatformID=7066191365225244112#S8 I need to be able to extract the following: Platform = Comcast PlatformID = 7066191365225244112#S8 However, django will escape the hash in the request.GET dictionary. Here is what it shows: GET:<QueryDict: {u'PlatformID': [u'7066191365225244112'], u'Platform': [u'Comcast']}>, How would I capture the full variable here, including the #S8 at the end? -
hidden input got chunked after space
Here's my use case: I've a hidden input like this: {% block content %} <form method= "post" action ="/new_stuff/"> <input type = "hidden" name = "myinput" id="myinput" value ={{myinputvalue}}></input> </form> {% endblock %} in this html page, the myinputvalue value was correct: AB CD, however, when I submit this form, this myinputvalue value got chunked after space, it became AB, I'm confused why this happens, thanks a lot! Thanks a lot. -
wsgi_mod dosn't serve admin static files
I know that there is few topic with this problem, but I still cannot resolve it. I have this structure /home /server /server_1 /static Static was generated by collectstatic and I have there all my staticfiles (include admin/css) Alias for static files in apach conifg look like: Alias /static/ /home/server/server_1/static/ <Directory /home/server/server_1/static/> Require all granted </Directory> When I'm running django admin page I can see login panel but without css but If i I click 'show page source' I can see <link rel="stylesheet" type="text/css" href="/static/admin/css/base.css" /> And I can click, and I can see whole css code (no 404 error) So, server can see this file? But it can use it or what? When I'm trying open: http://www.my.server.com/static/ I'm getting Forbidden You don't have permission to access /static/ on this server. I have STATIC_ROOT, and STATIC_URL, I can correctly run collectstatif, but server has some problem with render it. -
My Django Project isn't loading Bootstrap glyphicons
When I load my page I got the following messages in my terminal: Not Found: /fonts/glyphicons-halflings-regular.woff2 [24/Aug/2016 17:19:36] "GET /fonts/glyphicons-halflings-regular.woff2 HTTP/1.1" 404 2238 Not Found: /fonts/glyphicons-halflings-regular.woff [24/Aug/2016 17:19:36] "GET /fonts/glyphicons-halflings-regular.woff HTTP/1.1" 404 2235 Not Found: /fonts/glyphicons-halflings-regular.ttf My home_page code where I load this glyphicon is above: {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'bootstrapmin.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" /> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <a class="navbar-brand" href=""> <span class="glyphicon glyphicon-log-out" aria-hidden="true"></span>&nbsp <button class="btn-link" type="button"> OntoLogica</button> </a> </div> </nav> My bootstrap files are in: My Project Folder static Folder bootstrapmin.css style.css fonts Folder Here are the files that the Django couldn't find What I've tried to do: Move the files of the fonts Folder to the same path of the bootstrap Move the fonts folder outside the static folder. If you need any information I didn't provide, please ask and I will. Guys, what is wrong? Thanks in advance for any help! -
how to access uploaded file list in django forms.py
how can i in Django access uploaded file list (multi file upload) in forms.py. In a view i access file list like this : request.FILES.getlist('files') but in forms.py i get this error: Exception Value: 'UploadForm' object has no attribute 'request' i tried solution in this address but i get error when using this code : def clean_files(self): data = self.request.FILES error: Exception Value: 'NoneType' object has no attribute 'FILES' -
Django aggregate queried instances of foreign key
I have the following models: class Order(models.Model): some fields class OrderStatus(models.Model): order = models.ForiegnKey(Order) status = models.CharField(choices=['ORDERED', 'RECEIVED']) time = models.DateTimeField() Using Django ORM, How do I aggregate (average) turn-around-times (TAT) into a single timespan? For example (pseudo-code): Order0 (TAT=12 hours) OrderStatus0: order=Order0, status=ORDERED, time=00:00 8/24/16 OrderStatus1: order=Order0, status=RECEIVED, time=12:00 8/24/16 Order1 (TAT=24 hours) OrderStatus2: order=Order1, status=ORDERED, time=04:00 8/24/16 OrderStatus3: order=Order1, status=RECEIVED, time=04:00 8/25/16 Average TAT = 18 hours Pseudo-SQL would look like this: Order tat = Average Subtract OrderStatus.status_time where status=RECEIVED OrderStatus.status_time where status=ORDERED I have tried using a combination of Aggregate(), Annotate(), F(), Q(), When, and Case, but can't reach a solution because I need to need to query OrderStatus inside of the aggregation. Here is a non-working attempt: Order.objects.aggregate( Avg( F('order__orderstatus__status_time') - F('order__orderstatus__status_time'))) FYI, I'm using Django 1.9 and Postgresql 9.3 -
How can I override choices of abstract class?
I have AbstractProfile model with predefined PRIVACY_CHOICES: class AbstractProfile(models.Model): PRIVACY_CHOICES = ( (1, _('all')), (2, _('no one')), ) title = models.CharField(_('title'), max_length=30) info = models.TextField(_('information'), max_length=500, blank=True) info_privacy = models.IntegerField(_('show information to'), default=1, choices=PRIVACY_CHOICES) city = models.CharField(_('location'), max_length=30, blank=True) city_privacy = models.IntegerField(_('show location to'), default=1, choices=PRIVACY_CHOICES) address = models.CharField(_('address'), max_length=30, blank=True) address_privacy = models.IntegerField(_('show address to'), default=1, choices=PRIVACY_CHOICES) class Meta: abstract = True class UserProfile(AbstractProfile): PRIVACY_CHOICES = ( (1, _('all')), (2, _('friends')), (3, _('friends of friends')), (4, _('only me')), ) title = None first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) names_privacy = models.IntegerField(_('show names to'), default=1, choices=PRIVACY_CHOICES) birth_date = models.DateField(_('birth date'), null=True, blank=True) birth_date_privacy = models.IntegerField(_('show birth date to'), default=1, choices=PRIVACY_CHOICES) avatar = models.ImageField(upload_to='users/avatar', null=True, blank=True) class CompanyProfile(AbstractProfile): avatar = models.ImageField(upload_to='comanies/avatar', null=True, blank=True) UserProfile should have fields from AbstractProfile, but with its own PRIVACY_CHOICES. In the current realisation PRIVACY_CHOICES of UserProfile does not override PRIVACY_CHOICES of AbstractProfile. How is it possible to solve? In the future could be other models, which also should have its own PRIVACY_CHOICES I use Django 1.10 -
How to make Django rest_framework Session Authentication case insensitive?
I'm using Django rest framework basic authentication with the following code: class MyBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class AuthView(APIView): authentication_classes = (MyBasicAuthentication,) serializer_class = UserSerializer def post(self, request, *args, **kwargs): user = authenticate(username=request.user.username, password=request.user.password) login(request, user) response = get_user_basic_info(request.user) return Response(response) It is working fine, but I need to make this authentication case insensitive for the username. Any suggestions? -
django form add new rows upon changing to edit
Here's my use case: I'd like to display the information about something first using django_tables2, with a button on the top right corner called "Edit", once a user hits "Edit", at the bottom of the table, display a button called "Add New Record", and once the user clicks that button, a bunch of input fields pop up to let users enter values for each field, also the user could continue to click "Add new Record" to keep adding new. How can I achieve this in Django? I've read a lot of examples on stackoverflow but didn't find anything tailored to this particular case. Thanks a lot. -
Tivix - angular-django-registration-auth with Ionic?
I'm trying to create a user registration with Ionic and I installed Tivix's django backend, and the angular-django in eh front end. The thing is, I'm trying to incorporate it into Ionic. Here's my app structure in Visual Studio in my index.hml i have included the files I'm just having trouble understanding since how would I include the app "angularDjangoRegistrationAuthApp" into my index.html? I tried doing this in my index.html file. but when I click Sign Up button nothing happens. If anyone has ever worked with Tivix's module before and can poit me in the right direction, it would help allot. -
How to read Certification details in django Request Object?
We are trying integrate with Azure store. Azure store calls our API(built in django restframework) and along with request payload they send Certification details in request. But, I cannot see the certification details (X509Certificate) in Django request Header, body, cookies or session. Can any one help me on ways or location to read the X509Certificate2 certificate sent by Azure in Django request object ? -
Django test server and development server intermittently having trouble retrieving external resources
I recently noticed that functional tests using selenium in the test suite for my Django app will sometimes fail (timeout). When this happens, it is seemingly random which tests will fail; on one run test A will fail, on the next run test B will fail and A will pass. However, it seems like what usually fails is calls to outside web services (Google Maps API calls), or loading external libraries (loading Font Awesome or Bootstrap through a CDN) - selenium will timeout waiting for these resources to load. When this happens, running the site locally with the development server (./manage.py runserver) will usually be slower than usual (i.e., some pages will load much slower than usual, or will fail to load altogether). My suspicion is that some sort of network traffic on my computer is blocking or slowing down Django's development and test server, like another process is using/trying to use the same port or something of that nature. At one point when this issue was particularly bad, I realized I was trying to upload a ~1GB file to dropbox on the same machine. When I stopped this process my test suite and development server both started to run … -
django query parameter with space
I've a url that takes query parameters that might have spaces in them, I know it looks pretty simple, but my regex is not working for me. Here's my URL: url(r'^item_info_details_view/(?P<itemno>[\w \/&-]+)/$', 'purchasing.views.item_info_details_view'), My itemno could be a word like this FAX MODEM which contains a space However, when I pass such a parameter to it, the url in my browser is http://localhost/item_info_details_view/FAX%20MODEM/ And displays this debugging info: Using the URLconf defined in urls, Django tried these URL patterns, in this order: ^$ The current URL, item_info/FAX MODEM/, didn't match any of these. Any help is really appreciated! -
Hard Coded Baseline Data - practices post-fixture?
So, I have a Django app which needs to have some hard coded baseline data loaded into the database reliably. Previously (pre 1.8), I'd have done this with JSON fixtures and loaded them via loaddata. However, things have changed with data migrations, and I was keen to find out what the best approach for this behaviour is now. The options are: class Migration(migrations.Migration): initial = True dependencies = [ ('yourappname', '0001_initial'), ] def loadfixture(apps, schema_editor): call_command('loaddata', 'initial_data.json') operations = [ migrations.RunPython(loadfixture), ] Which appears to just rely on old behaviour (is loaddata deprecated?) Or do I write a similar setup myself, creating objects from a serialized JSON file manually? -
How to make Django button appear with javascript?
This is my code: {% block title %}Chart{% endblock title %} {% block content %} {% next_button %} {% endblock %} {% block scripts %} <script>//scripts<script> {% endblock %} I would like to make {% next_button %} disappear with javascript. -
Specifying values to select from/queryset to a modelform field dynamically
I have a model like class Lecture(models.Model): teacherCourse = models.ForeignKey(TeacherCourse, verbose_name = "teacher course combination") topicTaught = models.CharField("topic taught / reason, if not conducted", max_length=255) enteredOn = models.DateTimeField(auto_now = True, null=True) students = models.ManyToManyField(Student, verbose_name='students absent') def __str__(self): return self.pk I'm creating following modelform for this model. class addLectForm(ModelForm): class Meta: model = Lecture widgets = { 'students': forms.CheckboxSelectMultiple, } def __init__(self, corsList, *args, **kwargs): super(addLectForm, self).__init__(*args, **kwargs) self.corsList = corsList self.fields['teacherCourse'].queryset=self.corsList User is expected to select the teacherCourse first and then I want to list checkboxes for selecting only the students who were absent for that lecture. An ajax call like this : var csrftoken = getCookie('csrftoken'); $("#id_teacherCourse").change(function(){ var v = $("#id_teacherCourse").val(); $.ajax({ url : "/college/addLect/", method:"POST", dataType: "json", data: {vlue: v, csrfmiddlewaretoken: csrftoken}, success: function(result){ var data = new Array(); var i = 0; tableContent = '<h3><center>Mark the roll numbers of absent students</center></h3><div class="table-responsive"><table class="table table-bordered"><tbody><tr>' var x = 'a' for(i=0;i<result.length;i++){ x = result[i].fields.rollno tableContent += '<td style="display: table-cell; text-align:center; vertical-align:middle;">' + '<label>'+ x.toString() +' <input type="checkbox" id="'+ i.toString() +'" name=present[] value="'+x+'"/></label></td>' ; if((i+1)%10 == 0){ tableContent += '</tr><tr>'; } } for(var j=0;j<10-i%10;j++){ tableContent += '<td></td>'; } tableContent += '</tr></tbody></table></div>'; $("#forabsenty").html(tableContent); alert(result); } }) is creating the list … -
How can I use heroku for creating a python django web application?
I'm new to Heroku. I need to create a web application using python-django framework. Which tutorial is better for reference? And also I can't able to install the heroku toolbelt and I can't able to login to heroku account through terminal in linux. When I'm trying to login heroku: command not found error will be appear. Which tutorial is best for doing a python-django web application through heroku. -
How to allocate a Python (Django) project in a ready and configured server? (Apache, MySQL, Python, Django OK)
I have a ready and fully configured server. Python, Django, Apache, MySQL, all OK. I would like to replicate an existing project on this server for testing. The files and database are already replicated, however, to access the project folder via browser it back directories without interpreting the code in Python, as below: cgi-bin/ robots.txt wsgi.py Apache/2.2.29 (Unix) mod_ssl/2.2.29 OpenSSL/1.0.1e-fips mod_wsgi/3.5 Python/2.7.9 mod_bwlimited/1.4 Server at test.xxxxxx.com.br Port 80 -
Creating a django form which also uses database data as an option
My question title isn't very good but what I am trying to create is a way to add students into a database table and in the same form add their parents details into another table. The problem arises where 2 students have the same parents and I now have two sets of the same parent. Is there a way to select parent from the parent table when I am entering a student? How would I go about doing this. -
Django tables2 not rendering properly
I'm following the example on https://django-tables2.readthedocs.io/en/latest/pages/table-data.html#querysets The example shown at above site doesn't work properly for me. Please see my code below. The table is displayed but not rendered properly. Instead of using PersonsTable(), if I use the objects collection, table is rendered properly. The PersonsTable() is from the above page, as is. I'd like to be able to use PersonsTable()'s fields to filter displayed columns and get the nice formatting from django-tables2... Thanks in advance. My code: def person_list(request): #table = PersonsTable(Person.objects.all()) # this is from example, table is rendered plainly w/o any formatting present or up/down arrows table = Person.objects.all() # rendering works return render(request, 'person_list.html', {'table': table}) -
no access control allow origin header is present on the requested resource
I know this question has been asked before by many SO user but my problem is still unsolved. I am using axios and i am not getting any solution regarding axios. In superagent res.header('Access-Control-Allow-Origin', '*'); works but how can i resolve this issue in axios? my axios code for posting review is onSubmit(props){ console.log('csrf',CSRF_TOKEN); axios({ method:'POST', url:'http://192.168.1.103:8000/api/review/create/?type=restaurant&slug=kathmandu-fast-food-center', headers:{ 'X-CSRF-Token':CSRF_TOKEN, 'Accept': 'application/json', 'Content-Type': 'application/json', }, data:{ review:props.review } }) .then(response => { console.log('success'); }) .catch(error => { throw("Error: ",error); }); } api/Views.py class ReviewCreateAPIView(CreateAPIView): queryset = Review.objects.all() # permisssion_classes = [IsAuthenticated] def get_serializer_class(self): model_type = self.request.GET.get('type') slug = self.request.GET.get('slug') parent_id = self.request.GET.get('parent_id') return create_review_serializer(model_type=model_type, slug=slug, parent_id=parent_id, reviewer=self.request.user) def perform_create(self, serializer): print('serializer',serializer) print('self',self) print('self.request',self.request.user) serializer.save(reviewer=self.request.user) @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(ReviewCreateAPIView, self).dispatch(request, *args, **kwargs) -
In Django, how to code else statement to reload same page and trigger error message pop-up?
I am writing a Django view that should allow users to export selected records to Excel by selecting the records they'd like to export, then clicking an Export button on the Django Admin change list page. I have an if/else statement for this and I'd like my else: to basically reload the same change list page, but trigger a popup window error message if the user clicks "Export" without having selected any records to export. Something like "No records selected to export. Please try again." How would I accomplish this? TIA! -
Filter in template to arrange data specifically in django
How can I use a filter in my template to put the values in a row where the key matches. So for example all values in Inner OD key row 1 should have values for that key then in row two the should have all values of Outter OD key for row 2 values. Any help would be greatly appreciated Here is my view.py @login_required def shipping(request, id): sheet_data = Sheet.objects.get(pk=id) work_order = sheet_data.work_order customer_data = Customer.objects.get(id=sheet_data.customer_id) customer_name = customer_data.customer_name title_head = 'Shipping-%s' % sheet_data.work_order complete_data = Sheet.objects.raw("""select s.id, d.id d_id, s.work_order, d.target, i.reading, d.description, i.serial_number from app_sheet s left join app_dimension d on s.id = d.sheet_id left join app_inspection_vals i on d.id = i.dimension_id""") for c_d in complete_data: dim_description = Dimension.objects.filter(sheet_id=c_d.id).values_list('description', flat=True).distinct() dim_id = Dimension.objects.filter(sheet_id=c_d.id)[:1] for d_i in dim_id: dim_data = Inspection_vals.objects.filter(dimension_id=d_i.id) reading_data = Inspection_vals.objects.filter(dimension_id=d_i.id) key_list = [] vals_list = [] for xr in complete_data: key_list.append(xr.description) vals_list.append(xr.reading) #print reading_desc sample_size = dim_data res = {} for i in range(len(key_list)): if key_list[i] in res: res[key_list[i]].append(vals_list[i]) else: res[key_list[i]]=[vals_list[i]] reading_desc = res return render(request, 'app/shipping.html', { 'work_order': work_order, 'sample_size': sample_size, 'customer_name': customer_name, 'title': title_head, 'complete_data': complete_data, 'dim_description': dim_description, 'reading_desc': reading_desc, }) here is the output of reading_desc that correctly uses the correct …