Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django translations not working without language tag and execute on button clcik
I have a block of text that I want translated when the user click a button. I've run the following code: mkdir project/locale django-admin makemessages -l fr django-admin compilemessages In my html I have the following: <h5 class="slim">{% trans "This is an example" %}</h5> My translation only works if I do this in my html: {% language 'fr' %} <h5 class="slim">{% trans "This is an example" %}</h5> {% endlanguage %} I've tried changing the language in settings.py to 'fr' from 'en' and getting rid of {% language 'fr' %} and {% endlanguage %} but the translation did not work when I did that. Here is whats in my settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', # ADDED TO FILE FOR TRANSLATION 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ('de', _('German')), ) And here is what's in my .po file: msgid "This is an example" msgstr "Ceci est une example" -
Django 1.10 inheritance issue overriding properties
I'm trying to override a Parent class model on the Child class but nothing happens: class Parent(models.Model): title = models.CharField(max_length=255) @property def model_type(self): return 'parent' class Child(Parent): @property def model_type(self): return 'child' print(Child.objects.get(id=32).model_type) >>> "parent" Any quickfix around this ? I'm just trying to override the parent class properties but I couldn't find anything about this. Any help would be appreciated -
jquery/javascript: Edit the content after button click?
could someone explain me how I can write a function in Javascript for a button that lets me edit the content of an element? I searched the web, but all if found so far were only guides on how to change one premade text to another premade text, but I'd like to have something where I type in my own text and not replace the old one with one that is premade. I know that I could do it with forms, but I'd really like not to use them. My problem is that I have a table with items, that is build with django and rendered to a html file. The thing here is that the table is never going to have a specific amount of items. It'll have a variable amount, like this month I've got 20 items in there and next month I'll add another 40-50 and I don't want to give every item an extra id by hand, thats why I created a loop that gives them an individual id. So my Javascript or jQuery would have to always (somehow) trigger the exact text for the exact item. So what I want is something like this: <tr> … -
Django - Models - Recursively retrieve parents of a leaf node
I have a User model class defined as follows: class CustomUser(models.Model): user = models.OneToOneField(User) slug = models.SlugField(max_length=35, unique=True,help_text="URI dell'utente che appare sul browser") team = models.CharField(max_length=100, null=False, verbose_name="Team") area = models.CharField(max_length=100, null=False, verbose_name="Area") line_manager = models.ForeignKey('self', null=True, blank=True,related_name='parent') I would like to retrieve all the line_managers of a CustomUser. Let's suppose I have: A -B -C where C is the leaf and B and A are the values I would like to retrieve. How can I do in django? -
Postgres: values query on json key with django
I need to do a values/values_list query on nested key on a postgres backed jsonfield in django 1.10 eg. class AbcModel(models.model): context = fields.JSONField() If it has values like: { 'lev1': { 'lev': 2 } } I want to run a queries like AbcModel.objects.values('context__lev1__lev2').distinct() AbcModel.objects.values_list('context__lev1__lev2', flat=True).distinct() -
Django date-based ArchiveView with ForeignKey date_field
I have Django models describing Places and Visits to those Places on a particular day: from django.db import models class Place(models.Model): # ... name = models.CharField(max_length=255) class Visit(models.Model): # ... place = models.ForeignKey('Place', blank=False) visit_date = models.DateField(blank=False) I want to display all the Places visited in a year, so I've tried using YearArchiveView with a date_field spanning the relationship with Visits: from django.views.generic import YearArchiveView from myapp.models import Place class PlaceYearArchiveView(YearArchiveView): date_field = 'visit__visit_date' model = Place However, this gets me "Place has no field named 'visit__visit_date'". What's the simplest way to have this view use a queryset that's like this (assuming d1 and d2 are the first and last days of the year in question): Place.objects.filter(visit__visit_date__gte=d1, visit__visit_date__lte=d2).distinct() I could use a standard ListView and write my own get_queryset() method but if I can base this on YearArchiveView that seems better. -
To determine the user's role in the project
In my django website I have pages like 'project_list' and 'project_detail'. Every project has members with different roles (developer, manager, e.t.c.). I want to show different buttons depending on the current user's role in the project in template. I need ideas how to realise it. Lets say something like that in template: {% if request.user.role_in_the_current_project = 'manager' %} SOW SOMETHING {% endif %} models.py class Project(models.Model): name = models.CharField(max_length=250,) slug = models.SlugField(max_length=250, unique_for_date='publication_date',) *Other fields* def get_absolute_url(self): return reverse('project:project_detail', args=[self.slug]) class Membership (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) ROLE_CHOICES = ( ('manager', 'Manager'), ('developer', 'Developer'), ('business_analyst', 'Business analyst'), ('system_analysts', 'System analysts'), ) role = models.CharField(max_length=20, choices=ROLE_CHOICES,) view.py def project_detail(request, slug): project = get_object_or_404(Project, slug=slug, status='public') return render(request, 'project/project_detail.html', {'project': project,}) project_detail.html {% block content %} <h1>{{ project.name }}</h1> <p>{{ project.description|linebreaks }}</p> {%endblock %} urls.py urlpatterns = [ url(r'^project/(?P<slug>[-\w]+)/$', project_detail, name='project_detail'), ] -
django-The page isn’t redirecting properly
I have a middleware that check user profile. if auth user haven't profile, redirect to user profile. but my browser return me The page isn’t redirecting properly error. class Check(MiddlewareMixin): def process_request(self, request): if request.user.is_authenticated(): user = request.user try: profile = Profile.objects.get(user_id = user) if profile: pass except ObjectDoesNotExist: return HttpResponseRedirect('/accounts/profile/') i'm use django-allauth too -
User only sees certain data from database on django site
On my site I only want certain user to see what they "own" from my database. For example, if Bob owns houses 1, 2 and 3, he should only be able to see stuff related to those houses. Lets say my models looks something like this: class Houses(models.Model): houseid = models.models.AutoField(db_column='houseID', primary_key=True). owner = models.CharField(db_column='owner', max_length=50) size = models.FloatField(db_column='size') rooms = models.FloatField(db_column='rooms) floors = models.FloatField(db_column='floors') notes = models.CharField(db_column='notes', max_length=255, blank=True, null=True) class HouseData(models.Model): houseid = models.ForeignKey(Houses, models.DO_NOTHING, db_column='houseID') date = models.DateField() electricity = models.FloatField(db_column='electricity') water = models.FloatField(db_column='water') How would I restrict what the user sees on the site? -
the proper way to go from staging to production?
I am working on an Angular2/django(DRF) SPA application. to pass from staging to production deployement I have copied all files of staging folder to a new folder called production with editing env variables ? is it a good practice to have similar staging and production environment so that I can safely pass to prod after testing staging ? -
get active tab by click in django form template
I am developing my first Django app and want to optimize it. How can I get the last active tab in my form template? I want to be redirected from the create or update form to the last active tab on the page. I haven't any knowledge in JavaScript, so I am hoping for some help. -
How to parse a json dumped python dict as javascript object in django template
I have a python code which converts the normal dict into JSON as follows groups = { 'g_1': [ {'name': 'something', 'id': '1'}, {'name': 'something', 'id': '1'} ], 'g_2': [ {'name': 'something', 'id': '1'}, {'name': 'something', 'id': '1'} ] } I have used json.dumps to convert that to a json as follows import json groups = json.dumps(groups) I want to read the data in javascript as an object. How to I access it? I tried var groups=JSON.parse({{ groups }}) it didn't work out. Help me in parsing the data as javascript object. -
Template construct... it works, but feels ugly
In a template I am showing the first 5 translations of an item (i). The following logic is handled in the template: If there are more than 5 translations: I trim the list and show a link more.... If there are 1 to 5 translations: I simply show them. If there is no translation: I show a link to add a translation. Here is the (functional) template code I came up with: {% if i.translation_set.all %} <ul> {% for t in i.translation_set.all|slice:"6" %} {% if forloop.counter < 6 %} <li> <a href="#"> <i class="fa fa-play mr-2"></i> {{ t.language }} <i class="fa fa-commenting-o ml-1"></i> </a> </li> {% else %} <li>more...</li> {% endif %} {% endfor %} </ul> {% else %} <a href="{% url 'view-item' i_id=i.id slug=i.slug %}">Add translation</a> {% endif %} Here are my concerns regarding this code: What sort of query is executed for if i.translation_set.all? Does it query all translations or does it stop at 1? Is it maybe better to use the same slice query, since that gets used later and could be (automatically?) cached? It feels ugly to query 6 items, while only needing to display max 5. Is there another way to tell there are more … -
Wagtail - extending PageChooserBlock to support external URLs
I'm building a site with Wagtail and using StreamField to build up content on a homepage. I've built a block that allows users to add featured links, which could be internal or external links. Currently the featured links have both a PageChooserBlock and a URLBlock, but I'd like to add a new custom block type that allows a user to specify either an internal page or a URL. I can't see anything in the docs that would help me. Any ideas where to start? -
Sending form data within an email Django
Hey i have a form on django and need to send the results out in an email. now the email works and the form works. The only thing i do not like is the way the data is displayed i have tried using tuples and lists to send the data. if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] standard = form.cleaned_data['standard'] atex = form.cleaned_data['ATEX'] supply_type = form.cleaned_data['supply_type'] line_frequency = form.cleaned_data['line_frequency'] supply_voltage = form.cleaned_data['supply_voltage'] power = form.cleaned_data['power'] poles = form.cleaned_data['poles'] mounting = form.cleaned_data['mounting'] efficiency = form.cleaned_data['efficiency'] protection = form.cleaned_data['protection'] frame = form.cleaned_data['frame'] brake = form.cleaned_data['brake'] force_cooling = form.cleaned_data['force_cooling'] encoder = form.cleaned_data['encoder'] form = [str(message), ('Standard',str(standard))] if subject and message and from_email: try: send_mail(subject, str(form), from_email, ['jordanfeatherstone@gmail.com'], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') messages.success(request, 'Enquiry email successfully sent') return render(request, 'motors.html', {'motors': motors, 'form': form}) What would be the best way to manipulate the results in a human readable way? -
How can I add a form made by formbuilder to every page in Wagtail?
Is there any way to add form (for example feedback form) to every page in CMS? I really like to use Wagtail FormBuilder so Editor guy can change fields. My first idea is to create custom form page (inherited from AbstractEmailForm) as site root child and load it to base.html trough template tag. I can access page properties this way but I cant render the form. Here is my template tag: @register.assignment_tag(takes_context=True) def get_feedback_form(context): return context['request'].site.root_page.get_children().type(FeedbackFormPage).first() And this is how I use it from base.html: {% get_feedback_form as feedback_form %} ... {{ feedback_form.specific.title }} <-- this works {{ feedback_form.specific.form.as_p }} <-- this doesnt work It would be nice somehow to create a form as snippet or add it to Site Settings, but I didnt find how to do that. -
Installation of GeoDjango on Windows generates error
I am following this paper https://docs.djangoproject.com/en/1.10/ref/contrib/gis/install/ but it prints an error message: raise improperlyconfigured(error_msg) django.core.exceptions.improperlyconfigured:'django.contrib.gis.db.backends.postgis' isn't an available database backend. try using 'django.db.backends.XXX',where XXX is one of: 'mysql','oracle','postgresql','sqlite3' error was:cannot import name 'GDALRaster' my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'world', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'testdb', 'USER': 'postgres', }, } python version 3.5 django 1.10.6 psycopg2 2.7 Order of install 1.python 2.postgreSQL 3.postGIS 4.psycopg2 5.OSGeo4W 6.Modify Windows environment 7.django Please help me and thanx. -
Django mqtt subscriber work in development not in production
Just experimenting mqtt and django: How to use paho mqtt client in django? this work fine with ./manage.py runserver but not with: /usr/local/bin/uwsgi --socket :7011 --module myproject.wsgi tried with single process and multiple processes, result still the same: calling a web page result in a wait forever reply. Why? -
Is it a good idea to add time-consuming method or property to django model?
This is the model: class Sensor(models.Model): sensor_id = models.CharField(...) ... @property def get_data(self, self_id): #get data using paho-mqtt package Is it a good idea to add time-consuming method or property to django model or should I separate the time-consuming action outside the model? -
Full domain url subfolder redirected my django application with apache with mod_wsgi
i've been facing the following problem. I got django 1.9 integrated with apache 2.4+ via mod_wsgi application. i run manage.py collect and everythiong is fine when i use the root url. http//10.184.2.231 it is ok and static files are served properly. Actually i will be redirected to my django app from the link www.mydomain.com/nuovopatetdb This is my configuration from urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.search_ES,name='search_ES'), url(r'^nuovopatentdb$', views.search_ES,name='search_ES'), url(r'^download/(?P<id_src>.*)$', views.send_file, name="download"), url(r"^documents$", views.documents,name="documents"), ] from settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') WSGI_APPLICATION = 'ES_Brevetti.wsgi.application' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'patentdb.apps.patentdbConfig', 'mod_wsgi.server', 'el_pagination', ] and from httpconf.d Alias '/static' '/home/elastic/workspace/ES_Brevetti/static' <Directory '/home/elastic/workspace/ES_Brevetti/static'> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Require all granted </IfVersion> </Directory> This is an example of my template: <div id="waitLoading" > <img src="{%static "images/giphy.gif"%}"> </div> The image giphy.gif cannot be served and i get the3 follwoing error: GET http://www.mydomain/static/images/giphy.gif 404 (Not Found) How can i work this around? Many many thanx for ur help -
Django: Select a valid choice. That choice is not one of the available choices
I have two forms and get the error message Select a valid choice. That choice is not one of the available choices.. forms.py: class Forms1(forms.ModelForm): groups = ojrms.ModelChoiceField(queryset=None, widget=forms.Select(attrs={ 'onchange': 'this.form.submit();', }), empty_label='choice group') def __init__(self, *args, **kwargs): super(Form2, self).__init__(*args, **kwargs) class Form2(forms.ModelForm): self.fields['groups'].queryset = LDAPTenant.objects.filter(status=1) class Meta: model = User def __init__(self, group, *args, **kwargs): super(Form2, self).__init__(*args, **kwargs) self.fields['member'] = forms.ModelChoiceField(widget=forms.Select(attrs={}), empty_label='choice user', queryset=User.objects.filter(group=group)) But it doesn't work with the query queryset=User.objects.filter(group=group)), however it works queryset=User.objects.all()). What are the reasons for this or what did I wrong? -
Celery not all crontab values executed
I am pretty new in Celery and I have a problem with executing my periodic tasks. (Celery 4, Django 10.3, Python 3.4.3) I have example of code from Celery doc: from autoparts_project.celeryapp import app from celery.schedules import crontab @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) # Executes every Monday morning at 7:30 a.m. sender.add_periodic_task( crontab(minute=5, hour=15), test.s('Happy Mondays!'), ) @app.task def test(arg): print(arg) When I run command celery -A app.tasks beat -l info -S django The first two task it work correctly but the last one not executed But when I changed the the crontab parameters on crontab(minute=50, hour='*/2,*/3') it works correctly. As I understand the Cellery works well, but crontabs statement behaves differently. What can be the problem or what am I missing? -
Django multistep form with paypal button
I am building simple application using django. My application have following use case as shown in the figure below Step 1: Fill the form (after submission generate unique pdf file with form content) Step 2: Pay with payal (pay button generated from paypal) Step 3: Download pdf file At paypal I have set success url (localhost:8000/thankyou) for local testing Everything is working as expected! But I have problem in tracking unique generated pdf file after payment as it's redirected to thankyou view. As a hacky solution i am using session to track filename. I am not sure if it's a good approach. Can anyone provide me better solutions or pointer for my usecase? What i have done so far def form(request): return render(request, 'form.html') def payment(request): if request.method=='GET': customername = request.GET['customername'] other = request.GET['other'] dob = request.GET['dob'] unique_filename = str(uuid.uuid4())+".pdf" request.session['pdffile'] = unique_filename doc = SimpleDocTemplate(unique_filename,pagesize=A4, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) ................... doc.build(Story) return render(request, 'payment.html', {'filename':unique_filename}) else: return redirect(form) def thankyou(request): currentpdf = request.session['pdffile'] return render(request, 'thank-you.html') def download(request): currentpdf = request.session['pdfile'] response = HttpResponse(my_data, content_type='text/x-python') response['Content-Disposition'] = 'attachment; filename=currentpdf' del request.session['pdffile'] # redirect(home) -
Django: how to bind/save value from inline tinymce element to form field?
I have a crispy form with two fields: name and value. I have to have inline tinymce editor on the value field. So I did this to the form class: class MyForm(ModelForm): class Meta: model = SomeModel fields = ('name', 'value') def __init__(self, *args, **kwargs): super(MyForm,, self).__init__(*args, **kwargs) self.helper.layout = Layout( 'name', Field('value', type='hidden'), HTML('<div class="wrapper"><span class="editable"></span></div>'), FormAction(Submit('submit', 'Submit') ) in template: {% crispy form %} <script> tinymce.init({ selector: 'span.editable', toolbar: "superscript subscript", menubar:false, inline:true }); $('span.editable').html($('#id_value').val()); What I can't figure out is how to save on form submit the edited span element text to the 'value' field. -
Download file from Django Project root using a button
So, this is the webpage I'm creating atm with Django 1.8: Want the user to be able to export the data as .csv. When the user: writes a subreddit name in the box presses the button 'Get Data' What happens: it's created a test.csv (saved in the root of the project) data is retrieved using Praw data is inserted into the .csv data is rendered for the users to see The problem now is: I want the button with 'Export to Excel', to download the generated file from the root of the Django project. This is for the button: <form class="export_excel" id="login_form" action="/app/export"> {% csrf_token %} <button class="btn btn-lg btn-primary btn-block" value="Export to Excel" type="submit">Export To Excel</button> </form> This is in app/views.py: def export(request): filename = "test.csv" # this is the file people must download response['Content-Disposition'] = 'attachment; filename=' + filename response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16' return response This is in app/urls.py: # app/urls.py from django.conf.urls import url from . import views # Create your urls here. urlpatterns = [ (...) url(r'^export/$', views.export, name='export') ] This is the error I'm getting when clicking the button: Question is: How can I make the user export the file using the button? What am …