Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django-cms to edit django templates and add static media
I installed django-cms in my current existing django project but I don't know how to access my exiting django templates by django-cms to edit those. Done with: include {% cms_toolbar %} straight after the <body> tag I added this to the top of my template: {% load cms_tags menu_tags sekizai_tags static %} Thanks in Advance -
django class is not giving Httpresponse
i have copy pasted a django pdf generation class.it is having two parts js and django, in js i am trying fetch data from button on click and in django end i am getting those datas with request.GET.get parameter and sending them to API to get desired data so i can parse them and can give Httpresponse as pdf, but problem is every code is working fine,i am hitting the ajax on button click and getting data in backend and able to hit API, but i am not able to give Httpresponse! When i write button in an a tag with < a href={% utl 'app_name':'url_name' %}><button></button></a> its calling the function and gives Httpresponse as pdf but not with this ajax button on click method. ajax $('.btn-download').click(function(){ $.ajax({ url:'{% url 'tom:detail' %}', method:'GET', data:{ 'data-id':$(this).attr('data-id'), 'data-order':$(this).attr('data-order') }, } }) }) view.py class GeneratePDF(View): def get(self, request, *args, **kwargs): user_id = request.session['user_id'] invoice_id = request.GET.get('data-id') order_number = request.GET.get('data-order') parameter = { 'invoice_id': invoice_id, 'order_number': order_number, 'user': user } print(parameter) url = '{}{}'.format(API_URL, '/rest/getOrderDetail') r = requests.post(url=url, params=parameter) context = { "name": r.json()['name'], } pdf = render_to_pdf('pdf/contract.html',context) response= HttpResponse(pdf, content_type='application/pdf') return response urls.py url(r'^contract-pdf$',GeneratePDF.as_view(),name='detail'), -
Adding custom HTTP headers to Wagtail pages
I'm looking to make a new Wagtail site production-ready and have used some Django security middleware settings such as SECURE_BROWSER_XSS_FILTER and SECURE_HSTS_SECONDS. One HTTP header which doesn't seem to be provided for in the security middleware is Expect-CT. I'd like this header to have a value, (preferably based on (a) setting(s) in the production.py settings file) like: max-age=31536000, enforce, report-uri="https://username.report-uri.com/r/d/ct/enforce" What would be a good way to implement this and other custom HTTP headers in Wagtail? I have done some reading and experimenting, but I'm currently a Wagtail/Django/Python beginner and am not sure how to proceed. Thanks. -
Embedding a Form Builder page in another Wagtail page
The Wagtail Form Builder documentation states: form_page.html differs from a standard Wagtail template in that it is passed a variable form, containing a Django Form object, in addition to the usual page variable. But in my current project, I need to embed a contact form (implemented as a Form Builder page) in another page. In the model for that target page, I'm using a PageChooserPanel to let an editor select the form page to embed. In other words: class TargetPage(Page): [...snip...] contact_form = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) content_panels = Page.content_panels + [ [...snip...] PageChooserPanel('contact_form', 'FormPage'), ] My problem is in the template for the target page. I can access the attributes of the form page via page.contact_form, but since this page doesn't have a form object passed in, I can't figure out how to render my fields. I am guessing that I need to override my target page's get_context() so that it includes the form object I need. But I can't figure out how to get that object. Can some kind soul put me on the right track? -
How can I call my function in my utils.py of my Django app?
I am trying to call python manage.py load_json data.json but I get Unknown command: 'load_json'. Am I missing something? The utils.py is not in my core app. I also tried python manage.py inventory.load_json data.json and that didn't work either, inventory is the app that I have my utils.py file in. -
Calculating values from check boxes and input forms django
How can I get values from checkboxes and forms and calculate them in next template? I have checkbox A, checkbox B, check box C and then I want to user select value and after submitting it, to calculate the value. Im making some kind of calculator and i done it in tkinter but i know want to make it as webapp . Thank you all from django.db import models from django import forms from django.forms import ModelForm from django import forms # Create your models here. COLOR_CHOICES = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ) class Input(models.Model): r = models.BooleanField(null=True,default='2',choices=COLOR_CHOICES,max_length=10) b = models.BooleanField(null=True,default='2',choices=COLOR_CHOICES,max_length=10) class InputForm(ModelForm): class Meta: model = Input fields = '__all__' And here is my views.py file : from django.shortcuts import render from django.http import HttpResponse from .models import InputForm # Create your views here. def index(request): if request.method =='POST': form = InputForm(request.POST) if form.is_valid(): form = form.save(commit=False) return present_output(form) else: form = InputForm() context = {'form' : form} return render(request,'hw1.html',context) def present_output(form): b = form.b r = form.r k = b - r return HttpResponse(k) -
Create a string that lists the amount of object types in a queryset
I'm trying to create a string that prints out the totals of each type of item in a queryset for the following model. class Booking(models.Model): _JACKET_SIZES = ( ('s', 'Small'), ('m', 'Medium'), ('l', 'Large'), ('xl', 'X Large'), ('xxl', '2X Large'), ('unknown', 'Unsure'), ) ... jacket_size = models.CharField(max_length=7, choices=_JACKET_SIZES, default='small', null=True) ... Basically, I'm trying to collate a list of jacket sizes into a string. This is what I have attempted already but I am sure there is an easier way. bookings = Booking.objects.all() jackets = {} for booking in bookings: jackets.setdefault(booking.get_jacket_size_display(), jackets.get(booking_get_jacket_size_display(), 0) + 1) o = ', '.join('{}: {}'.format(k,v) for k,v in jackets.items()]) Lets assume that the queryset contains 4 objects. 1 Small jacket, 2 medium jackets and 1 large jacket. The result of the above code only seems to provide 1 Medium, not 2 as if it was ignoring the second medium jacket. -
How to run a function after x time as defined in a database?
I have this issue I cannot solve: If I save a value in a row in some table which defines a period of x time in seconds (e.g. 50000), how can I get something to happen after that time period is up? E.g. run a function which sends mail to the user. The counter would begin when the row is inserted into the table, and I would need the 'counter' to run in the background of a server (and run with many other 'counters' in parallel for each row inserted). This is for a Django project. Any help is much appreciated. -
Python Social Auth with Django - how to retrieve extra data?
For my first Django project I wanted to tie up Python Social Auth for the social authentication (namely Facebook). Django==2.0 social-auth-app-django==2.1.0 social-auth-core==1.7.0 How can I retrieve extra data from the logged in user's profile? My goal is to filter the logged in users to custom groups based on FB groups they are members of. However at this point I can't even get the email, just the username. In my settings.py: SOCIAL_AUTH_FACEBOOK_KEY = 'xxxx' SOCIAL_AUTH_FACEBOOK_SECRET = 'xxxx' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'groups_access_member_info'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email', 'edges': 'groups' } The pipeline is the basic pipline: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) I'm not asking for complete code, any help would be much appreciated. Thank you in advance! -
Django dynamic choice field, appointments slots
I need some direction on how to create a dynamic choice field for a form. The context is that of appointments. I want to give people the ability to book their own appointments however it needs to be based on some criteria. The criteria being the date, time, and the number of people. I want the time field to be a dynamic choice field. Based on the date and party size "psize" I originally thought that this could be achieved via filter, aggregate, and sum. Using the input from whomever was filing out the from. I was thinking that I could take the date and the party size from the form and use that to filter and sum the number of people that chose the same selection (this is important because I want 15 or less people signed up for any given time period) my time periods are in 15 minute increments and are listed in a tuple (like a regular choice field). Any ideas? models.py class Reservation(models.Model): """This tuple is for the Inside, Outside, First Available drop down menu for the reservations tab """ INSIDEOUTSIDE = ( ('Inside','Inside'), ('Outside', 'Outside'), ('First Available', 'First Available'), ) STATUS = ( ('Reservation','Reservation'), … -
Django admin: how to add Save button to the top for list view
When there are list editable fields, a Save button appears at the bottom in Django admin list view. (Surrounded with a red box in the picture). How to add the same Save button to the top as well? (The expected result is surrounded with a green box in the same picture.) For change list view Django provides a simple solution, but there seems to be no built-in option for list view. -
Unable to render variable in django template that contains HTML
I've read through all the other stackoverflow questions regarding this issue and none of those solutions work for me. I'm passing down a variable to a django template that contains an html. For example <strong>example</strong>. I mark this string as mark_safe() before storing it in my variable. When I load it into the template and load the page in my browser it shows the html as plain text, <strong>example</strong>. If I look at it in the chrome console the only thing that is different is that the text is surround with parenthesis. So it would look like this, "<strong>example</strong>" Like I said I've read through all the other stackoverflow posts and marked the variables using the {% autoescape off %} tags and I've tried 'safe' tag. These will remove the escaping, but the HTML still doesn't render. Below is the actual html unescaped. I'm wondering if it's the space in front of it? &lt;p&gt;Modern Comics That Are Valuable But Often Overlooked and Should Be Sought Out In Dollar Bins and In Your Own Collection&lt;/p&gt; <p><strong><em>Its Like Having $-Ray Vision</em></strong></p> Thanks for the help. -
how can I get a query set from multiple levels of sets / foreign keys?
If A contains a set of B and B contains a set of C, then I am looking for a way to start with A and end up with a query set of C. A simple example: class Book(models.Model): name = models.CharField(max_length=64) class Page(models.Model): number = models.IntegerField() book = models.ForeignKey(Book) class Paragraph(models.Model): number = models.IntegerField() page = models.ForeignKey(Page) def query(): books = Book.objects.all()\ .prefetch_related('page_set', 'page_set__paragraph_set') for book in books: pages = book.page_set # I need to do something like this paragraphs = pages.all().paragraph_set # or paragraphs = book.page_set.paragraph_set # this works, but results in one query for EVERY book, # which is what I need to avoid paragraphs = Paragraph.objects.filter(page__book=book) # do stuff with the book #... # do stuff with the paragraphs in the book # ... How do I get a query set of paragraphs from just a Book instance? The named args syntax for Django queries supports an infinite level of nesting of sets/foreign key relationships, but I can't find a way to use the ORM mapping to actually get a related query set from the top-down. And getting query-set from the bottom-up negates the benefits of prefetch_related/select_related. The above example is a simplified version of what … -
Django Form Inputs Won't Show Up - Only See Submit Button
I'm playing around with the forms framework, but the inputfields for my form will not show. I can only see the submit button. forms.py from django import forms class NameForm(forms.Form): name = forms.CharField(label='Enter your name', max_length=100) email = forms.EmailField(label='Enter your email', max_length=100) views.py from django.shortcuts import render, from .forms import NameForm def get_name(request): if request.method == 'POST': form = NameForm(request.POST) else: form = NameForm() return render(request, 'index.html', {'form': form}) index.html <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> The responding html, when showed in my browser is the following: <html> <head></head> <body> <form action="" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="pSzpDAHu89XC8Re0aDYMOETDS30l3HozZWlL4fF0LljYkrXFCWIiOYCzYwOWtqjk"> <input type="submit" value="Submit"> </form> </body> </html> I hope you are able to help or point me in some direction. -
Adding items to many-many field in a model not showing up
I am attempting to add items to a many-many field in a model. However those items are not showing up as added. This is what my code looks like.In this code I am populating dummy values This is what my model looks like class modelEmployee(models.Model): class Meta: verbose_name_plural = "Employee (Contractors)" # Name to display in admin interface user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200, unique=False, blank=False, null=True) employee_image = models.ImageField(upload_to='images/',null=True,blank=True,default='images/defaultServiceProvider.png') employee_zip = models.IntegerField(default=0) skills = models.ManyToManyField(modelSkill, blank=True) location = models.PointField(srid=4326,max_length=40, blank=True,null=True) objects = GeoManager()#models.GeoManager() #GeoDjango Model API This is the method that adds dummy data to the model.The employee gets created fine however the skills (many-to-many fields) never get updated with that employee.gskills contains instances of modelSkill and gskills[val] works fine and returns back a random instance of modelSkill def populateEmployees(): modelEmployee.objects.all().delete() temp = gusers[0:len(gusers)-1] for user in temp: emp = modelEmployee.objects.create(user=user, title="Instant Landscaping",employee_image="images/populate/unknown.jpeg", ) for x in range(6): val = random.randint(0, len(gskills) - 1) res = gskills[val] emp.skills.add = gskills[val] emp.save() Any suggestions on what I might be doing wrong ? -
Why does reCaptcha return timeout-or-duplicate error?
I'm trying to implement Google reCaptcha v2 on a wizard form. If I complete the captcha and submit the form without having filled out the other fields, it returns result: {'success': True, 'challenge_ts': '2018-10-30T21:47:25Z', 'hostname': '127.0.0.1'}. But if I fill out all the required fields so that the form is valid it returns result: {'success': True, 'challenge_ts': '2018-10-30T21:47:25Z', 'hostname': '127.0.0.1'}. {'success': False, 'error-codes': ['timeout-or-duplicate']} [30/Oct/2018 21:47:44] "POST /register/ HTTP/1.1" 200 3912 rendering the form invalid, and throwing an invalid captcha error. I'm guessing that the problem is that the captcha is being validated twice. My verify captcha logic is in the form clean method, so maybe that is the problem: def clean(self): cleaned_data = super(Form, self).clean() recaptcha_response = self.request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) print (result) if result['success']: return cleaned_data else: raise forms.ValidationError('Error.') I'm wondering if it's conflicting with my done method in the view: def done(self, form_list, **kwargs): data = {k: v for form in form_list for k, v in form.cleaned_data.items()} Any ideas on how to fix this? -
Installing application in Django
I'm using django and this peice of code in settings python file doesn't work because it can't read ".apps.LabConfig" !!! INSTALLED_APPS = [ 'Lab.apps.LabConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', -
django using multiple session engines
I would like to use multiple session engines in my django app : one for admin using django.contrib.sessions.backends.db and one for an other usage using django.contrib.sessions.backends.signed_cookies. Is it possible ? How ? -
Access updated values in prefetched self recursion set
I have a model class Vertex(models.Model): pmap = models.ForeignKey('PMap',on_delete=models.CASCADE) elevation = models.FloatField(default=0) flow_sink = models.ForeignKey( 'Vertex', on_delete=models.CASCADE, related_name='upstream', null=True) and another model with the following function class PMap(models.Model): def compute_flux(self, save=False): vertices = self.vertex_set.order_by('-elevation').prefetch_related('flow_sink') # Init flux for vert in vertices: vert.flux = 1.0 / len(vertices) # Add flux from current to the downstream node. for vert in vertices: if vert.id != vert.flow_sink.id: vert.flow_sink.flux = vert.flux The function compute_flux() function is supposed to add the flux value from the currently visited vertex to its flow_sink (which in turn is another vertex). It should do this recursively, so that when when it reaches a vertex that has had it flux updated previously it should yield that value to its own flow_sink. Sadly, this doesn't work. All vertices end up with the initial flux = 1.0 / len(vertices). I think the reason is that we're updating the vertices in the prefetched set prefetch_related('flow_sink') rather than the vertices in the vertices set. Thus vert.flux in the last loop will never have any other value than the one set in the first (init) loop. How can I fix this or work around the problem? -
How to solve reason=string error in py.test?
Im trying to run a code in anaconda prompt but I just stuck in this: How can i solve it? Thank u very much tests/SmartMT/test_exportDialog.py::TestExportDialog::test_defaults PASSED [ 5%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_directory_change ERROR [ 10%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_dpi ERROR [ 15%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_export ERROR [ 21%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_file_name_change ERROR [ 26%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_file_type_change ERROR [ 31%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_eps ERROR [ 36%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_jpeg ERROR [ 42%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_jpg ERROR [ 47%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_pdf ERROR [ 52%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_pgf ERROR [ 57%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_png ERROR [ 63%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_ps ERROR [ 68%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_raw ERROR [ 73%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_rgba ERROR [ 78%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_svg ERROR [ 84%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_svgz ERROR [ 89%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_tif ERROR [ 94%] tests/SmartMT/test_exportDialog.py::TestExportDialog::test_transparent_tiff ERROR [100%] =================================== ERRORS ==================================== __________ ERROR at setup of TestExportDialog.test_directory_change ___________ Error evaluating 'skipif' expression False Failed: you need to specify reason=STRING when using booleans as conditions. _________________ ERROR at setup of TestExportDialog.test_dpi _________________ Error evaluating 'skipif' expression False Failed: you need to specify reason=STRING when using booleans as conditions. _______________ ERROR at setup of TestExportDialog.test_export ________________ Error evaluating 'skipif' expression False Failed: you need to specify reason=STRING when using booleans as conditions. __________ ERROR at setup of TestExportDialog.test_file_name_change ___________ Error evaluating 'skipif' expression False Failed: you need to specify reason=STRING when using booleans as conditions. __________ ERROR at setup of TestExportDialog.test_file_type_change … -
Angular+Django form validation at the backend
I have Angular(6) component - a form with bunch of inputs I want to validate all inputs on server side - Django (submit, validate using django-forms, and in case of errors - show these errors using angular) what's the best approach to do that ? -
Creating a form with an update and delete button in Django
Current form updates appropriately, but the delete button does the same actions as the update button. I would like the delete button to delete a selected value from the database. I have tried assigning values to the button as well as replacing the button with an 'a' tag. This is the employee update page: <h5>Edit Work Record</h5> <div class="divider"></div> <div class="divider"></div> <form method="post" action="{% url 'employd:workrecordupdate' view.object.pk %}"> <div class="row"> {% csrf_token %} {{ form | materializecss:'s6' }} <div class="col s6 left-align"> <button type="submit" class="waves-effect waves-yellow green lighten-2 btn-small"> <i class="material-icons left">save</i>update </button> </div> <div class="col s6 right-align"> <!-- <a class="waves-effect waves-darken btn-small red" href="delete">delete</a> --> <button type="submit" value="delete" class="waves-effect waves-darken btn-small red"> <i class="material-icons left">delete</i>delete </button> </div> </div> </form> This corresponds to the following links from my urls.py : # ex: /employd/wr/12 -- Update a WorkRecord path('wr/<int:pk>/', views.WorkRecordUpdateView.as_view(), name='workrecordupdate'), # ex: /employd/wr/create -- Create a new WorkRecord path('wr/create', views.WorkRecordCreate.as_view(), name='workrecordcreate'), # ex: /employd/wr/delete -- Delete an existing WorkRecord path('wr/<int:pk>/delete', views.WorkRecordDelete.as_view(), name='workrecorddelete'), These direct to the following views: class WorkRecordUpdateView(SuccessMessageMixin, generic.UpdateView): """ Display WorkRecord update form, for use inside a modal """ model = WorkRecord fields = '__all__' template_name_suffix = '_update' success_message = "Update successful." def get_success_url(self): return self.request.META.get('HTTP_REFERER') and … -
Django Rendering HTML in a template give bytes
In my django application, I am manually rendering a page and giving it to a template to include : def get_context_data(self, **kwargs): page = render(self.request, test_absolute_path, context, content_type=None, status=None, using=None) soup = BeautifulSoup(page.content, 'html.parser') soup.dosomestuff() page.content = str(soup.decode()).replace('\n','') context['subtests'].append(page) return context Then including the rendered HTML into a template using the safe tag : {{ page.content | safe }} I do have my tags included but the text appears like a bytearray and the encoding isn't right for some reason : b' My text Cat\xc3\xa9gorisation S\xc3\xa9quqsdazeences R\xc3\xa9ponses associ\xc3\xa9es Fluidit\xc3\xa9 Notice that I also had to replace all \n with nothing in the code. -
Set innerHtml of select element based on variable
How can I set the default value of an element by comparing the innerHTML to a variable? This is the select box <select name="added_by" class="form-item-added_by" required="" id="id_added_by"> <option value="" selected="">---------</option> <option value="1">admin</option> </select> This is what I've tried, but nothing happens. <script type = "text/javascript"> $(document).ready(function(){ {%for note in notes%} added_by = "{{note.added_by}}" $(".form-item-added_by").val(added_by).change(); {%endfor%} }); </script> -
Django validate_unique at the end of transaction
I have a model: class BikePhoto(models.Model): photo = models.ImageField(verbose_name=_('zdjęcie'), upload_to='bikes') bike = models.ForeignKey(Bike, on_delete=models.CASCADE, verbose_name=_('motocykl')) position = models.IntegerField(verbose_name=_('Pozycja'), null=True) class Meta: unique_together = (('position', 'bike'),) And there are some instances of this in my DB. For a specific bike we have a list of 3 BikePhotos with positions 1,2 and 3. I want to reorder them, so that I want these three BPs with positions 2, 1 and 3. But unfortunately I get and error while saving first BP (old: 1, new 2) Key ("position", bike_id)=(1, 2) already exists. This is a code that I use to reorder photos: def update_image_positions(request): if request.POST: items = request.POST.getlist('items[]') bps = [] for position, item in enumerate(items): bp = BikePhoto.objects.get(id=item) bp.position = position bps.append(bp) [i.save() for i in bps] return JsonResponse({'result': 1}) I have also tried to use transaction.atomic, but it actually does not work as I supposed so I dropped it. I thought that it will check for unique constraints at the end of transaction, but it checks it whenever I run BP.save(). Is there a way to swap position of those BPs? I have a solution in my mind, but I don't actually like it. I could first set position to …