Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to deal with multitenancy in django application
This is probably a stupid question, but I'm having trouble visualizing the best way to do this. I'm building a really simple app in Django for two different groups, and I was wondering what the best way to deal with multi-tenancy issue would be. Here is my current requirements: Each group has a group account number. Each group has multiple members that need to login under their specific group and have their own member ID. I don't really want each member in the group to have to put in their group account number on the login screen, and I don't really want to have a drop down with each group name and/or account numbers, since this app can be used for multiple groups and not just the two I'm currently working with. When the member logins, I kind of want the system to know which group each member is part of already. Each group admin needs to be able to add additional members through a self-provisioning portal. App is being hosted in a cloud environment. Here is my current thought process on how to develop this functionality: Create a lookup table that contains two columns. 1 column for group account … -
Send response in html templates without reload page
In my Django project i have a listing page for all customers. On that page all customers list shows, i have a filed is_active there. I if i click on change status button ( every row of customer listing page have a change status button) is_active field become false without reloading my listing page.and when i again clcik on change status button it turn True.Please help me by giving a sample code for it. MY listing page is as follows- <!DOCTYPE html> <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> </head> <body> <form id="myform" method = "POST" action="#"> <table> <tr> <th>Name</th> <th>Location</th> <th>quantity</th> <th>time</th> <th>fb_id</th> <th>contact_number</th> <th>is_active</th> <th>Action</th> </tr> {% for lead in leads %} <tr> <td>{{lead.customer_name}}</td> <td>{{lead.location}}</td> <td>{{lead.quantity}}</td> <td>{{lead.time_requirement}}</td> <td>{{lead.fb_id}}</td> <td>{{lead.contact_number}}</td> <td> {% if lead.is_active %} <input type="radio" value="" checked> {% else %} <input type="radio" value="" > {% endif %} <button name="button" value="OK" type="button" >change status</button> </td> <td><button name="button" value="OK" type="button" align="middle"><a href="/customapi/vendor/detail-customer-leads/?lead_id={{lead.id}}">Edit</a></button> </td> </tr> {% endfor %} </table> </form> </body> </html> -
Why are my Django form fields not rendering in the template?
I'm receiving no errors and everything seems fine but the fields to my form will not show up, although the submit button does show. My form: from django import forms class ContactForm(forms.Form): name = forms.CharField(required=False, max_length=100, help_text='100 characters max') email = forms.EmailField(required=True) comment = forms.CharField(required=True, widget=forms.Textarea) My view: from .forms import ContactForm def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): print(request.POST) context = {'form': form} return render(request, 'contact.html', context) contact.html template: <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" class="btn btn-default" /> </form> base.html template: {% block content %} {% endblock content %} {% include "contact.html" %} </div> What am I missing? The template housing the form is not surrounded by any block tags because the template is being {% include[d] %} into my base.html. Additional details: The form and view are in their own separate 'contact' app, and I haven't configured any urls for the contact app as I planned on simply including the template into base.html -
Defining models when using multiple databases
I want to read data from an external database and generate reports in Django. I am trying to create the required models for the data that I will be fetching. Is it possible to define relationships when doing this? For example: I have 2 tables, ITEMS and STAKEHOLDERS, each ITEM has many STAKEHOLDERS. Is it possible to define the models such that, when I do, ITEM.objects.get(pk = 1).STAKEHOLDERS, I get all the stakeholders for that specific item? -
Django - Form update, how to update the foreginkeys?
I created a page where the user can edit/update his Post. I am using a populate form and passing it trough the view. All the Post fields like title, description, main_image and others are rendering and updating fine. The problem is that the Post images are foreginkeys (Imagens) which I catche using a formset, but I don't know how to let the user edit them. I mean, should I populate a formset and pass trough the view? For the post main_image (which is in the populated form), I don't know how it happens, but it automactly creates a label with the actual image name and a change input button for the a new image. models.py class Post(models.Model): # Detalhes do usuario nome_contato = models.CharField(max_length=50) telefone_contato = models.CharField(max_length=50) ... imagem_principal = models.ImageField(upload_to='anuncios/%Y/%m/%d') class ImagensAnuncio(models.Model): anuncio = models.ForeignKey(Post, related_name='imagens') imagem = models.ImageField(upload_to='anuncios/%Y/%m/%d') views.py def dashboard_editar_anuncio(request, id=None): obj = get_object_or_404(Post, id=id) form = AnuncioForm(request.POST or None, request.FILES or None, instance=obj) if request.method == 'POST': if form.is_valid(): form.save() return redirect('/dashboard/home') return render(request, 'dashboard/dashboard_editar_anuncio.html', {'form': form, 'obj':obj}) -
How to access form date fields in template
I want to render a form in Django. In normal case, you access fields like this: {{ form.name }} But I'm using date field with SelectDateWidget widget. This widget has different field for year,month and day. How could I access these fields one by one? {{ form.date.year }} or {{ form.date.0 }} or {{ form.date_year }} etc. doesn't work. -
Django Rest Framework - main url HTTP/1.1" 404 Not Found
I have in my project in the main urls.py file the following: # REST Framework packages from rest_framework import routers router = routers.DefaultRouter() # ... My viewsets serialized router.register(r'users', UserViewSet) # ... Another viewsets urlpatterns = [ url(r'^$', HomeView.as_view(), name='home'), # Home url in my project url(r'^', include('userprofiles.urls')), # Call the userprofiles/urls.py application url(r'^pacientes/', include('userprofiles.urls', namespace='pacientes')), # Patients url url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) # Rest frameworks urls ] Until here, when I type in my browser calling to my local server http://localhost:8000/api/ I get this like response: [08/Dec/2016 16:39:42] "GET /api/ HTTP/1.1" 200 7084 And my REST url's serialized models appear After, I've created one url additional in the userprofiles/urls.py application with some regular expression of this way: from .views import PatientDetail urlpatterns = [ url(r'^(?P<slug>[\w\-]+)/$', PatientDetail.as_view(), name='patient_detail'), ] And, when I go to http://localhost:8000/api/ I get this response: Not Found: /api/ [08/Dec/2016 16:42:26] "GET /api/ HTTP/1.1" 404 1753 My rest frameworks url is not found and in my browser, denote that the url which call to PatientDetailView is the origin of this problem: My PatientDetailView have the following: class PatientDetail(LoginRequiredMixin, DetailView): model = PatientProfile template_name = 'patient_detail.html' context_object_name = 'patientdetail' def get_context_data(self, **kwargs): context=super(PatientDetail, self).get_context_data(**kwargs) # And other … -
Update the django version of my project to django1.10 break django-celery
I am trying to upgrade the django version and the django-celery starts breaking. from celery.utils.timeutils import timedelta_seconds ImportError: No module named timeutils Django - Version 1.10 Celery - 4.0 django-celery 3.1.17 I have tried down grading celery. It gives different errors then. -
How to reference view inside of a function?
I have a function that I need to call inside all of my Views that takes the view as the argument: def view_1(request): def foo(): return Model.objects.create(user = request.user, view = 'view_1') return render(request, myAPP/view_1.html) def view_2(request): def foo(): return Model.objects.create(user = request.user, view = 'view_2') return render(request, myAPP/view_2.html) . . . def view_N(request): def foo(): return Model.objects.create(user = request.user, view = 'view_N') return render(request, myAPP/view_N.html) Is there a way to dynamically generate the view variable so that I can write the function once and call it within each view? def view_1(request) foo() return render(request, myAPP/view_1.html) def view_2(request) foo() return render(request, myAPP/view_2.html) . . . def view_N(request) foo() return render(request, myAPP/view_N.html) -
Accessing QueryDict element from response.POST.get() in Django
Here's my page: <p>Request as string: {{ request.POST }}</p> Which correctly renders: Request as string: <QueryDict: {'csrfmiddlewaretoken': ['HPOQ0pfVf5DU0Lkz05IXqbECipdPUOcTiNGYWd4giZC7LVL5Y6jdT0nb0AcmX9pd'], 'txtNumBins': ['3']}> I'm trying to access the list txtNumBins. But when I try any of the following in my Django template: <p>Total bins: {{ request.POST['txtNumBins'][0] }} </p> <p>Total bins: {{ request.POST.get('txtNumBins')[0] }} </p> <p>Total bins: {{ request.POST['txtNumBins'] }} </p> <p>Total bins: {{ request.POST.get('txtNumBins') }} </p> I keep getting an identical error: TemplateSyntaxError at /analysis/ Could not parse the remainder: '['txtNumBins'][0]' from'request.POST['txtNumBins'][0]' How do I access the dictionary element txtNumBins by name? -
Does visual studio 2017 have support for bash and linux virtualenv for Django
Does visual studio have support for bash on Ubuntu on Windows 10? Is it possible to work inside linux virtualenv(Django) with visual studio? -
microservices and multiple databases
i have written MicroServices like for auth, location, etc. All of microservices have different database, with for eg location is there in all my databases for these services.When in any of my project i need a location of user, it first looks in cache, if not found it hits the database. So far so good.Now when location is changed in any of my different databases, i need to update it in other databases as well as update my cache. currently i made a model (called subscription) with url as its field, whenever a location is changed in any database, a object is created of this subscription. A periodic task is running which checks for subscription model, when it finds such objects it hits api of other services and updates location and updates the cache. I am wondering if there is any better way to do this? -
Django template tag split
I have a url which is generated using {{request.get_ull_path}}. I want to split and get last part of it using django template tag. <a href="{{ request.get_full_path }}"> which gives me abc.me/profile/bio/ How can I get only last part (bio) using django template tag? Or do I have to write custom template tag? -
Any open source Questions & Answer applications in python Django like Stack overflow for commercial use?
How can we use OSQA & Askbot commercially for internal use? Both of them are under GPL licence.So, Is there any way to use GNU software in the commercial project? -
django.db.utils.ProgrammingError: operator does not exist: character varying = integer
Guys i kindly need your help to figure out why am getting this error when i ran my script on a server. the server runs a postgres db i think it is something to do with the object type of the data it's been iterated but not sure how to fix that. Traceback (most recent call last): File "scripts/change_topup.py", line 58, in <module> main() File "scripts/change_topup.py", line 55, in main process_file(path) File "scripts/change_topup.py", line 45, in process_file for enrolment in enrolments: File "/opt/cv_instances/cv1/autodeploy/branches/nboreports/.venv/lib/python2.7/site-packages/django/db/models/query.py", line 258, in __iter__ self._fetch_all() File "/opt/cv_instances/cv1/autodeploy/branches/nboreports/.venv/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/opt/cv_instances/cv1/autodeploy/branches/nboreports/.venv/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__ results = compiler.execute_sql() File "/opt/cv_instances/cv1/autodeploy/branches/nboreports/.venv/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql cursor.execute(sql, params) File "/opt/cv_instances/cv1/autodeploy/branches/nboreports/.venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/opt/cv_instances/cv1/autodeploy/branches/nboreports/.venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/opt/cv_instances/cv1/autodeploy/branches/nboreports/.venv/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/opt/cv_instances/cv1/autodeploy/branches/nboreports/.venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: operator does not exist: character varying = integer LINE 1: ...n"."type" = 1 AND "registration_household"."name" IN (SELECT... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. my script is here # script to update hh top-up locations import … -
django unique constraint failed user_id
django unique constraint failed salebook_saleman.user_id model.py: class Saleman(models.Model): name = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.name class Book(models.Model): owner = models.ForeignKey(Saleman) book_name = models.CharField(max_length=200) book_text = models.TextField(max_length=2000,blank=True) price = models.IntegerField(default=0) telephone = models.CharField(max_length=200) #image = models.ImageField(upload_to='photos') pub_date = models.DateTimeField('date published',default = timezone.now) def __str__(self): return self.book_name view.py: def user_register(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] email = request.POST['email'] new_user = User.objects.create_user(username,email,password) new_saleman = Saleman.objects.create(name=username,password=password) if newsaleman is not None: new_saleman.save() if new_user is not None: new_user.save() context = {'Username':username} return render(request,"salebook/index.html",context) else: context = {'error_message':'Register Fail'} return render(request,"salebook/register.html",context) Not really sure what it means or what's causing it. Let me know if there's an easy fix. Thanks! -
Django : Groups in production
If I create some groups for my users with admin system, when I make my project in production, do I have to recreate all my groups and reassign permissions ? Or I need to dump database ? -
Python/ Django- how to update what information is displayed on a generated PDF
I am working on a project that has been written in Python/ Django, and in particular, want to make a small change to one of its features. On one of the webpages, there is a button, which, when clicked will generate a PDF document with information about a project in the database. I simply want to add a 'date' to the PDF, so that whenever the button is clicked, and a PDF is generated, it will be generated with today's date displayed in the header, to keep track of when which PDF has been created (as they might show different information each time the user generates them). The URL on which page the button is displayed is: www.xyz.com/costing/5915/ The numbers in the URL '/5915/' are the ID of the project that the user is currently working with. In the urls.py file of the costing app, there is the following line: url(r'^(?P<project_id>[0-9]+)/$', views.costing_home, name='home'), and this view is defined in views.py with: def costing_home(request, project_id): """ Current costing home page in FileMaker with budget reports, CCIs, variations etc """ project = Project.objects.get(id=project_id) context = {'project': project, 'mini_form':CostingMiniForm(instance=project)} if project.budget_overview.deposit_budget_saved: curr_budget = Budget.objects.get_or_create(project=project, version_number=None, current_marker=False)[0] context['current_budget'] = curr_budget return render(request, 'costing/costing_post_deposit.html', context) … -
Template does not exist at / error exception at- loader.py line 43
I am trying to create a home page for my django project. I keep getting this error: TemplateDoesNotExist at / home.html Request Method: GET Request URL: http://xtradev.local/ Django Version: 1.9 Exception Type: TemplateDoesNotExist Exception Value: home.html Exception Location: /home/epic/EPIC/venv/lib/python2.7/site-packages/django/template/loader.py in get_template, line 43 Python Executable: /usr/bin/python Python Version: 2.7.9 Python Path: ['/home/epic/EPIC/EPIC-PROJECT/EPIC-Django/EPIC_AR', '/home/epic/EPIC/venv/lib/python2.7/site-packages', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7'] Server time: Thu, 8 Dec 2016 14:04:41 +0000 My settings.py looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My templates folder is located in my project folder and contains a home.html This is the code from loader.py (but I don't have my head around what it's doing / requesting exactly): def get_template(template_name, dirs=_dirs_undefined, using=None): """ Loads and returns a template for the given name. Raises TemplateDoesNotExist if no such template exists. """ chain = [] engines = _engine_list(using) for engine in engines: try: # This is required for deprecating the dirs argument. Simply # return engine.get_template(template_name) in Django 1.10. if isinstance(engine, DjangoTemplates): return engine.get_template(template_name, dirs) elif dirs is not _dirs_undefined: warnings.warn( "Skipping template backend %s because its get_template … -
Django AJAX GET list via context
I want to send an array of IDs from my HTML to the Django backend and return the corresponding queryset as context. So far I have the following code but it just does not work and I could not find any solution: HTML Form: <form id="select_form" method="get"> <button type="submit" id="submit_selection_button" .btn-lg">Submit</button> </form> jQuery: <script type="text/javascript"> $(document).ready(function() { $("#submit_selection_button").click(function() { selectedFoo = [1,2]; $.ajax({ type: 'GET', url: '/', data: {'selected_foo[]': selectedFoo}}); }); }); </script> Django View: class FooBar(TemplateView): def dispatch(self, request, *args, **kwargs): self.request = request return super(FooBar, self).dispatch(request, *args, **kwargs) def get_queryset(self): return super(FooBar, self).get_queryset() def get_context_data(self, **kwargs): context = super(FooBar, self).get_context_data(**kwargs) selected_foo = [] if(self.request.method == "GET"): selected_foo = self.request.GET.getlist('selected_foo[]') if(selected_foo): bar_results = Bar.objects.filter(id__in=selected_foo) else: bar_results = Bar.objects.none() context = { 'bar_results': bar_results, } return context foobar = FooBar.as_view() So my problem is that I receive a GET request, but when I try to use "selected_foo" it is just empty. I probably made a mistake in the jQuery part but I'm a beginner and don't know what I did wrong. Please help me and explain. Thanks -
Django - Only ONE specific static file GET 404
When refactoring the templates of a Django Project, the response of ONE SPECIFIC .js static file is 404: Terminal: [08/Dec/2016 13:54:43] "GET /static/new_site/js/general_scripts.js' HTTP/1.1" 404 1718 [08/Dec/2016 13:54:43] "GET /static/new_site/js/core.min.js HTTP/1.1" 200 758545 HTML ... <script src="{% static 'new_site/js/general_scripts.js' %}'"></script> <script src="{% static 'new_site/js/core.min.js' %}"></script> </body> </html> Paths: .../static/new_site/js/general_scripts.js .../static/new_site/js/core.min.js Django==1.8.17 OBS: Pycharm IDE is aware of both files -
Django - extended User profile, object does not exist, how to create a blank record?
ive created a user profile class as per below, if the user clicks on the my account page and they dont have a record i get the below error: RelatedObjectDoesNotExist at /profile User has no userprofile. Exception Type: RelatedObjectDoesNotExist Exception Value: User has no userprofile. and this is the error line profile_form = ProfileForm(instance=request.user.userprofile) so i thought i need to put a try around that section? but im not sure how to create a record as the exception? Thanks Models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings # Create your models here. class UserProfile(models.Model): mpls_m_subscriptions = models.CharField(max_length=50,verbose_name="MPLS Maintenance Subscription",choices=settings.SUBSCRIPTION_TYPE,blank=True,null=True) user = models.OneToOneField(User, on_delete=models.CASCADE) views.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=request.user.userprofile) if profile_form.is_valid(): profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('home:profile') else: messages.error(request, ('Please correct the error below.')) else: profile_form = ProfileForm(instance=request.user.userprofile) return render(request, 'home/profile.html', { 'profile_form': profile_form }) -
Show Django Admin views in my App
I am creating a website and I want to bring some of the functionality from django admin to my app. Something like adding users and group should be something anyone can do from my app. They don't have to go to www.website.com/admin/ to do that. I also have written some other functionality in admin which can be useful for general user. Please advise. Thanks. Have a great day. -
Filter on calculated representation of some fields
I have three numeric columns in my model that together create a string, which is presented to the user: class Location(models.Model): aisle = models.PositiveIntegerField() rack = models.PositiveIntegerField() plank = models.PositiveIntegerField() def __unicode__(self): return "{a:02}{r:02}{p:02}".format(a=self.aisle, r=self.rack, p=self.plank) Now I want to filter on (part of) that string, so say I have three locations, 010101, 010102, 010201, and I filter on 0101, I want to select only the first two. How would I do that, I looked into the Q objects and available database functions, but I don't find a solution. -
highlight with code instead of text
I have problem with highlight in django app template. Below is my code and I get text and part of jQuery code. I tried with safe filter but it is not working for me. {% highlight other.raw_content with search_query html_tag "b" max_length 300 %}