Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Insert number as folderID
I'm getting a new little problem with API Rest Python between Django and LogicalDOC. I'm creating a folder inside LogicalDOC, then I would like to save my pdf file inside this new folder taking the folderId. But, when it seems work because the syntax is good from my point of view : none pdf file appears. I create a folder, I pick up his ID number : 348930 for example with the command data["id"] and I insert str(data["id"]) in FolderId when I want to save my pdf file in the new folder. The new folder is created and worked well, but the pdf file is not save inside. Something wrong ? This is my script : @login_required def BirthCertificate_PDF(request, id) : birthcertificate = get_object_or_404(BirthCertificate, pk=id) data = {"birthcertificate" : birthcertificate} template = get_template('BC_raw.html') html = template.render(Context(data)) filename_directory = str(BirthCertificate.objects.get(pk=id).lastname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).firstname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).birthday) filename = 'Acte_Naissance_' + filename_directory + '.pdf' path = '/Users/valentinjungbluth/Desktop/Django/Individus/' + filename file = open(path, "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() if pdf : payload = '{{ "name":"{0}", "parentId":3309569 }}'.format(filename_directory) #Fix parent folder url = 'http://localhost:8080/services/rest/folder/create' headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} resp = requests.post(url, data=payload, headers=headers, auth=('admin', 'admin')) … -
Last created object id
My ID column is auto-increment, but I have to send ID to another function after object created and saved. actionObj = ScAnsAction() #actionObj.id -- auto increment actionObj.user_id = getUserID(request) actionObj.action_id = 6 actionObj.req_id = request_id actionObj.a_date = i.strftime("%Y-%m-%d") actionObj.save() setUserNotifs(request,#should be latest above objectID) I have try latest function over query set, but I retreived list out of index. -
Getting error on my GET request even though I didn't call the GET request
So when an element is clicked I trigger this ajax GET function: $('a.username').on('click', function() { var username = $(this).html(); var url = window.location.href.split('?')[0]; $.ajax({ type: 'GET', url: url, data: { username_clicked: username, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() }, success: function (data) { console.log(data.username_clicked) } }) }); which gets the text of the element clicked (aka the username). This successfully sends to my view which captures the GET data through the following code: username_clicked = request.GET.get('username_clicked') print(username_clicked) #prints the correct text However when I add this code under the above text in the view: profile = Profile.objects.get(username=username_clicked) if username_clicked: print(profile.age) It gives me this error ONLOAD: DoesNotExist at /news/151/ Profile matching query does not exist. How can this error be raised if I haven't even triggered the click() event? The error appears when I load the page. Also just to reassure, when I manually add an instance of username, e.g. like this: profile = Profile.objects.get(username='zorgan'), that works fine. But it won't take a variable for some reason. Here's my models if you're wondering: class Profile(models.Model): username = models.CharField(max_length=32, default='AnonymousUser') age = models.IntegerField(default=0) def __str__(self): return self.username Any idea? -
Retrieve related field's object in GET requests, otherwise use only ID of the object in POST, PUT, DELETE etc
I have two serializers. The 'category' field in the Article is a ForeignKey. I want to retrieve category object completely when I do a GET request. And I want to use only ID of the category when I do a POST, PUT or DELETE request. class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('pk', 'name', 'slug') class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Provider fields = ('pk', 'title', 'slug', 'body', 'category') depth = 1 If I add the "depth = 1" property to the Meta class, then I'm getting the category object. It's OK. But, if I try to add new Article (via POST request) I'm getting this error: IntegrityError at /api/articles NOT NULL constraint failed: panel_article.category_id If I try with defining a CategorySerializer field, instead of use 'depth' property like this: class ArticleSerializer(serializers.ModelSerializer): category = CategorySerializer() class Meta: model = Provider fields = ('pk', 'title', 'slug', 'body', 'category') I'm getting this error due to category field: "Invalid data. Expected a dictionary, but got int." I guess DRF is trying to create new category, when I try to create a new Article. How do I solve this problem? -
get next key element in dictionary in django template
dict = {'1':{'name':'Andy','territory':'Asia'},'5':{'name':"John",'territory':"Africa",'3':{'name':"Beny",'territory':'Worldwide'}} I have a dict and i need to use it in for loop and i need next key element in current for loop {% for key,val in dict.items %} {{key}} {{key.nextkey}} {% endfor %} Can anyone help to access it -
How can i make template with django-rest-auth
I am so noob in django-webprogramming. I want to implement login, social login function with django-rest-auth. But i can not understand how can i make templates even i read officail docs and github... There are any way to make login template(e-mail login, social login) and css? -
Upgrade django-haystack from 2.4.1 to 2.5.0
I want to upgrade django-haystack in my app from 2.4.1 to 2.5.0. On version 2.4.1 my code works fine. But when I installed verison 2.5.0 I get error when I start searching, for example: New york and I dont have any search results. "GET /en/search?q=new%20york HTTP/1.1" 500 26693 -
H14 error in heroku - "no web processes running"
error H14 happen while deploying to heroku this is my procfile: web: gunicorn -w 4 -b 0.0.0.0:$PORT -k gevent main:app log on heroku: 2017-01-23T10:42:58.904480+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=meetcapstone.herokuapp.com request_id=df88efb5-a81a-4ac0-86dc-4e03d71266bb fwd="81.218.117.137" dyno= connect= service= status=503 bytes= 2017-01-23T10:42:59.009135+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=meetcapstone.herokuapp.com request_id=21cea981-36b0-4410-891f-548bbc29f0ee fwd="81.218.117.137" dyno= connect= service= status=503 bytes= requirements: Flask==0.11.1 passlib==1.7.0 SQLAlchemy==1.1.5 Werkzeug==0.11.15 gunicorn==19.0.0 gevent==1.2.1 -
Django Rest Framework: Exclude one queryset from another with combined filters
I have the following method which return objects for is_active=True and for particular user. def filter_active_user(self, queryset, name, value): return queryset.filter(active_states__is_active=True, active_states__user_id=value) I would like to build a method which will return a queryset with all the objects which are not included in the above method. So I created the following method: def filter_inactive_user(self, queryset, name, value): return queryset.exclude(active_states__is_active=True, active_states__user_id=value) I also tried the following implementation: def filter_inactive_user(self, queryset, name, value): return queryset.filter(~Q(active_states__is_active=True, active_states__user_id=value)) But, I don't get the correct results. Can you help me to build the properly way to combine two filters in a queryset? -
Expected view to be called with a URL keyword argument named "pk"
I'm writing a test for a Django Rest Framework view following closely the testing documentation Here's my simple test: def test_patient_detail_api_opens(self): factory = APIRequestFactory() view =PatientDetailApi.as_view() request = factory.get(reverse('api_pacjent', kwargs={'pk' :1})) force_authenticate(request, user=self.user) response = view(request) self.assertEqual(response.status_code, 200) This test fails with the following message: AssertionError: Expected view PatientDetailApi to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I fail to understand why this is happening and how to fix this. The pk kwargs is there in the URL, according to the docs there's no need to add the lookup-field value explicitly if it defaults to pk, the view opens correctly and yet this test fails... Can somebody please explain why this error occurs? Here's the relevant code: the 'main' url.py: urlpatterns = [ url(r'^pacjent/', include('pacjent.urls')), ] pacjent.urls looks like this: url(r'^api/szczegoly/(?P<pk>\d+)/$', PatientDetailApi.as_view(), name="api_pacjent"), And PatientDetailApi is this: class PatientDetailApi(generics.RetrieveUpdateAPIView): model = Patient serializer_class = PatientDetailsSerializer queryset = Patient.objects.all() authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) -
Creating configuration files for vpc on elastic beanstalk
Please I need help answering this questions. Create configuration files that achieve the following Creates a VPC with appropriate settings for an Elastic Beanstalk environment to run within it Deploys a dockerized Django app to Elastic Beanstalk on AWS inside the VPC Deploys an RDS instance inside the VPC Trigger a run of the test suite on Travis CI -
invalid literal for int() with base 10: 'Requires moderation'
In past I've resolve this problem couple of times and in my practice this was only related to date time field issues. Currently I am not able to determine the reason for this error at all and this is really frustrating. I am posting the complete model with its view and exact functions where traceback points out the error in code. However I've also added date time fields of the Product model which is related by a ForeignKey field at end of post which I believe may not be relevant but perhaps it might help. A little explanation about the issue would be a great help as well. Please advise. ProductReview model: class ProductReview(models.Model): product = models.ForeignKey( 'catalogue.Product', related_name='reviews', null=True, on_delete=models.SET_NULL) SCORE_CHOICES = tuple([(x, x) for x in range(0, 6)]) score = models.SmallIntegerField(_("Score"), choices=SCORE_CHOICES) title = models.CharField( verbose_name=pgettext_lazy(u"Product review title", u"Title"), max_length=255, validators=[validators.non_whitespace]) body = models.TextField(_("Body")) user = models.ForeignKey( AUTH_USER_MODEL, related_name='reviews', null=True, blank=True) name = models.CharField( pgettext_lazy(u"Anonymous reviewer name", u"Name"), max_length=255, blank=True) email = models.EmailField(_("Email"), blank=True) homepage = models.URLField(_("URL"), blank=True) FOR_MODERATION, APPROVED, REJECTED = 0, 1, 2 STATUS_CHOICES = ( (FOR_MODERATION, _("Requires moderation")), (APPROVED, _("Approved")), (REJECTED, _("Rejected")), ) status = models.SmallIntegerField( _("Status"), choices=STATUS_CHOICES, default="Requires moderation") total_votes = models.IntegerField( _("Total Votes"), … -
Django admin site not showing image from ImageField
I have created a model having ImageField as below: class Category(models.Model): name = models.CharField(max_length=15) image = models.ImageField(upload_to='pic_folder') url = models.URLField() def image_tag(self): return mark_safe('<img src="%s" width="50px" height="50px" />' % self.image.url) image_tag.short_description = 'Image' image_tag.allow_tags = True def __str__(self): return self.name And in admin.py class CategoryAdmin(admin.ModelAdmin): fields = ('image_tag', 'name',) readonly_fields = ('image_tag',) admin.site.register(Category, CategoryAdmin) But my images are not showing in django admin site, Need urgent help: enter image description here -
API Rest Python & Django
I have a problem with my script which let to generate a PDF file and then send it to another application (LogicalDOC) in order to save it. This is my script : @login_required def BirthCertificate_PDF(request, id) : birthcertificate = get_object_or_404(BirthCertificate, pk=id) data = {"birthcertificate" : birthcertificate} template = get_template('BC_raw.html') html = template.render(Context(data)) filename_directory = str(BirthCertificate.objects.get(pk=id).lastname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).firstname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).birthday) filename = 'Acte_Naissance_' + filename_directory + '.pdf' path = '/Users/valentinjungbluth/Desktop/Django/Individus/' + filename file = open(path, "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() if pdf : payload = '{ "language":"fr","fileName":filename,"folderId":3309569 }' upfile = path files = { 'document': (None, payload, 'application/json'), 'content': (os.path.basename(upfile), open(upfile, 'rb'), 'application/octet-stream') } url = 'http://localhost:8080/services/rest/document/create' headers = {'Content-Type': 'multipart/form-data'} r = requests.post(url, files=files, headers=headers, auth=('admin', 'admin')) context = {"birthcertificate":birthcertificate, "path":path} return render(request, 'BC_PDF.html', context) file.close() return HttpResponse(pdf, 'application/pdf') I'm getting a problem with payload line. The filename should be my filename variable but it doesn't take account. If I write filename.pdf, I find filename.pdf in LogicalDOC with the good content. But filename have to change automatically for each new BirthCertificate. How I can pass the path as filename ? Thank you so much ! I'm sorry if my English is … -
Celery: Received unregistered task of type u'send_emails_to_queue'
I'm deploying my Django project to VPS. I use supervisord to run Celery as daemon. There are situations when I for example rename some task and I want to start everything from scratch so no tasks are registered and no tasks are in Redis queue. How can I restart the celery so tasks would be registered again? Since I have supervisord set to autorestart, I've tried: sudo pkill celery which seems to work but no new tasks are registered. I've changed name of "test_email" to "send_emails_to_queue". [2017-01-23 09:11:24,069: INFO/MainProcess] Task test_email[142e25ce-d6fc-4468-b0f4-74290a8be698] succeeded in 0.782588873059s: None [2017-01-23 09:13:55,699: ERROR/MainProcess] Received unregistered task of type u'send_emails_to_queue'. -
Celery task giving ConnectionError on hitting endpoint when running from docker container
I have a celery task like so: @app.task(name="parse_xml_feed") def parse_xml_feed(url, feeds, user, domain): result = {'test':'data'} response = { "data": result, "url": url, "user": user, "status": "SUCCESS" } print response time.sleep(2) sendData = requests.post('http://localhost:7000/server/content/websocket-relay', data=response) return sendData.status_code which works perfectly except that whenever it reaches the line sendData = requests.post(...), it gives out ConnectionError: None: Max retries exceeded with url: /server/content/websocket-relay (Caused by None) error. The reason for calling this endpoint is to send the result to this endpoint which further pushes to the frontend using web sockets. This code works perfectly when running locally, but in docker container, it gives out the error when it tries hitting the endpoint for sending the result. What is the reason for this? -
Celery overrides Django logging formatters
I know that I can define Django logging format in LOGGING at settings. Here is mine: LOGGING = { 'version': 1, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'console', }, }, 'formatters': { 'console': { 'format': '[%(asctime)s] [%(levelname)-5s] %(filename)s:%(lineno)d [%(name)s] - %(message)s', }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'django.db.backends': { 'handlers': ['console'], 'level': 'WARNING', 'propagate': False, }, 'celery': { 'handlers': ['console'], 'level': 'WARNING', 'propagate': False, }, 'requests': { 'handlers': ['console'], 'level': 'WARNING', 'propagate': False, } } } The problem is, that my logging format works for "synchronous" tasks, but when my tasks are running under celery worker, the output differs. Here is output for "synchronous" tasks: [2017-01-23 09:15:59,278] [INFO ] basehttp.py:131 [django.server] Here is output for from celery task: [2017-01-23 09:18:59,264: INFO/PoolWorker-3] So module, line are missing. How can I override logging format for celery tasks? -
Django-haystack, wrong search results with dash (-) symbol
I have django app in version 1.8. I use there django-haystack (2.4.1) with enginge: "whoosh". I have a problem with the search words in which there is a dash (-). For example, searching for the words "New York" - is all about, it displays a corresponding number of results. On the other hand, sought the title of the song "love-love" (with "-"), it shows a lot more results than should show and searched phrase is not shown in the search results. -
when i add in buildozer.spec jar file my android app have authorization
I add in buildozer.spec: android.add_jars = libs/android/zbar.jar And my android app "Permission denied". Authorization made with django and restdjango. In PC app work normaly. Why? If i delete this code from buildozer.spec my android app work normaly too. Why? -
DRF can't authorize account via token, always getting anonymous user object
I am using TokenAuthentication and have model Profile for users: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) participant = models.CharField(max_length=255) title = models.CharField(max_length=100) And view for profile creating: class ProfileView(LoggingMixin, GenericAPIView): serializer_class = ProfileSerializer queryset = Profile.objects.all() def get(self, request, format=None): """ Return user's profile information """ serializer = ProfileSerializer(queryset) return Response(serializer.data) def post(self, request, format=None): """ Create new profile """ data = request.data.copy() data['user'] = request.user.id print data serializer = self.serializer_class(data=data, context={"request":request}) print serializer if serializer.is_valid(): print 1 serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I need to create profile object after registration. I am sending data from a web page via jquery: $.ajax({ headers: {"Authorization": "Token " + data.key}, type: "POST", url: "http://127.0.0.1:8002/v1/profiles/", data: JSON.stringify(profileDataToSend), success: function(){ console.log('Success! 2'); }, dataType: "json", contentType : "application/json" }); Registration works fine, Token gets created, but when I try to send this request for creating a profile, linked to logged user, I get anonymous user object every time. In my settings I am setting : DEFAULT_AUTHENTICATION_CLASSES = "rest_framework.authentication.TokenAuthentication" But still, can't understand why I can't get user logged in with my request. Where am I doing mistake? -
Use Django header to pass data
I'm new to Django and now facing a problem. I don't know how to pass a data from one webpage to another using html header. (using Django) Usually I use django form with post method to pass the data But now I need to pass the data without form. Here's what I want to do: json.py handles a webpage that produces json data chart.py handles a webpage that receives json data and turn it into charts I need the json data to save in somewhere and post it to the webpage that chart.py controls I've read the docs but I have poor understanding to it. To be short, I want to ask 2 things: How to save the data in json.py and post to chart.py? (through header) After post, how to get the data from header? (in chart.py) -
Django 1.9.6 how to set csrf token in automating requests
I am trying to automate a request but there is an error as shown below when the following script is run,what is wrong here and how to prevent this error, I am running django local server in this case Note: Even though i have disabled csrf middleware i still have to go through setting csrf token from django.conf import settings as st from reports.tasks import save from datetime import datetime as dt import requests import django from django.http import HttpRequest import urllib url = 'http://127.0.0.1:8000/reports/update/' lat = 12.97161923; lon = 77.59463452; client = requests.session() client.get(url) csrftoken = client.cookies['csrftoken'] csrf = client.get(url).cookies['csrf'] for i in range(10): data = {'latitude':lat+0.5,'longitude':lon+0.5,'accuracy':0.7,'csrfmiddlewaretoken':csrf,'csrf_token' : csrftoken, 'next':'/'} r = requests.post(url, data=data,headers=dict(Referer=url)) break Error Press ENTER or type command to continue Traceback (most recent call last): File "update_query.py", line 14, in <module> csrftoken = client.cookies['csrftoken'] File "/home/r/go/.go/local/lib/python2.7/site-packages/requests/cookies.py", line 329, in __getitem__ return self._find_no_duplicates(name) File "/home/r/go/.go/local/lib/python2.7/site-packages/requests/cookies.py", line 400, in _find_no_duplicates raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) KeyError: "name='csrftoken', domain=None, path=None" -
Django Query set with distinct and exclude together
I want to send notification to users who has previously commented in the request. So, for this aim, I have to find distinct users and exclude current commenter(user) id from that list. object_id_list = ScAns.objects.filter(username=username).values_list('id',flat=True) result-> QuerySet [22] actionUsers = ScAnsAction.objects.filter(req_id=request_id).values_list('user_id',flat=True).distinct().exclude(id__in=object_id_list) result-> QuerySet [13, 15, 22] final Result should not contain 22. It should give [13,15] -
How to replace Django-sqlite3 database with Redis Database?
We are trying to integrate Redis DB with Django-1.9, where in all the documents contains the procedure to integrate redis cache with django. But we want use Redis Db over the Default Sqlite3. Please help us on how we can achieve this? -
How to send a zip file to frontend to download in DRF
I am trying to send a zip file to frontend so that it could download it in the browser. Zip file has a folders inside and those folders have files: file.zip - first folder - file1.pdf - file2.pdf - second folder - file3.pdf I think that I need to convert the file to bytes first to send it as a response so I tried to do this: zip_file = ZipFile(zip_file_path) zip_byte_array = bytearray() for filename in zip_file.namelist(): byte_content = zip_file.read(filename) zip_byte_array.append(byte_content) return Response(zip_byte_array) It gives the following error while appending to the bytearray: an integer is required the folder was archived like this: zip_file_path = shutil.make_archive(dir_path, 'zip', dir_path) How can I fix this?