Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
make a field required when this is under scope with other fields
the content of my field depends to another camps. for this, it is impossible make mi field required. can someone help me? { 'name': 'name', 'col_dv': 'col-md-6 col-sm-6 col-xs-12', 'params': { 'html_params': { 'ng-required': 'true' }, 'div_params': { 'ng-value': 'formData.name = formData.nombre + \' \' + formData.apellido', } } }, my ng-required does not work because my field is under the scope of nombre and apellido. (i think) -
Django URL redirection issue
Hi guys I am trying to use a django App that I found called django-invitations (https://github.com/bee-keeper/django-invitations) It use an mail invitation to create a user. I created a registration app called registration using a view: def registerCandidate(request): registered = False if request.method == "POST": Candidate_form = CandidateForm(data=request.POST) if Candidate_form.is_valid(): user = Candidate_form.save() user.set_password(user.password) user.is_candidate = True user.save() registered = True else: print("Error!") else: Candidate_form = CandidateForm() return render(request,'Candidate_form_registration.html', {'Candidate_form':Candidate_form, 'registered':registered}) and an url.py url(r'^candidate_register/$', views.registerCandidate, name='Candidate_register') The thing isI tried to configure like the documentation said in my setting.py INVITATIONS_SIGNUP_REDIRECT = 'registration:registerCandidate' But I cannot manage to use the right redirection to work could you help me ? -
Wagtail Embed Finder not matching twitter and facebook urls
I'm using Wagtail 1.12.1 and having trouble getting the oembed provider finders to match twitter, facebook post/video, and vimeo urls. There may be others but so far I have only had success with youtube and instagram urls. I encountered the problem when trying to create a StructBlock which has an EmbedBlock but also tried directly adding urls to {% embed %} tags and using the get_embed method neither of which worked with Twitter and Facebook URLs. Has anyone had success with using Facebook and Twitter embeds with the oembed finders and might know what I am doing wrong? I've tried leaving WAGTAILEMBEDS_FINDERS out of my settings, then added it will all_providers set and finally tried only importing the ones that I needed. It didn't have any effect. settings.py from wagtail.wagtailembeds.oembed_providers import youtube, twitter, vimeo, instagram, facebook_video, facebook_post, twitter, soundcloud, tumblr WAGTAILEMBEDS_FINDERS = [ { 'class': 'wagtail.wagtailembeds.finders.oembed', 'providers': [youtube, twitter, vimeo, instagram, facebook_video, facebook_post, twitter, soundcloud, tumblr] } ] An example of the Twitter StructBlock I created. blocks.py from wagtail.wagtailcore import blocks from wagtail.wagtailembeds.blocks import EmbedBlock class TwitterEmbedBlock(blocks.StructBlock): tweet_url = EmbedBlock(required=True) show_cards = blocks.BooleanBlock(required=False, default=True) show_conversation = blocks.BooleanBlock(required=False, default=True) class Meta: template = 'blog/blocks/tweet.html' When I save that I've checked the β¦ -
Regarding Django erroe message TemplateDoesNotExist at /
I am trying an application for a blog by django, but the top page (post_list.html) is not displayed. The following error message will be displayed. TemplateDoesNotExist at / blogapp3/post_list.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.4 Exception Type: TemplateDoesNotExist Exception Value: blogapp3/post_list.html Exception Location: F:\01_pro\kaso3\lib\site-packages\django\template\loader.py in select_template, line 53 Python Executable: F:\01_pro\kaso3\Scripts\python.exe Python Version: 3.6.2 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: F:\01_pro\blogpro3\blogapp3\templates\blog\blogapp3\post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: F:\01_pro\kaso3\lib\site-packages\django\contrib\admin\templates\blogapp3\post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: F:\01_pro\kaso3\lib\site-packages\django\contrib\auth\templates\blogapp3\post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: F:\01_pro\blogpro3\blogapp3\templates\blogapp3\post_list.html (Source does not exist) I had been pointed out that the file structure is wrong from other website, but I think this file doesn't seem to be strange. file structure is as follows. F:\01_PRO\BLOGPRO3 β db.sqlite3 β manage.py β ββblogapp3 β β admin.py β β apps.py β β forms.py β β models.py β β tests.py β β urls.py β β views.py β β __init__.py β β β ββmigrations β β β 0001_initial.py β β | 0002_auto_20170905_1930.py β β ββ __init__.py β β β β β ββstatic β β ββcss β β β blog.css β β β β β ββjs β β β ββtemplates β ββblog β β about.html β β β¦ -
Store the IDs in the Parent Model of the Child Models which are currently related via ForeignKeys
I have three models, currently i am using an url like so to do updates and get content: http://localhost:8000/manuscripts-api/manuscriptlibrary/28/ My question relates to the approach i should use so that i can include in my ManuscriptItem model the IDs of the related Libraries and Settings. What kind of fields can i add to the ManuscriptItem model that does this? My models: class ManuscriptItem(models.Model): """Represents a single manuscript's content""" author = models.ForeignKey('accounts_api.UserProfile', on_delete=models.CASCADE) title = models.CharField(max_length=255, blank=True) content = models.CharField(max_length=99999999, blank=True) def __str__(self): """Django uses when it needs to convert the object to a string""" return str(self.id) class ManuscriptLibrary(models.Model): """Represents a single manuscript's library""" manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE) bookmarks = models.CharField(max_length=99999999) history = models.CharField(max_length=99999999) def __str__(self): """Django uses when it needs to convert the object to a string""" return str(self.manuscript) class ManuscriptSettings(models.Model): """Represents a single manuscript's settings""" manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE) citation_suggestions = models.BooleanField(default=False) terminology_suggestions = models.BooleanField(default=False) paper_suggestions = models.BooleanField(default=False) def __str__(self): """Django uses when it needs to convert the object to a string""" return str(self.manuscript) -
django-jinja: intcomma filter not found
I have my settings configured as described in the django-jinja documentation INSTALLED_APPS = ( ... 'django_jinja', 'django_jinja.contrib._humanize', ... ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'APP_DIRS': True, 'OPTIONS': { 'extensions': DEFAULT_EXTENSIONS + [ ... ], ... }, }, ] USE_I18N = True USE_L10N = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) gettext = lambda s: s LANGUAGES = ( ('nl', gettext('Dutch')), ('de', gettext('German')), ) But when I do {{ somevalue|intcomma }} I get the error: django.template.exceptions.TemplateSyntaxError: ("no filter named 'intcomma'",) What could be the cause of this? -
Failed lookup for key [form] in u' on crispy formset
I keep getting Failed lookup for key [form] in u'(...) when I click submit button. I cant figure whats is happening or why. I dont know if is crispy, form or views problem. Maybe a tip is that i put extra=1 in formset but only shows 1 line. form.py class CotizacionForm(forms.ModelForm): class Meta: model = Cotizacion fields = ('fecha', 'local','estado_pago','estado_trabajo','detalle_monto', 'observacion',) widgets = {'fecha': forms.DateInput(attrs={'id': 'datetimepicker12'})} def __init__(self, *args, **kwargs): super(CotizacionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-cotizacion-form' self.helper.form_method = 'post' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-3 text-left' self.helper.field_class = 'col-lg-9' self.helper.layout = Layout( Div( Field('fecha',style="margin-bottom: -10px;"), Field('local',style="margin-bottom: -10px;"), Field('estado_trabajo', style="margin-bottom: -10px;"), Field('estado_pago', style="margin-bottom: -10px;"), Field('detalle_monto', style="margin-bottom: -10px;"), css_class="col-lg-6" ), Div( Field('observacion',style="max-height: 100px;"), css_class="col-lg-6" ), ) class TrabajoForm(forms.ModelForm): class Meta: model = Trabajo fields = ('unidad','valor','actividad','cuadrilla') descripcion = forms.CharField( label = "Escriba el detalle del trabajo", max_length = 200, required = True, ) def __init__(self, *args, **kwargs): super(TrabajoForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-trabajo-form' self.helper.form_method = 'post' # self.helper.form_action = reverse('submit_form') # self.helper.add_input(Submit('submit', '+', css_class='btn btn-rounded btn-sm btn-icon btn-default text-right')) self.helper.form_class = 'form-inline col-lg-12' self.helper.field_template = 'bootstrap3/layout/inline_field.html' self.helper.layout = Layout( Div( InlineField('descripcion', style="width:650px" ), 'unidad', 'valor', 'actividad', 'cuadrilla', HTML("<a class=" + "delete-row" + " href=" + "javascript:void(0)" β¦ -
Django rest framework full-text search not finding word "Will"
I'm developing a Django app with an API REST using Django REST Framework. I have implemented a search filter for the User model in which I want to use a Full-text Search for the field 'name'. It is working fine for every name or word except for word "Will" or "will". I've tried other similar words like "wall" or "well" and it just worked fine. Hope anyone has a clue, thank you very much! -
django - dynamic field's verbose_name/label
i am searching for the right way to implement the same model data but with different fields titles corresponding to the group the user belong to. for example: if the model field name is "text", for group1 admin will define that the verbose_name/label = "text1", so: 1. when the model form open for update "text1" will be showen. make the fields headers of the table (at the templates) that shows a model list result by the same behavior. and of course solution with good performance and cost. would much appreaciate some guidence, thanks -
How to loop within a loop in django while passing multiple context
I having trouble trying to access the foreign key element from my template. I am trying to pass multiple contexts using class view like this: class HomeView(ListView): template_name = "homepage/home.html" queryset = Author.objects.all() def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['author_links'] = Author_link.objects.all() context['categories'] = Category.objects.all() context['extra_links'] = Extra_link.objects.all() context['poems'] = Poem.objects.all() return context my models.py file: class Author(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Author_link(models.Model): url_text = models.CharField(max_length=100) url = models.CharField(max_length=200) author = models.ForeignKey(Author) def __str__(self): return self.url_text class Category(models.Model): name = models.CharField(max_length=100) description = models.TextField() class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name class Extra_link(models.Model): url_text = models.CharField(max_length=100) url = models.CharField(max_length=200) category = models.ForeignKey(Category) def __str__(self): return self.url_text however when I am trying to loop through the context I can't seem to access the foreign key of each item: {% for author in object_list %} <li class = "collection-item"> <ul class="collapsible" data-collapsible="accordion"> <li> <div class="collapsible-header">{{author.name}}</div> <div class="collapsible-body"> {% for item in category.item_set.all %} <p>{{item.url}}</p> {% endfor %} </div> </li> </ul> </li> {% endfor %} what I am trying to do is loop through the authors and at the same time under each author loop through the urls that are associated with each author. -
Django Form not showing, only the button (NEW)
only my Submit button is popping up when i am trying to pass a form. I even tried just copying the code from the Django website... Still does not work for me. This is my forms.py from django import forms class contactForm(forms.Form): name = forms.CharField(required=False, max_length=100, help_text='100 max.') email = forms.EmailField(required=True) comment = forms.CharField(required=True, widget=forms.Textarea) This is my views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .forms import contactForm def contact(request): form = contactForm(request.POST or None) if form.is_valid(): print(request.POST) context = locals() return render(request, 'contact/contact.html', context) def index(request): return render(request, 'contact/contact.html') This is my contact.html {% extends "contact/base.html" %} {% block content %} <h1>Contact</h1> <form method='POST' acion=''> {% csrf_token %} {{ form.as_p }} <input type='submit' value='submit form'/> </form> {% endblock %} I really do not know what is wrong with this code...please help! Thanks ps: I am new to python, maybe i need another version? -
Django model design to analyse user activities on external websites
I am working on an app that analyses the activities of users on some external sites. The contents of the target sites fall into three types: Forum post: A user can either start a thread or reply to an existing one, the reply will get an unique url; Blog entry: Any user can post. The blog entry gets an unique url, comments do not. News article: Not user posted, from a number of news sources. Comments do not have an unique url. The focus of my app is on user activities, below are some possible questions: How often does user A post (with respect to types, daily, weekly, etc.)? What topics are the user mostly interested in? (for this, all threads will be taged based on their original category and scanned keyword from title/content). Is user A tend to reply user B's posts then user C's? (obviously this particular question suits more on forum posts and blog entries). I plan to consolidate a Thread model to hold all three types of contents, do not address the diffrences in them, for example, theat the news source just as a regular user. The Thread model will have roughly 10 millions of records. β¦ -
Django template two select area and one url address
I have app in django 1.8 with template, where I have two things to select - month and year. I want to be able select month, then year and after select year redirect to view with events which I choose. Or recived events first for selected month then for year, but I have no idea how to do this. My view after choose month and year: class ArticleMonthArchiveView(ListView, MonthArchiveView): queryset = models.Booking.objects.order_by('-date_start') template_name = 'events/archive_list_2.html' date_field = "date_start" make_object_list = True allow_future = True def get_context_data(self, *args, **kwargs): min_year = self.queryset.aggregate(Min('date_start')) max_year = self.queryset.aggregate(Max('date_start')) context = super(ArticleMonthArchiveView, self).get_context_data(*args, **kwargs) context['mode'] = 'archive' context['object_list'] = models.Booking.objects.filter(date_start__year=self.get_year(), date_start__month=self.get_month()) context['year'] = range(min_year['date_start__min'].year, max_year['date_start__max'].year + 1) context['months'] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', ] return context Url to this view: url(r'^/(?P<year>[0-9]{4})/(?P<month>[0-9]+)$', views.ArticleMonthArchiveView.as_view(), name="archive_month_numeric"), Templete where I can select - with hardcoded data, I know this is wrong, but here is bottelneck for me: <div class="content-row row-big"> <div class="right pr-0 pr-md-3 mr-0"> <div class="filter-element location-filter"> <input id="location-opener" type="checkbox" class="hidden-input"/> <label for="location-opener" class="filter-label">Month</label> <div class="filter-overlay checkboxes-overlay"> <ul> {% for i in months %} <li> <a href="">{{ i }}</a> </li> {% endfor %} </ul> </div> </div> <div class="filter-element opener-filter"> <input β¦ -
NameError: global name 'logger' is not defined
I wrote a logging.json file from where the logging configuration is setup after which i created a class in which all my methods will be there but for logging when i use logger inside the class it is throwing error NameError: global name 'logger' is not defined app.py #/usr/bin/python import sys import logging import time import json import os import logging.config def setup_logging(default_path='logging.json',default_level=logging.INFO,env_key='LOG_CFG'): """Setup logging configuration""" path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level) class Generic: def __init__(self , file_path): self.file_path = file_path def check_mime(self): logger.info('Generic on file {} starts at {}'.format(file_path , time.time())) print 'File path is {}'.format(sys.argv[1]) file_path = sys.argv[1] def parser(): parser = Generic(file_path) parser.check_mime() def main(): print 'This is intended for module purpose only' setup_logging() parser() if __name__ == '__main__': main() logging.json { "version": 1, "disable_existing_loggers": false, "formatters": { "simple": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "simple", "stream": "ext://sys.stdout" }, "info_file_handler": { "class": "logging.handlers.RotatingFileHandler", "level": "INFO", "formatter": "simple", "filename": "logs/gp.log", "maxBytes": 10485760, "backupCount": 20, "encoding": "utf8" }, "error_file_handler": { "class": "logging.handlers.RotatingFileHandler", "level": "ERROR", "formatter": "simple", β¦ -
Why I can still access static assets when using gunicorn?
I just deployed my django app to AWS EC2 instance and change the WSGI server to gunicorn, but I still able to access static assets from browser (e.g. http://xxx.compute.amazonaws.com:8000/media/aaa/test.jpg) From my understanding, gunicorn does not serving static files, can somebody explain why? Here's the server initialization screenshot: gunicorn -
Path to static files in Django CMS admin
I'm having an issue with some administrative icons being used in a Django CMS I have deployed for one of my clients. As you can see from the attached image, the path to the static folder where the images are stored is wrong and therefore doesn't render the icons. It's missing the static part of the URL. Can anyone provide any pointers on this? Many thanks in advance for any assistance people may be able to provide on this -
Sending HTML emails Django 1.9
Im trying to create a contact form that sends a HTML email responses using send_mass_email, but I keep getting a syntax error. I have the following code in my views.py def email(request, template='marketing/email.html'): form = ContactForm(request.POST or None) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] html_content = render_to_string( 'marketing/welcome.html', { 'message': message, 'subject': subject, } ) try: message1 = (subject, message, from_email, ['test@test.com'], html_message=html_content) message2 = (subject, message, from_email, ['test@test.com'], html_message=html_content) send_mass_mail((message1, message2), fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') context = { "form": form, } return render(request, template, context) def thanks(request): return HttpResponse('Thank you for your message.') I keep getting the following error. message1 = (subject, message, from_email, ['test@test.com'], html_message=html_content) SyntaxError: invalid syntax -
attribute error method object has no attribute
Im new to Django Framework and i'm taking an online course on LinkedIn Learning. I am using a newer version of python/django so I run into some syntax problems. my python version is 3.5.4rc1. my django version is 1.11.4 I created a model in models.py for an inventory: class Item(models.Model): titel = models.CharField(max_length=200) omschrijving = models.TextField() aantal = models.IntegerField() This is the code in my views.py file: from django.shortcuts import render from django.http import Http404 from inventory.models import Item def index(request): items = Item.objects.exclude(aantal=0) return render (request, 'inventory/index.html', { 'items': items, }) return HttpResponse('<p>In index view</p>') def item_detail(request, id): try: item = Item.objects.get.id=(id) #THIS ONE CAUSES PROBLEM??? except Item.DoesNotExist: raise Http404('Dit item bestaat niet') return render(request, 'inventory/item_detail.html', { 'item': item, }) In the browser the localhost:8000 shows homepage as expected. localhost:8000/item/1/ gives error: AttributeError at /item/1/ 'method' object has no attribute 'id' Request Method: GET Request URL: http://localhost:8000/item/1/ Django Version: 1.11.4 Exception Type: AttributeError Exception Value: 'method' object has no attribute 'id' Exception Location: C:\Users\info_000\Desktop\django\mysite\inventory\views.py in item_detail, line 15 Please Help! -
Form validation for Twilio in Django to send a SMS message
I'm trying to set up Twilio integration inside a DetailView Django page. They look at the detailed view page and can request a booking via from POST method. Upon booking, I would like to send SMS to the owner of the booking, in my case the teacher. forms.py from django.core.validators import RegexValidator class BookingForm(forms.Form): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") Phone = forms.CharField(max_length=15,validators=[phone_regex],label='Phone') views.py def post(self,request,**kwargs): form = BookingForm(self.request.POST) account_sid = "xxx" auth_token = "xxx" teacher = Teacher.objects.get(id=self.kwargs['pk']) client = Client(account_sid, auth_token) user_phone = form['Phone'].value #user_phone = self.request.POST['Phone'] client.messages.create( to=teacher.phone_number, from_="+442033225719", body="You have a new student" + " Student phone number:{}".format(user_phone)) And I have a template form, which has 1 input - phone number. However, when I submit the form, I get the following text message: Student Phone number: <bound method BoundField.value of <django.forms.boundfield.Boundfield object at 0x104e5f0b8>> Note that if I don't use forms, but instead have a simple user_phone = self.request.POST['Phone'] instead of validating the form using if form.is_valid(), everything works correctly. -
Django Rest Framework returning "detail": "Not found."
I have an API endpoint which i am able to POST and GET with (Tested with Postman). But the problem arises when i try to do a partial update. I am not sure what I am missing, I have included the code with the attempt and the error it gives. The error: "detail": "Not found." As far as i understand the url should include the ID of the instance i would like to partially update, so the url to perform the PATCH on is: http://localhost:8000/manuscripts-api/manuscriptlibrary/9/ My view: class ManuscriptLibraryViewSet(viewsets.ModelViewSet): """Handles creating, reading and updating manuscript library.""" authentication_classes = (TokenAuthentication,) serializer_class = serializers.ManuscriptLibrarySerializer queryset = models.ManuscriptLibrary.objects.all() permission_classes = (permissions.PostOwnManuscriptLibrary,) def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) My model: class ManuscriptLibrary(models.Model): """Represents a single manuscript's library""" manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE) bookmarks = models.CharField(max_length=99999999) history = models.CharField(max_length=99999999) def __str__(self): """Django uses when it needs to convert the object to a string""" return str(self.manuscript) My serializer: class ManuscriptLibrarySerializer(serializers.ModelSerializer): """A serializer for a manuscript's library.""" class Meta: model = models.ManuscriptLibrary fields = ('id', 'manuscript', 'bookmarks', 'history') My urls: router = DefaultRouter() router.register('manuscripts', views.ManuscriptViewSet, base_name="manuscripts") # auto basename for models router.register('manuscriptlibrary', views.ManuscriptLibraryViewSet, base_name="manuscript_library") router.register('manuscriptsettings', views.ManuscriptSettingsViewSet) urlpatterns = [ url(r'', include(router.urls)) ] My permission: class β¦ -
Autopopulate Foreign Key Field Based on User Choice Selection
I have two models: class Entity(models.Model): entity = models.CharField(primary_key=True, max_length=12) entityDescription = models.CharField(max_length=200) def __str__(self): return self.entityDescription class Action(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, db_column='entity') entityDescription = models.CharField(max_length=200) action = models.CharField(max_length=50) def __str__(self): return '%s' % self.entity I have a model form and model formset, along with a form helper for crispy-forms: class ActionForm(ModelForm): class Meta: model = Action fields = '__all__' def __init__(self, *args, **kwargs): super(AlertForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: disabledFields = ['entity', 'entityDescription'] for field in disabledFields: self.fields[field].disabled=True else: self.fields['entity'].blank=True self.fields['entityDescription'] = ModelChoiceField(queryset=Entity.objects.all()) ActionFormSet = modelformset_factory(Action, extra=1, exclude=(), form=ActionForm) class ActionFormsetHelper(FormHelper): def __init__(self, *args, **kwargs): super(ActionFormsetHelper, self).__init__(*args, **kwargs) self.form_method = 'post' self.template = 'bootstrap/table_inline_formset.html' self.add_input(Submit("submit", "Submit")) self.layout = Layout( Field('entity', css_class="input", type="hidden"), Field('entityDescription', css_class="input"), Field('action', css_class="input") ) I have a view: def actions(request): newActions = Action.objects.filter(action='') formset = ActionFormSet(request.POST or None, queryset=newActions) helper = ActionFormsetHelper() context = {'formset':formset, 'helper':helper} if request.method == 'POST': for form in formset: if form.is_valid(): if form.has_changed(): obj = form.save(commit=False) obj.entity = form.cleaned_data['entityDescription'] obj.save() return HttpResponseRedirect('/actions') return render(request, 'actions/actions.html', context) So my rendered page looks something like this: entityDescription action Jim Halpert [Blank Cell] Michael Scott [Blank Cell] [Blank Cell] [Blank Cell] entity is hidden, and entityDescription is β¦ -
Converting static CASE WHEN statements to dynamic to supply to .annotate()
I have this ORM query that is working well. I tested the following out to see the ouptut and it is as expected actually: members=Members.objects.all().annotate(age_groups=Case( When(birthdate__year__range=(2007,2017), then=Value('0-10')), When(birthdate__year__range=(1997,2006), then=Value('11-20')), When(birthdate__year__range=(1987,1996), then=Value('21-30')), When(birthdate__year__range=(1977,1986), then=Value('31-40')), When(birthdate__year__range=(1967,1976), then=Value('41-50')), When(birthdate__year__range=(1957,1966), then=Value('51-60')), When(birthdate__year__range=(1947,1956), then=Value('61-70')), When(birthdate__year__range=(1937,1946), then=Value('71-80')), When(birthdate__year__range=(1927,1936), then=Value('81-90')), When(birthdate__year__range=(1917,1926), then=Value('91-100')), default=Value('100+'), output_field=CharField()) ).values('age_groups',).annotate(total=Count('age_groups')) But I want to move it to a function so users can specify the date field they want o work wit and the step grouping they prefer(e.g 0-20, 21-40 etc). For tat, I did the following function which simply outputs the CASE WHEN statements as a string when called. The problem is when I pass it to annotate() I get the 'str' has no 'resolve' error. Hope you get what I want to do. I need to pass the output of the following function to annoate(): from datetime import date def AgeGrouping(field_name,required_min_age=0,required_max_age=100,jump_by=10): now_year=date.today().year reply='Case(' just_started=True for i in range(now_year-required_min_age,now_year-required_max_age,-jump_by): if just_started==False: min_age=max_age + 1 max_age=min_age + 9 else: min_age= now_year - i max_age= min_age + 10 min_year=now_year- min_age max_year= now_year - max_age reply="\n".join([reply,"When(" + field_name + "__year__range=(" + str(max_year) + "," + str(min_year) + "), then=Value('" + str(min_age) + "-" + str(max_age) + "')),"]) just_started=False reply="\n".join([reply, "default=Value('100+'), output_field=models.CharField())"]) return reply Then call β¦ -
Handling categories and sub categories in Django
I am working on a django project where "venues" can have a menu of food and drink items. Within this, there can be a varying number of sub menus, "Breakfast", "Lunch", "Dinner", "Drinks" etc etc. I am struggling to work out how while using django generic views to simply use a {% foreach %} to achieve this result. I do not know how many sub menus there will be in each instance or the names of them. Can anyone point me in the right direction for where to look? Or should I try to solve in python in a custom template tag? -
How to enable compression on Django project and still be safe?
We're using Python Django for our project. When I tested the website on google page speed, I saw a warning of Enable compression, Leverage browser caching, and Reduce server response time. For this post I'd like to ask regarding the Enable compression problem. I myself has no experience with GZIP compression and my backender has no experience with this as well. One thing is, he suggested not to do it due to a warning on Django site: Warning Security researchers recently revealed that when compression techniques (including GZipMiddleware) are used on a website, the site becomes exposed to a number of possible attacks. These approaches can be used to compromise, among other things, Djangoβs CSRF protection. Before using GZipMiddleware on your site, you should consider very carefully whether you are subject to these attacks. If youβre in any doubt about whether youβre affected, you should avoid using GZipMiddleware. For more details, see the the BREACH paper (PDF) and breachattack.com. How do I enable compression and still be safe? What do I need to do? -
Django Questionnaire app
I guys I am very new to Django and app dev and I am having trouble to structure my app. I am creating an app to send team questionaire.So wokflow is the following: 1) I create a team_project (Team_name) 2) Send Invitations to team members using Emails 3) Based on that invitation Team_member signIn (creating a new user) and are directly assigned to that team created. I have no idea how to handle that and especially part 3 If you could give me a direction how to do it I will really appreciate Thx you very much