Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Swift iOS POST not working with Django View
I have the following basic view: def updateAPNS(request): result = json.loads(request.body, encoding='utf-8') return HttpResponse(result) All I seem to get is "No JSON object could be decoded". My code from iOS is as follows: let request = NSMutableURLRequest(url: NSURL(string: "https://str8red.com/updateAPNS")! as URL) let session = URLSession.shared request.httpMethod = "POST" let params = ["email":"test"] as Dictionary<String, String> request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: []) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in print("Response: \(String(describing: response))")}) task.resume() I have tried so many different examples of POST form iOS and all give me the same error. So I am assuming it is an error on the django side, however, if I put #@require_POST at the start of my view it seems to suggest that it is not being treated as a POST request. I am going around in circles and going insane here so if anyone can help that would be great. Many thanks, Alan. Result in iOS console screen incase it helps: Response: Optional(<NSHTTPURLResponse: 0x60000023c920> { URL: https://str8red.com/updateAPNS/ } { status code: 500, headers { Connection = close; "Content-Type" = "text/html; charset=utf-8"; Date = "Sat, 27 May 2017 12:51:01 GMT"; Server … -
Django and s3boto - Change file download name
I'm using the s3boto package to store media files on Amazon S3 for my Django project. I'm storing files as unguessable UUID strings inside s3 buckets. Now what I want is to change the file name as the user downloads it. So that they don't get a UUID, but something more user friendly. The file name would be something that would change for each file (e.g Quote-Robert-2017-05-25.pdf). I found this answser: Amazon S3 Change file download name. It tells how you can change the download name by changing the ContentDisposition Header on the file. However with s3boto the only way to override this header is by doing it globally in the django settings (AWS_HEADERS). It works, but doing it globally is not what I want, I'd like each file to have it's own on-the-fly-generated ContentDisposition Header when it's uploaded. I guess the right place to do it would be directly in the model or something... -
How to access specific objects in django models?
I have the following model below: class Question(models.Model): title = models.CharField(max_length=100) date_pub = models.DateTimeField(auto_now_add=True) professor = models.ForeignKey(Professor, on_delete=models.CASCADE, default="") #Show only course belonging to this professor classes = Classes.objects.filter() I would like to know how to access classes that belong only to the "professor" above, because if many professors create Questions I dont want all classes to appear when the professor had nothing to do with those classes. I want only classes they created to appear. -
Can't update user profile in my Django app Django
I have created a Edit Profile form in my Django app but it doesn't save in the database. This is the profile model: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', primary_key=True) #Each User is related to only one User Profile city_search_text = models.CharField(blank=True, max_length=300)#user picks a city from autocomplete and in the view I get or create a City object city = models.ForeignKey(City, blank=True, null=True, related_name='city') #Each User Profile must be related to one city. prof_pic = models.ImageField(blank=True, upload_to='profile_pictures') dob = models.DateField(blank=True, null=True) def __str__(self): return self.user.first_name This is the form: class EditProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('dob',)#I'm testing to update this field only def save(self, commit=True): profile = super(EditProfileForm, self).save(commit=False) if commit: profile.save() return profile This is the view: def editprofile(request): if request.method == 'POST': edit_profile_form = EditProfileForm(request.POST, instance=request.user) if edit_profile_form.is_valid(): profile = edit_profile_form.save(commit=False) profile.save() if 'next' in request.GET: return redirect(request.GET['next']) else: print (profile_form.errors) else: edit_profile_form = EditProfileForm(instance=request.user.profile) return render(request, 'excurj/editprofile.html', {'edit_profile_form':edit_profile_form,}) After I submit the form it forwards me to index page okay but the values remain the same in the user's profile. -
celery seems to sleep and not working
I am using celery and flower to perform a periodic task. The problem is that sometimes the tasks are not performed at the determined time and when I restart celery in the shell, the delayed tasks starts to be done. Do you know what is the problem and how can I solve it? -
Wrong time in Docker container of Django app built by Jenkins
I am comparing two container times. One built on my local machine and the other is built on the Jenkins server. I attached to both of them and tried these commands: First: date function of the Linux. The same results: Locally running container: Sat May 27 10:47:06 UTC 2017 Container running on Jenkins server: Sat May 27 10:47:28 UTC 2017 Second: python shell. The same results: Locally running container: '2017-05-27 10:59:40.005836' Container running on Jenkins server: '2017-05-27 10:59:35.567902' Third: datetime.now() in Django shell (./manage.py shell). Different results: Locally running container: '2017-05-27 06:01:52.547923' Container running on Jenkins server: '2017-05-27 11:01:17.001070' Locally running container is the correct one because in my Django app, I set the timezone to America/Chicago and at the time of this writing this is the correct time. The one in Jenkins is wrong and looks as if ignoring the timezone set by Django. I don't understand why. Thank you for any help -
iOS Swift 3 post issues
I am using the following Swift 3 code in an iOS app to try to update a backend MySQL database: var request = URLRequest(url: URL(string: "https://str8red.com/updateAPNS")!) request.httpMethod = "POST" let postString = "devicetoken=gjhgjgjgkkgggkgkghgkgkhjg" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } let responseString = String(data: data, encoding: .utf8) print("responseString = \(String(describing: responseString))") } task.resume() When I run this code iOS acts as expected and returns a 500 error from the web server. When I check the Webserver report I get the following error: MultiValueDictKeyError at /updateAPNS/ "'devicetoken' More confusingly the feedback suggests: POST: No POST data Should iOS not being posting the devicetoken variable as described in line 3 in the code above? If not how do I access the devicetoken variable in my view? My Django view is below incase it may help: def updateAPNS(request, extra_context={}): currentUser = request.user currentUserID = currentUser.id if not currentUserID: … -
Did you forget to register or load this tag? Django
enter image description here Did you forget to register or load this tag? I was watching the django tutorial in udemy, and I follow the same step as the professor did. The error came out with this -
Navigation in the same page with Django, Python and MongoDB
I want to make something like this: https://morelab.deusto.es/publications/ Something like the Advanced search of that page, but I don't know how can I make the 'navigation pages'. I am using Django 1.10.5, Python 3.6 and MongoDB with Pymongo. I just want to make click and open the form depending where I click on. -
how to filter a many-to-many fied?django
example: class Person(model.Models) name = model.CharField(max_length=30) age = model.IntegerField() class Book(model.Model) title = model.CharField(max_length=30) author = model.ManyToManyField(Person) per1 = Person('Jack',10) per1.save per2 = Person('Rose',20) per2.save book1 = Book() book1.title = 'booktitle' book1.author.add(per1) book1.author.add(per2) now I want to get the 'book1' obj like this { 'title':'booktitle', 'author':[ { 'name':'Jack', 'age':10, } ] } there is noly one author in the 'book1' obj how to filter the related field? Anyone can help me? -
Django restauth new field creation in registration
I am using Django rest auth library for registration and login, now I want to introduce a new field in the registration form, I have managed to do it by adding the field in rest auth library directly, it is the best way or any other way to do it like overriding. so without override let say for an example: if i am doing the changes in the rest auth library so if any update on rest auth library will create any impact on changes which i have done. -
Django CMS - link to uploaded image returns 404
I have a Django 1.8.4 site with Django CMS 3.1.3. Via the djangocms-picture plugin I want the editors to be able to upload images to the site. If I upload an image on a page using this plugin, the image ends up in the following folder on the server: [PATH_TO_APP_ROOT]/media/cms_page_media/8/ Where ‘8’ is the id of the page. When I browse the page, the link to the image is given as https://[MY_SITE]/media/cms_page_media/8/my_image.png But this link is not correct and I get a 404. I am having a hard time figuring out what I am missing but it seems that there is some URL setting that should be changed. In settings.py I have: MEDIA_ROOT = os.path.join([PATH_TO_APP_ROOT], "media") MEDIA_URL = "/media/" Where [PATH_TO_APP_ROOT] is the same as given above. I have not changed any of the media-settings given in the Django CMS docs so they should all be default. I am confused that the server looks for the image in /media/cms_page_media/8/my_image.png as the cms_page_media-part of this URL comes from CMS_PAGE_MEDIA_PATH which is not a URL setting(?). What setting do I need to look for to correct this? Note that everything works perfectly for me in DEV (locally) - the problem is only … -
how to use managment form in django formset
I am trying to understand how to validate a formset. I read the docs and bunch of other articles so I already get the idea - but I can not get it working. In particular I do not understand where I should place the manage formset data and how to integrate it with the data obtained via POST request? Could anyone post an example of using formset with an actual formset management form? It is possible (and actually quite probable) that I simply do not understand some basic functionality, but I am out idea where to get an answer. In addition: This question originated from another issue, described in this question. -
TypeError at /1 argument should be string, bytes or integer, not Download
Am new here, i want to serve my download files from the media files and the files are being uploaded through from the admin. i tried doing something and i am getting this error TypeError at /1 argument should be string, bytes or integer, not Download below are my codes. view.py def download(request, download_id): downloading = Download.objects.get(pk=download_id) if os.path.exists(downloading): with open(downloading, 'rb') as fh: response = HttpResponse(fh.read(), content_type="text/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(downloading) response['Content-Length'] = os.path.getsize(downloading) return response pdf.closed raise Http404 url.py url(r'^(?P<download_id>\d+)$', views.download, name='download'), html link <a href="{% url 'peruse:download' download.id %}" class="btn btn-generic btn-sm" role="button">DOWNLOAD</a> please help me out on how to make this work. thank you -
Django change multiple model entries
I have a model containing various entries tied to one user and I want to give the user a view where he can review these entries, select some of them and perform an action on the selection. something like the admin intereface has. I have tried UpdateView but that is for one entry only. ListView doesn't like that the model returns multiple entries for one identificator. Is there something else I could use? -
Django python, differences between self.request and '%s' % self.request
I'm getting parameters through GET or POST. On the book I'm reading, there's Word = '%s' % self.request.POST['word'] I wonder whether there's a specific reason for that. I mean why not like this just simply? Word = self.request.POST['word'] -
Django DRF without db
I need to build a rest api using django. On GET requests my tool has to captures parameters from url and invoke a function for their manipulation. For example: on input url myapp/name=john&birthdate=11July, the function compute(name,birthdate) computes a transformation on parameters returning a json as output. I don't understand how to proceed, considering that each tutorial i followed is about db interaction. -
A user can explore(see) any page in wagtail admin interface?
Issue: The site structure is as following: Homepage |- Blog Index |- Event Index |- People |- Contact Page |- User A |- Test Page 1 |- Test Page 2 Now I add a user called 'UserA', who belongs to roles group of 'UserA' (the same name), and group 'UserA' is set to only has 'add' & 'publish' permissions to 'User A' page. The left nav bar in admin area works fine, 'UserA' can only see 'User A' as the root; But when clicking on the wagtail bird icon in admin page, 'UserA' can see Homepage and all its children, like 'Blog Index' and 'Event Index'. So it's like a user can view any pages in Wagtail admin area? Is this on purpose? What I really expect is a user can only see(explore) pages owned by himself, or pages that his role group has access to. It's like user isolation. Can this be done? Thanks. Project: wagtail-demo Python: 3.6.1 Django: 1.10 Wagtail: 1.10.1 -
Using a python backend for a machine learning web application, interplay between JS and Python?
I'm building a machine learning web platform (Chemistry application). For this, I was thinking about using python to do the actual machine learning, using the sklearn library and JS to do the client-side computing (things like drawing of molecules -- I found a library to help me do this for JS). My question is how exactly can I have python, HTML, and JS interplay with each other. My only idea was to use django to send and receive APIs from JS to python. In essence, the javascript would request an API for certain parameters, the python would run the algorithm and send an API back. Does this sound feasible? If so, does anyone have any tips, further questions, or other ways of doing this that may be simpler? I also need some help with the actual implementation of this, as I'm fairly new with using APIs. Thank you all so much in advance, Ameet -
How to get the MAC address of client
On my website I am selling Course materials and user have to pay for that and I want to get the MAC ID of user who purchase my courses so that they cannot use it on other devices. Is that Feasible to code in Python/Django ? My approach from uuid import getnode as get_mac mac = get_mac() print mac The above code give the MAC ID but this is my server's MAC ID. Is there any possible sollution for that then please share. Thanks in Advance -
Passing a parameter to an HTML page
I have an HTML page that displays orders and buttons with the confirmation of these orders. I need to press the confirmation button to change the confirmation status in the database. But if at least one order with the same id is already confirmed, then do not show this button for other similar orders. To do this, when I press the button, I need to return to the same page, but with some parameter that I will check in the condition. I can not pass the parameter to the same page. This is HTML page myFeedback.html: {% for myFeedback in myFeedbacks %} <p>{{ myFeedbacks.extra.values }}</p> {% if not myFeedback.confirmed %} <a class="btn btn-default" href="{% url 'feedback_approve' order_id=myFeedback.id %}"><span class="glyphicon glyphicon-ok" aria-hidden="true"></span></a> {% endif %} {% if myFeedback.confirmed %} <a class="btn btn-default" href="{% url 'feedback_remove' order_id=myFeedback.id %}"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a> {% endif %} <h5>{{ myFeedback.order }}</h5> <hr> {% endfor %} urls: urlpatterns = [ url(r'^my_feedback/$', my_feedback, name='my_feedback'), url(r'^(?P<order_id>\d+)/feedback_approve/$', feedback_approve, name='feedback_approve'), url(r'^(?P<order_id>\d+)/feedback_remove/$', feedback_remove, name='feedback_remove'), ] views: def my_feedback(request): if request.user.is_authenticated(): return render(request, 'orders/myFeedback.html', {'myFeedbacks': Replies.objects.filter(applicant=request.user) }) else: return redirect('/auth/login/') def feedback_approve(request, order_id): if request.user.is_authenticated(): approve_feedback = get_object_or_404(Replies, id=order_id) approve_feedback.confirmed = True approve_feedback.save() q = 'confirmed=True and order=' + order_id + ' and … -
Django content_type object_id
I have model call Report: class Report(models.Model): owner = models.ForeignKey(User, related_name='report_owner') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') How do I find out what the object_id of my models in all my apps are? -
How to get timezones on django template without context?
I need to get pytz timezonesin django template like {% load pytz %} {% for tz in get_timezones %} <option value="{{ tz }}"{% if tz == TIME_ZONE %} selected{% endif %}>{{ tz }}</option> {% endfor %} -
Transmit reversed url to include tag
Django 1.11 I have created a template which I'll include in different other templates. It contains something like this: ajax_create_object_inclusion.html <a class="custom-control" data-url="{{ creation_url }}" href="javascript:void(0)">Plus</a> It is used like this: home.html {% url 'frames:create' as frame_create_url %} {% include 'general/cbv/cbv_inclusions/create_object_inclusion.html' with creation_url=frame_create_url %} I failed to use nested tags in templates. Could you help me understand whether this is the most rational way? Or I somehow can change ajax_create_object_inclusion.html so that I could use only one include string instead of two. -
How to extract data from given url through urllib.request module in python?
I'm creating a webapp in Python with django web-framework. I want to extract some information from https://play.google.com/store. This url will take search query parameter like food, shooting etc. So url will look https://play.google.com/store/search?q=food. Now I want extract AppID AppName, 'Developer name, 'Developer Email etc of first 10 search results. Can someone tell, How can I do this? Any help would be appreciatd.