Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I exclude a view from the API documentation?
I use django-rest-framework (DRF) to provide the REST API of a site of mine. From what I understand, the automatic generation of API documentation relies on DRF's generation of a schema. It may then be interpreted by a third-party tool to produce pretty documentation. I've used django-rest-swagger as the tool that produces the pretty documentation from DRF's schema, but I suspect the solution to my problem is DRF-based, independent of whatever tool I use to transform the schema to something "pretty". The problem is that by default, DRF provides documentation for the whole API, even though some parts of it are really for my sites own internal purpose. I'd like some views to be excluded from the documentation. Some views should always be excluded. Some views should be excluded only if the user viewing the documentation is not logged into the site. -
Django NoReverseMatch exception in django template
I have a problem with reverse in django, i've tryed different ways as in docs on different urls with the same result. For example: url: url(r'^(?P<year>[0-9]{4})/$', views.example, name='example'), view: def example(request, year): data = dict() books_year = Book.objects.filter(publication_date__year=year) data['books_year'] = books_year return render(request, 'example.html', data) example.html: {% if books_year %} {% for book in books_year %} <tr> <td> {{ book.title }} | {% for authors in book.authors.all %} {{ authors }} {% endfor %} | {{ book.publisher }} | {{ book.publication_date }} </td> </tr> <tr> <td> <a href="/2014/">2014 Archive</a> <a href="{% url 'example' 2014 %}">2014 Archive</a> <ul> {% for yearvar in year_list %} <li><a href="{% url 'example' yearvar %}">{{ yearvar }} Archive</a></li> {% endfor %} </ul> </td> </tr> {% endfor %} {% endif %} If i do it with this <a href="/2014/">2014 Archive</a> it works. If i try it with this <a href="{% url 'example' 2014 %}">2014 Archive</a> it gives me this error: django.urls.exceptions.NoReverseMatch: Reverse for 'example' with arguments '(2014,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] And finally when i'm trying like this: <ul> {% for yearvar in year_list %} <li><a href="{% url 'example' yearvar %}">{{ yearvar }} Archive</a></li> {% endfor %} </ul> The page runs … -
Document Serializer returns object instead of id while using listfield of referencefield
I am using django 1.5.11 for mongodb. Serializer.data is returning objects instead of id for all references given in listfield. My files are as follows: model.py: from django.db import models from rest_framework_mongoengine.serializers import DocumentSerializer from mongoengine.document import Document from mongoengine.fields import EmbeddedDocumentField,ListField,ReferenceField, StringField, ObjectIdField, IntField, BooleanField, FloatField, DateTimeField from mongoengine import connect, CASCADE from pymongo import ReadPreference connect('mydb16', username='admin', password='admin123') class Authors(Document): author_name = StringField(max_length=30) author_country = StringField(max_length=30) class Books(Document): author_id =ListField(ReferenceField('Authors',required = True)) #author_id =ReferenceField('Authors') title = StringField(max_length=30) Cost = IntField() serializer.py: from app.models import Authors from app.models import Books from rest_framework_mongoengine.serializers import DocumentSerializer from rest_framework import serializers class AuthorsSerializer(DocumentSerializer): class Meta: model = Authors def to_internal_value(self, data): return super(DocumentSerializer, self).to_internal_value(data) class BooksSerializer(DocumentSerializer): class Meta: model = Books def to_internal_value(self, data): return super(DocumentSerializer, self).to_internal_value(data) views.py from app.serializers import AuthorsSerializer from app.serializers import BooksSerializer from rest_framework import status from app.models import Authors from app.models import Books from rest_framework.views import APIView from rest_framework.response import Response class AuthorsList(APIView): def get(self,request,fromat=None): print "I am Authorlist get..." author = Authors.objects.all() serializer = AuthorsSerializer(author, many=True) print "\n\nserializers data: " , serializer.data, "\n\n" return Response(serializer.data) def post(self, request, format=None): print "I am Authorlist post" data = request.data print "\nData: ", data , "\n\n" serializer = AuthorsSerializer(data=data) … -
How to create a new table using model
So I have this django installation in which there are a bunch of migration scripts. They look like so: 00001_initial.py 00002_blah_blah.py 00003_bleh_bleh.py Now I know these are "database building" scripts which will take stuff defined in models.py and run them against the db to "create" tables and stuff. I want to create a new table(so I created its definition in models.py). For this, I have copied another model class and edited its name and fields and it is all fine. Lets call this new model class 'boom'. My question is now how do I "create" this boom table using the migration script and the boom model? I am worried that I might accidentally disrupt anything that is already in DB. How do I run the migration to create only boom table? How do I create a migration script specifically for it? I know that it has something to do with manage.py and running migrate or runmigration (or is it sqlmigrate?...im confused). While creating the boom table, I dont want the database to go boom if you know what I mean :) -
Cannot log in to PayPal sandbox
I am testing the payment for a subscription using the PayPal sandbox and for the last few days I have intermittently been unable to log in. However today, I can't log in at all. Nothing has changed with my IPN integration (my PayPal integration already works), I am simply testing confirmation emails on my side which have nothing to do with PayPal. I click the subscribe button on my site and get taken to the PayPal sandbox to login. I then try to login with the *-buyer test account and get the error: There is no more information. Nothing that I can work with to try and figure out what is going on. I also don't get any errors/feedback to my API. It just seems like the PayPal sandbox is down and not accepting logins for test payments. Once again, nothing has changed on my side. I am simply testing emails after a member signs up but I can't get to that point because I can't login to make the payment. -
How to get data from another app Django
I have a news platform and I want to pass some amount of articles links on the main page. As I understand there's no way just to pass it with {% for article in context %} loop cause it can't resolve from where to take "context" list. Found a way to do that with "templatetag", but maybe there's more elegant way? -
Compare returned difference of fields with a variable in django queryset
I am trying to list all objects of a model based on the difference of field values and a variable. For example I am trying to pull objects which has been created since 3 days or more. So I am trying to query the models as follows import datetime from myapp_books.models import Gift from django.db.models import F current_date = datetime.date.today() books = Book.objects.annotate(day_difference=F('date_added__date') - current_date).filter(day_difference__gte=3) books.count() This is giving me an error when I run it in the shell as follows AttributeError: 'ExpressionNode' object has no attribute 'lookup' Please advice. I am using django 1.5.12 -
Wagtail ModelAdmin inline?
I am using wagtails' ModelAdmin module ( not the same as Django ModelAdmin) to add a custom Order model to the wagtail admin. This model has a foreign key to a custom Address model. I would like to display the Address model as an inline (like in django's admin) in the InspectView (which I have enabled). Currently it displays the string representation. -
Django website appears to be broken- but only for me
I am responsible for maintaining a website that my company uses internally for the management of projects and purchasing materials from suppliers, etc. The website has been written in Python/ Django, and I have 'superuser' status. The way I am currently working is by fixing any bugs/ implementing any new features on my local machine, using Git to manage the versions/ releases. I am merging those bug fixes/ new features with my local master branch as and when a fix/ new feature is complete, testing everything locally, and then pushing master to origin/master on the server, and restarting the server to make it available on the live version at www.mysite.co.uk. This is the process I have followed since I first took on this project, and I've never had any inconsistencies with doing it this way (obviously other than problems/ bugs that I have accidentally introduced into the system- but the process has always remained the same and has always worked). I fixed a particular bug within the system yesterday, pushed my changes to the server & restarted the server, the same as usual. However, this morning, when trying to access the live site from www.mysite.co.uk, my browser displayed an error … -
djangocms: AttributeError: 'FileNotFoundError' object has no attribute 'cmd'
I am trying to install Django CMS on windows. I am using following steps. C:\Python34\Scripts\pip install djangocms-installer E:\Projects\example>C:\Python34\Scripts\djangocms -p mysite mysite But throws following error: Creating the project Please wait while I install dependencies ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "c:\python34\lib\site-packages\djangocms_installer\install\__init__.py", line 95, in requirements output = subprocess.check_output(['pip'] + args, stderr=subprocess.STDOUT) File "c:\python34\lib\subprocess.py", line 607, in check_output with Popen(*popenargs, stdout=PIPE, **kwargs) as process: File "c:\python34\lib\subprocess.py", line 859, in __init__ restore_signals, start_new_session) File "c:\python34\lib\subprocess.py", line 1114, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python34\lib\runpy.py", line 170, in _run_module_as_main "__main__", mod_spec) File "c:\python34\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Python34\Scripts\djangocms.exe\__main__.py", line 9, in <module> File "c:\python34\lib\site-packages\djangocms_installer\main.py", line 33, in execute verbose=config_data.verbose File "c:\python34\lib\site-packages\djangocms_installer\install\__init__.py", line 98, in requirements logger.error('cmd : %s :%s' % (e.cmd, e.output)) AttributeError: 'FileNotFoundError' object has no attribute 'cmd' I have searched on it but can't get any solution. -
EmailMessage to multiple users without seeing each other
How can I send message to multiple users without seeing each other? I use from django.core.mail import EmailMessage which works good but the problem is that email recipients see each other in message. I suppose that I should use BCC argument but not sure if its a good way. I'm opening a new thread to send email. class EmailThread(threading.Thread): def __init__(self, subject, message, user_emails): self.subject = subject self.user_emails = user_emails self.message = message threading.Thread.__init__(self) def run(self): EmailMessage(self.subject, self.message, to=self.user_emails).send() Should I do to=[self.user_emails[0]], bcc=self.user_emails[1:] or what is the most appropriate way to do this? -
Django + Ajax + Facebook API 403 FORBIDDEN
I am trying to apply Facebook Login API in django project. I planned to use Facebook username and default password(as far as django doesn't allow to create users without pass) and authenticate via ajax. FB.api('/me', function(response) { alert(response.name); // it's fine, it's there ajaxPost('/authfb/', {'username': response.name}, function(){ }); }); What I get in log is : Failed to load resource: the server responded with a status of 403 (FORBIDDEN) And in alert message: POST /authfb/ 403 FORBIDDEN undefined I am using django-ajax with decorator, but it works for me in all other parts of code. views.py: @ajax def authfb(request): if request.method == "POST": username = request.POST.get('username') password = '112358' user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) username = auth.get_user(request).username print ('logged in succesfully') return redirect("/user/%s/" % username) else: print("The username and password were incorrect.") error_message_login_page = 'you do not exist' return render(request, 'blog/facebook.html', {'error_message_login_page':error_message_login_page}) else: print("whatever") In similar questions csrf security is often pointed as issue. So I tried this js code, which might be right, but still didn't help: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; … -
Automatic filled in field in CreateView
I have the models: class Patient(models.Model): patientID = models.CharField(max_length=200 , help_text='Insert PatientID') birth_date = models.DateField(auto_now=False, auto_now_add=False, help_text='YYYY-MM-DD') gender = models.CharField(max_length=200,choices=Gender_Choice, default='UNDEFINED') class GeneralData(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) examination = models.CharField(max_length=100, choices=Examination_Choice, default='notchosenyet') height = models.FloatField(help_text= '[m] not [cm]! ') weight = models.FloatField(help_text= '[kg]') And in my Website I navigate the User, after adding a patient, to the patient detail page. There, the User can add the GeneralData via an add-button. Now I want, that the CreateView of the GeneralData select automatically the patient. Because the user came to the CreateView from the patient detail page of one specific patient I think this should be possible. But I am totally new to Django and web development in general and have no clue how to fix my problem. Thank you for your help! P.S. Sorry for my english. -
Use multi admin app in django?
I want to use "suit" package suit and "grappelli" grappelli for admin in django. If link is "/admin" will go to admin with skin suit and link is "back-office" will go to admin with skin grappelli. -
ORA-01461: can bind a LONG value when uploading blob
I want to save blob to my database(oracle 11g) using python django. The output is ORA-01461: can bind a LONG value only for insert i nto a LONG column Here's my view for filecol in request.FILES.getlist('file'): filename = filecol.name filetype = filecol.content_type fileblob = filecol.read() FileRecord.objects.create(O_FILE_ID=oID, FILE_NAME=filename, FILE_TYPE=filetype, FILE_BLOB=fileblob, DATE_UPLOADED=datetime.datetime.now().replace(microsecond=0)) I tried to encode it to base64, but same result -
Is there any way django- rest-framework-filters (query) working using "search" button?
in django filters we can get data easily like for example : http:127.../api/?first_name=kiran (gives output for first_name is kiran ) or http:127.0.0.1:8000/api/?last_name=Prajapti views.py from rest_framework.viewsets import ModelViewSet from rest_framework import filters from WBCIS.serializers import WbcisSerializer from WBCIS.models import Wbcis from rest_framework import generics import django_filters.rest_framework class WbcisViewSet(ModelViewSet): queryset = Wbcis.objects.all() model=Wbcis serializer_class = WbcisSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filter_fields = ('first_name','last_name',) So, when we run the server http:/api/?first_name=Kiran&last_name=Prajapati query works and gives exact output : { "_id" : ObjectId("58747e0b1a39f11292539da0"), "first_name" : "kiran", "last_name" : "prajapati", } So, Now, I want to write same query but using django-html button [first_name] [last_name] [ search] So,ones we fill the first_name and last_name that will run the query and gives me exact output : for example : when we run server http:127.0.0.1:8000/ html page showing [first_name] [ last_name] [search button] then we can here put the input, first_name=Kiran, last_name = Prajapati [search] then it will show our data in json format, same query http:.//api/?first_name=Kiran&last_name=Prajapati output : { "_id" : ObjectId("58747e0b1a39f11292539da0"), "first_name" : "kiran", "last_name" : "prajapati", } Can you tell me how to get data in json format when we use django-html button instead of typing http:127./api/?first_name=kiran&last_name=Prajapati ? -
Send PDF file from Django website to LogicalDOC
I'm developing my Django website since about 2 months and I begin to get a good global result with my own functions. But, now I have to start a very hard part (to my mind) and I need some advices, ideas before to do that. My Django website creates some PDF files from HTML templates with Django variables. Up to now, I'm saving PDF files directly on my Desktop (in a specific folder) but it's completely unsecured. So, I installed another web application which is named LogicalDoc in order to save PDF file directly on this application. PDF files are created and sent to LogicalDoc. LogicalDoc owns 2 API : SOAP and REST (http://wiki.logicaldoc.com/rest/#/) and I know that Django could communicate with REST method. I'm reading this part of Django documentation too in order to understand How I can process : https://docs.djangoproject.com/en/dev/topics/http/file-uploads/ I made a scheme in order to understand what I'm exposing : Then, I write a script which makes some things : When the PDF file is created, I create a folder inside LogicalDoc which takes for example the following name : lastname_firstname_birthday Two possibilities : If the folder exists,I don't create a new folder, else I create … -
How can i provide an api to get history of changes made in any model in django-rest?
I have a model class Project(models.Model): STATUS_CHOICE= (('going_on','GOING_ON'), ('project_co','PROJECT_COMPLETED'), ('contract_c','CONTRACT_COMPLETED'), ('contract_e','CONTRACT_EXTENDED'), ) title= models.CharField(max_length=30,unique=True) description= models.CharField(max_length=2000,null=True,blank=True) assigned_date= models.DateField(null=True, blank=True) completion_date= models.DateField(null=True, blank=True) join_date= models.DateField(null=True, blank=True) technology= models.ForeignKey(Technology,null=True, blank=True) consultant= models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'project') status= models.CharField(max_length= 10, choices= STATUS_CHOICE, default= 'pending') file=models.FileField(upload_to=get_attachment_file_path,null=True,blank=True) history = HistoricalRecords() Now i want to keep track of all changes in this project model.I have used django-simple-history. But it provides limited features.I know i can use signals in django. But I have to send Historical data in such a way that how many projects have been done by a specific user with the respective STATUS_CHOICE of that project. -
Django Allauth - Dynamic redirect
I have been using Django Allauth for a long time with a lot of success. Today I'm faced with a little issue I can't fix by myself. I want to redirect users after login, based on a dynamic parameter provided before the connection happens. Use case : During signup, users are redirected to a /welcome page. After a while, When a token gets revoked by the third party, I would like to reconnect my app to the user third party account. This time I would like to redirect the user to a /success page. So far I have been using get_connect_redirect_url to redirect the user to different pages (/welcome_twitter or /welcome_facebook for instance). My plan was to send users to /accounts/social_account/login/?process=reconnect and capture the process parameter. To do that, I wanted to use the new get_callback_url, but I don't know where it should live so that all my social account 'reconnect' get intercepted. I'm not sure this is the best way to achieve what I want. Any suggestions? -
Making Django's CBV's get an instance method
I'm currently building a Django app which uses a singleton object. I want to save this object as a CBV variable because I dont want to initialize it for every 'get' call. My question in short - can you make a CBV's get function an instance method instead of a classmethod? And if so, can I save a variable as an instance variable? -
Can't upload blob using python django
I'm trying to upload multiple files in oracle 11g database using python django. Here's my view for filecol in request.FILES.getlist('file'): filename = filecol.name filetype = filecol.content_type fileblob = filecol.read() FileRecord.objects.create(O_FILE_ID=oID, FILE_NAME=filename, FILE_TYPE=filetype, FILE_BLOB=fileblob, DATE_UPLOADED=datetime.datetime.now().replace(microsecond=0)) Then I received this error message return self.cursor.execute(query, self._param_generator(params)) django.db.utils.DatabaseError: ORA-01465: invalid hex number Here in my models.py class FileRecord(models.Model): O_FILE_ID = models.IntegerField(primary_key=True, validators=[MinValueValidator(1), MaxValueValidator(11)], blank=True, null=True) FILE_NAME = models.CharField(max_length=50, blank=True, null=True) FILE_TYPE = models.CharField(max_length=50, blank=True, null=True) FILE_BLOB = models.FileField() DATE_UPLOADED = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = True db_table= 'FILE_RECORD' def __str__(self): return str(self.O_FILE_ID) Sample data: filename=Koala.jpg, filetype=image/jpeg, fileblob='' I'm planning to insert base64 encoding in fileblob if possible. How can I encode file or read the file for uploading? I'm using python 3.4 and django and oracle 11g -
How to customise django inline admin form's delete function
How do I customise django's inline admin form's delete action. My admin.py setup is below. #admin.py class ChildModelInline(admin.TabularInline): model = ChildModel can_delete = True #admin.py @admin.register(ParentModel) class ParentModelAdmin(admin.ModelAdmin): inlines = [ChildModelInline,] The ChildModel is related to the ParentModel by a models.ForeignKey field. I would like to be able to select multiple child object on the ParentModel's Inline Form to be removed, but not delete the child object from the database, just remove the ForeignKey relationship in the child obj. Thank you! -
Defining custom RelatedManager in django
I want to override related manager for a class. I have a Company model. It has state column which can be in ACTIVE, INACTIVE, SUSPENDED. I am adding 2 new states called SALES, CLOSED. Since its legacy model, just adding state can be devastating(there are very many places in code which doesn't filter by state). So, to avoid inadvertent changes elsewhere, I decided to hide our new states for all other apps/elsewhere unless required otherwise (I'll whitelist only for our app/models) I've overridden object manager in company. class CompanyManager(models.Manager): def get_queryset(self): return super(CompanyRelatedManager, self).get_queryset().exclude(state__in=['SALES', 'CLOSED']) class Company(models.Model): _default_manager = models.Manager() objects = CompanyManager() allObjects = models.Manager() name = models.TextField() ... salesContact = models.ForeignKey(Contact) The problem is that Company.objects.filter(blah=blah) filters out new states. But something like salesContact.companies.all() doesn't. In [9]: salesContact.companies Out[9]: <django.db.models.fields.related.RelatedManager at 0x12157a990> My question is how to override the related manager of the salesContact = models.ForeignKey(Contact) and the likes so that I can modify the default queryset to exclude my new state. And, I can't override the default manager, since overriding default manager also implies that I am overriding the db_manager which results in un-intended consequence (db tries to insert instead of update, whole other story). -
How to store data from html form to postgres database using Django 1.10?
I am new to Django , i just created a simple form to store the user input to database, but the data is not stored while clicking submit button, when i click the submit button the current page is refreshed, but data not stored in database. what is wrong in my code ?.I have created the following models, and my code is , mysite/jobs/models.py from django.db import models class Cost(models.Model): cost = models.FloatField() date = models.DateField() mysite/jobs/views.py from django.shortcuts import render from jobs.forms import CostForm from jobs.models import Cost def costView(request): if request.method == 'POST': form = CostForm(request.POST) if form.is_valid(): date = request.POST.get('date','') cost = request.POST.get('cost','') cost_obj = Cost(date=date, cost=cost) cost_obj.save() return HttpResponse("csdfsdf") else: form = CostForm() return render(request,'jobs/cost.html',{'form':form,}) mysite/jobs/forms.py from django import forms class CostForm(forms.Form): date = forms.DateField() cost = forms.FloatField() mysite/jobs/templates/jobs/cost.html <form action="{% url 'jobs:cost' %}" method="post"> {% csrf_token %} <p><label for="date">Date:</label><input type="text" name="date" value={% now "Y-m-d" %}/></p> <p><label for="cost">Cost:</label><input type="text" name="cost" value="0" id="cost"/></p> <input type="submit" value="Submit"/> </form> mysite/jobs/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.costView, name='cost'), ] mysite/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^', include('jobs.urls',namespace="jobs")), url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] -
Wagtail blocks: accessing context and request in overidden get_context
I trying to get the page and the request from context to be able to use pagination inside the block. The only context i get is context {'self': None, 'value': None} Is it even possible to have pagination inside a streamfield block? class CustomStaticBlock(blocks.StaticBlock): def get_context(self, value): context = super(CustomStaticBlock, self).get_context(value) Rendering with {% include_block block%}