Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python&Django: What does ** mean
Possibly i know the following uses of ** Power x ** y # x power y equivalent to pow(x,y) Passing indefinite number of args def sample(x, **other): print(x, other.keys) sample(x=2,y=3,z=4) But i don't understand when its used as follow( in Serializers) def create(self, validated_data): return Comment(**validated_data) -
Django: No reverse match
def test_post_request_for_api_view(self): data = { "email": self.user.email, } url = self.reverse('users:the_api', self.user.pk) response = self.json_post(data, url=url) self.mock.assert_called_once_with(self.user) data2 = json.loads(response.content.decode('utf-8')) self.assertEqual(data2, { 'booking_order': ['ABCDEFGHIJKL'], 'transaction_total': '20000.00' }) As much as i understand how reverse works in Django, i believe for the above test to pass, i only need to have a the_api url in my urls.py. However, the test does not pass even with that. As such, i would love to know what the right thing to do is. How do i get the test to run? The error i keep getting is: django.urls.exceptions.NoReverseMatch: Reverse for 'about' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['users:the_api/$'] -
Convert HTML file into PDF, save it in projects media folder and send pdf in email in django
I have to create a dynamic pdf from html file in this pdf i am passing some keywords as well as barcode is also generated, basically this pdf is a ticket of an event. So i have to send this pdf(ticket) to user's email id, as well as i have to save this pdf to my project's directory so that user could also download this pdf from his/her account. I have successfully created pdf from html file, i have used code on stackoverflow and its working fine but the problem is that it's opening in tab, i have to save it in directory. Here is my code def testing_pdf(request): image = treepoem.generate_barcode( barcode_type='azteccode', data='00100111001000000101001101111000010100111100101000000110', options={'layers':5} ) image.save(settings.MEDIA_ROOT+'/barcodes/barcode.png') template = get_template('home/pdf-template/index.html') context_dict = { 'name':'Testing','event': 'testing', 'barcode':image} context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result) if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') return response return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) What should i do in my this code so that it can be saved into my project's directory and send into user's email account. -
Celery PeriodicTask added in runtime wouldn't be received?
try: delete_interval = IntervalSchedule.objects.get(every=1, period='seconds') except ObjectDoesNotExist: delete_interval = IntervalSchedule(every=1, period='seconds') delete_interval.save() delete_report_task = PeriodicTask( name="%s_%s" % (datetime.now(), 'delete_report'), interval=delete_interval, task='tasks.delete_report', ) delete_report_task.args = (report.id) delete_report_task.save() As you can see from the above, I create and save the PeriodicTask instance, and I expect the message "Received delete_report task" will be printed out every second by celery beat. But nothing shows, anyone has idea about why? -
Web Push Notification with Encrypted Payload in Python
Can someone please explain how to send notification with Payload for Chrome using Python/Django I am doing so- fcm_url = "https://fcm.googleapis.com/fcm/send" encoded = WebPusher(subscription_info).encode(json.dumps(data)) crypto_key = "dh=" + encoded["crypto_key"] salt = "salt=" + encoded['salt'] headers = {'Authorization': 'key=' + gcm_key, 'Content-Type': 'application/json', } headers.update({'crypto-key': crypto_key, 'content-encoding': 'aesgcm', 'encryption': salt}) fcm_data = {"raw_data":base64.b64encode(encoded.get('body')), "registration_ids": ['eYXdX1V94XY:APA91bHPQdnlQiVwe5HmWnRQrtpOnHzAJ4kEHNgB8GrEZ_YxSgtwz-0gvcpUFBAb3_eVXOVcJAjvVotGfKl9jLGM_X6nZb76YzFBZazMu1auIDAXhXjUgFDHm7E2ffRpBD70rpD1qC1r']} resp = requests.post(fcm_url,data=json.dumps(fcm_data),headers=headers) Output:- {"multicast_id":6483153199368608385,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1481362362576359%958b01adf9fd7ecd"}]} but the notification doesn't contain the above specified Data. I think,It is done by naveen bro if know please help me. -
django verify is HttpResponse reached user
Is there anyway to make sure that an HttpResponse in django has successfully reached the end-user? A normal TCP connection will end with FIN request! Is there anyway to know if the response was actually returned without forcing the end-user device to send a receive tag? -
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
This is my index function of view.py def index(request): logger_user_id = None if 'id' in request.session: request.user.is_active = True logger_user_id = request.session['id'] print(logger_user_id) posts = Post.objects.all() all_users = User.objects.all(); author_name = {} for e in posts: author_name[e.id] = get_object_or_404(User, id=e.user_id).username e.likes_count = Likes.objects.filter(post_id=e.id).count() try: post_logger_like = Likes.objects.get(user_id=logger_user_id, post_id=e.id) e.logger_like = 1 except Likes.DoesNotExist: e.logger_like = None recent_liker = Likes.objects.filter(post_id=e.id).exclude(user_id=logger_user_id).order_by('-liked_date')[:2] e.liker_count = recent_liker.count(); if (e.liker_count == 2): e.postliker1 = get_object_or_404(User, id=recent_liker[e.liker_count - 2].user_id).username e.postliker2 = get_object_or_404(User, id=recent_liker[e.liker_count - 1].user_id).username if (e.liker_count == 1): e.postliker1 = get_object_or_404(User, id=recent_liker[e.liker_count - 1].user_id).username for e in posts: print(e.liker_count) all_comments = Comment.objects.all() commentor_names = {} for e in all_comments: commentor_names[e.id] = get_object_or_404(User, id=e.user_id).username all_replies = Reply.objects.all() replier_names = {} for e in all_replies: replier_names[e.id] = get_object_or_404(User, id=e.user_id).username if (logger_user_id is not None): #return HttpResponse("<h1> hello user "+str(logger_user_id)+"</h1>") return render(request, 'mysite/_index.html', {'posts': posts, 'replies': all_replies, 'comments': all_comments, 'author_name': author_name, 'commentor_names': commentor_names, 'replier_names': replier_names, 'logger_user_id': logger_user_id}) else: return render(request, 'mysite/_index.html', {'posts': posts, 'replies': all_replies, 'comments': all_comments, 'author_name': author_name, 'commentor_names': commentor_names, 'replier_names': replier_names, }) I am new in python I am getting error in my recent django project that is "Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []" What's that error … -
How to find if a model was saved from Django Admin, or elsewhere
Is there a way to identify if the current save() or post_save happened via Django Admin? I want to do something differently for models saved via Admin, than models saved from my Django Rest Framework API. Specifically, I have a create_related_objects I call on post_save of model Transaction, to create related object CalendarInfo. But when creating Transaction via Admin, because the related CalendarInfo object is an inline, I don't need to call that create_related_objects on the Transaction model's post_save. -
Changing Id of django form in form loop
I'm stuck in my code. Need help. This is my front end. I am rendering forms stored in "form_list". The problem is that the forms stored are of same type and thus produce input fields with same "id" and same "name". {% for form in form_list %} <div class="form-group"> <label for="id_video_link">Video Link:</label> {{ form.video_link }} </div> {% endfor %} How can I create different "id" and different "name" in each iteration of for loop's input tag, automatically without having knowledge of no form stored in form_list. I tried {{ forloop.counter}} it didn't worked, perhaps I made some mistake. Also, raw python don't work in template. Thanks in Advance. -
ImportError at /complete/facebook/ No module named 'social_core.contrib'
I started using python-social-auth in django 1.8 a couple weeks ago and was getting ready to work on getting user profile data beyond user name and email from facebook and google when I noticed the "Deprecation notice - 03-12-2016" at https://github.com/omab/python-social-auth. I uninstalled python-social-auth and instlalled social-core in it's place, as I understood was recommended at the page referenced above. I followed the "Migrating from python-social-auth to split social" steps at https://github.com/omab/python-social-auth/blob/master/MIGRATING_TO_SOCIAL.md, and now I'm getting the "ImportError at /complete/facebook/ No module named 'social_core.contrib'" error. Could someone advise me on how to get this solved? -
Is it Possible to Handle Sub-domains in Django without having them registered with registrar?
Is it possible to handle sub-domains in Django without having them registered with registrar, provided i have purchased and setup the domain? Suppose i own example.com. I have purchased it, and setup it to point to my website at some hosting service. But, did not add a sub-domain blog.example.com. Then, can i serve some webpage at blog.example.com? How request.subdomain in django is supposed to be used? -
filter manytomanyfield form 'str' object has no attribute 'get'
I have theses classes in my models.py class Parent(models.Model): title = models.CharField() class Child(models.Model): title = models.CharField() parent = models.ForeignKey(Parent) Class Address(models.Model) title = models.CharField() parent = models.ForeignKey(Parent) child = models.ManyToManyField(Child) Because I wanted "child" field in "Address" model only displays "child" objects that are related to "parent" I wrote this code to my forms.py class AddressForm(forms.ModelForm): class Meta: model = Address fields = ('title', 'parent', 'child') def __init__(self, parent_id, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) self.fields['child'].queryset = Child.objects.filter(parent__id=parent_id) views.py def address(request, parent_id): parent = get_object_or_404(Parent, id=parent_id) if request.method == 'POST': form = AddressForm(request.POST, parent_id) if form.is_valid(): address = form.save(commit=False) address.parent = parent address.save() return redirect('app:address_added') else: form = AddressForm(parent_id) template = "add_address.html" context = {'form': form} return render(request, template, context) The result : the child field displays only the child objects related to parent requested . which what I want. The problem : when I submit I get this error : 'str' object has no attribute 'get' and : if form.is_valid(): is highlighted .. so i think there is a validation problem Help please? -
ValueError: save() prohibited to prevent data loss due to unsaved related object 'sender'
I am trying to create Message obj while creating an object for Quotation. i've tried looking at the official Django docs, but it doesn't seem to apply. I don't know where is the error. class Message(models.Model): sender = models.ForeignKey(User, related_name="sender_user") recipient = models.ForeignKey(User, related_name="recipient_user") sender_read = models.BooleanField(default=False) recipient_read = models.BooleanField(default=False) parent_msg = models.ForeignKey("self", null=True, blank=True, related_name="parent") subject = models.CharField(max_length=255, blank=True, null=True) message = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) and here is my Quotation Table class Quotation(models.Model): editor = models.ForeignKey(Editors) discipline = models.ForeignKey(Discipline, null=True, blank=True) title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) words_count = models.CharField(max_length=255) student = models.ForeignKey(Students, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) modified = models.DateTimeField(auto_now=True, null=True, blank=True) and here is my view function: quotation = Quotation.objects.create( editor=editor, student=student, title=form.cleaned_data['title'], discipline = discipline, description = form.cleaned_data['description'], words_count=form.cleaned_data['words_count'] ) quotation.save() create_message = Message.objects.create( sender= User(username=quotation.student.user.username), recipient=User(username=quotation.editor.user.username), subject=quotation.title, messages=quotation.description ) -
How to combine FormMixin and ListView togethor
Trying to add a form to my homepage view and getting this error when I submit the form: The view app.views.BoxesView didn't return an HttpResponse object. It returned None instead. Here's my code: views.py class BoxesView(ListView, FormMixin): template_name = 'polls.html' form_class = UserRegistrationForm def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = User.objects.create_user(username=username, password=password) user.save() return redirect('/') def get_context_data(self): context = super(BoxesView, self).get_context_data() context['form'] = self.get_form() ... return context def get_queryset(self): pass forms.py class UserRegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'password', ] base.html <form action="" enctype="multipart/form-data" method="post">{% csrf_token %} <div class="registerBox"> {{ form.username }} {{ form.password }} <input type="submit" value="register"/> </div> </form> The form.is_valid() doesn't validate. Any idea what's wrong or a better way to add the form? Keep in mind I need ListView there because i'm returning querysets in get_context_data (I took out that code to remove clutter). -
WHy use a base view in Django?
Why would one use a Base view in Django when this from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request, *args, **kwargs): return HttpResponse('Hello, World!') can be written as def get(request): return HttpResponse('Hello, World!') What is the advantage of the Base view vs the function view? -
RegExp to match anyname/anynamewithid/date/string
I want to write a regular expression to match the given pattern anyname/anyname2/anydate/string anyname: It must accept valid names including underscore (_) anyname2: It must accept valid names including underscore(_) or hiffen (-) anydate: The date must be in the format like 'yyyy-mm-dd'. Ex: 2016-12-10 string: This string contains predefined strings. it needs to match only the required characters like, [computer],[desktop],[laptop]. Other than these 3, it should not match any other. Note: The expression must also match '/' as in the above mentioned pattern -
Can someone please show me how to upload multiple files with Django into a postgresql Database??
I've been trying to figure this out for weeks to no avail unfortunately. Even after looking through hundreds of web pages and tutorials, I still can't figure it out. PLEASE HELP! P.S. Thanks ahead of time :) -
Best way to query postgres db from django to list all users (tab1) which have active book borrows (tab2)?
I have a simple application in Django. The simple logic is kind of book library. Tab1. stores the users: class Readers(Model): last_name = CharField(...) first_name = CharField(...) Tab2. stores the book borrows: class BookBorrows(Model): index = IntegerField(db_index=True, ...) reader = ForeignKey('Reader', ...) book = ForeignKey('Book', ...) active = BooleanField(...) I am struggling to figure out what is the proper solution to get: 1. List of all Readers with at least one borrowed book (the field active==True). 2. List of all Readers without any currently borrowed book (the field active==False). After some serche I am thinking about django .raw('QUERY ...') or maybe is there a more django-friendly way to achieve this? P.S.:this is my first question posted to SO. -
Django form.save() not taking updated form.cleaned_data
I'm lost here and can't figure out what I'm missing, which is probably something stupid, but I need another set of eyes because as far as I can tell this should be working. What I'm trying to do is allow my users to enter phone numbers in ways they are used to seeing, but then take that input and get a validated international phone number from Twilio and save it. By definition that means it will be in the following format - which is the format I need to have it in the database so that it interacts well with another part of the application: +17085551212 I've debugged to the point there I know the values are coming in correctly, everything works right if I get an invalid number, etc. For some reason, the updated value is not being passed back to the form when I set form.cleaned_data['office_phone'] prior to the form.save(). So I am getting the original number (708) 555-1212 in the database. forms.py class ProfileForm(forms.ModelForm): office_phone = forms.CharField(max_length=20, label="Office Phone") views.py if form.is_valid(): print (form.cleaned_data['office_phone']) pn = form.cleaned_data['office_phone'].replace(" ","") try: response = validator.phone_numbers.get(str(pn)) form.cleaned_data['office_phone'] = str(response.phone_number) print form.cleaned_data form.save() success_message = "Your changes have been saved" except: error_message … -
How to prepopulate an Django Update form and write it back to the database
I'm new at programming Django and Python and I'm struggling a lot right now :(!! I created an update/edit form with Django Model forms, but it just doesn't prepopulate the form fields and post it to the database at the same time. I think the problem lies here: "form = AdvertForm(request.POST or None, request.FILES or None, instance=form)" Without "request.POST or None, request.FILES or None", it does prepopulate the fields but doesn't update the database... That's my views.py: def update_advert(request, id): if not request.user.is_authenticated(): return render(request, 'forum/login.html') else: form = get_object_or_404(Advert, pk=id) if request.method == 'POST': form = AdvertForm(request.POST or None, request.FILES or None, instance=form) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('forum:user_account') else: form = AdvertForm(instance=form) context = {'form': form} return render(request, 'forum/update_advert.html', context) In the moment it looks like this, when I try to open the update form: opening the form --> not prepopulated :( -
What are the uses for . in Django?
What are the uses for . in Django? One use I know is to indicate a directory like 'directory.file'. Can somebody give a complete use case? -
Django ChartIt, 'Expecting a list in place of'
I am trying to display a pie chart in Django, associating the name of a tree condition with the number of trees in that condition. I can get the chart to display, but without the names of the conditions. If I try to get it to include the names of the conditions, I get the error, "Expecting a list in place of:" My models look like this: class TreeCondition(models.Model): name = models.CharField(max_length=256) class Tree(models.Model): condition = models.ForeignKey(TreeCondition, related_name='trees_in_this_condition') and my view: def uf_chart(request): condition_data = PivotDataPool( series = [ {'options': { 'source': TreeCondition.objects.all(), 'categories': ['name'] }, 'terms': {'condition_count': Count('trees_in_this_condition')} } ] ) def condition_name(id_condition): names ={1: 'Excellent', 2: 'Very Good', 3: 'Good', 4: 'Fair', 5: 'Poor', 6: 'Critical', 7: 'Dead', 8: 'Unknown'} return names[id_condition] condition_chart = PivotChart( datasource = condition_data, series_options = [{'options':{ 'type': 'pie', 'stacking': False}, 'terms': {'name': ['condition_count']} }], chart_options = {'title': {'text': 'Tree Conditions'}, } ) args = {'condition_data': condition_data, 'condition_chart': condition_chart} return render(request, 'uf_chart.html', args) The demo on ChartIt's pie chart example would have me go like this: def uf_chart(request): condition_data = PivotDataPool( series = [ {'options': { 'source': TreeCondition.objects.all(), 'categories': ['name'] }, 'terms': {'condition_count': Count('trees_in_this_condition')} } ] ) def condition_name(id_condition): names ={1: 'Excellent', 2: 'Very … -
Python/Django crash on gunicorn on Heroku
I've deployed my app to Heroku and am getting the following error in the logs upon loading the page: 2016-12-09T22:47:56.020392+00:00 heroku[slug-compiler]: Slug compilation started 2016-12-09T22:47:56.020401+00:00 heroku[slug-compiler]: Slug compilation finished 2016-12-09T22:47:56.001478+00:00 heroku[web.1]: State changed from crashed to starting 2016-12-09T22:48:00.770182+00:00 heroku[web.1]: Starting process with command `gunicorn projectname.wsgi --log-file -` 2016-12-09T22:48:03.282956+00:00 heroku[web.1]: Process exited with status 127 2016-12-09T22:48:03.180446+00:00 app[web.1]: bash: gunicorn: command not found 2016-12-09T22:48:03.300446+00:00 heroku[web.1]: State changed from starting to crashed For this person, they received the same issue and solved it because they had not installed gunicorn. However, I do have gunicorn installed in my requirements.txt, using "pip install gunicorn" Here is my requirements.txt file: $ cat requirements.txt boto==2.43.0 click==6.6 click-plugins==1.0.3 cligj==0.4.0 descartes==1.0.2 dj-database-url==0.4.1 Django==1.10.4 django-bootstrap3==7.1.0 django-geojson==2.9.1 django-leaflet==0.19.0 django-storages==1.5.1 django-tables2==1.2.6 django-widget-tweaks==1.4.1 Fiona==1.7.1 GeoAlchemy2==0.4.0 gunicorn==19.6.0 jsonfield==1.0.3 munch==2.0.4 numpy==1.11.2 pandas==0.19.1 psycopg2==2.6.2 pyproj==1.9.5.1 python-dateutil==2.6.0 pytz==2016.7 requests==2.12.3 six==1.10.0 SQLAlchemy==1.1.4 Any tips? Thank you! -
Iterate through nested Django REST Framework API with KnockoutJs
I am building an application and using Django & Django REST Framework for the backend and KnockoutJS to handle my lists on the front-end. I've used Knockout before but it was with a simple JSON list, but I am having trouble figuring out how to grab the nested JSON objects from the API and display in my template. It will print the object structure to the console, so I know I am connected, but at the same time will print the error Uncaught TypeError: Cannot read property 'fromJson' of undefined(…); if I can properly iterate over the objects, I believe it may also fix the Uncaught error. Thank you. <script> $(document).ready(function () { var url = "/api/plaques/"; var viewModel = {}; $.getJSON(url, function (data) { console.log(data); viewModel.model = ko.mapping.fromJson(data); ko.applyBindings(viewModel); }); }); </script> <table data-bind="foreach: items"> <tr> <td data-bind="text: id"></td> ... </tr> </table> -
angular2 and django when handling forms
How can somebody make django forms and angular2 framework play together nicely? I like how django works with forms by making it's creation and validation super-easy. However, same can be said about angular2 with it's rich syntax. In terms of loose coupling, I would assume that creating form should be handled in client side. However, creating forms looks equally enticing on both django and angular2. Which path should be taken? Is creating form using django redundant and the form should be created at client-side using angular2, so that django only serves the purpose of validating?