Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Invalid HTTP_HOST header: 'mydomain'. You may need to add u'mydomain' to ALLOWED_HOSTS
This comes up when I try to access my site with the domain name, but it works fine when I use the IP address. I've tried adding 'mydomain', u'mydomain', and my IP address to ALLOWED_HOSTS in settings.py, but always get this error -
Pre-Caching API URL Django
I have a few api urls that return some json and I am also using django's builtin cache system. This works wonderfully except for the first user that uses the site. It will take a long time initially cache everything. So I want to write a Management Command that will make a request to these urls. On my server side I do receive the request but it is not successfully cached. Here is a part of my script where I make the call: import requests response = requests.get('url') content = json.loads(response.content.decode('utf-8')) So my question is, does the request module not enable caching? -
Stream music on template in Django
I'm building Django website to stream music from internet. As we got the url of audio file from which we can stream audio and it's working but I don't know how to make it play on webpage on users action. -
How to include javascript in Django template?
In my Django project 'pizzeria', I have created a static files folder for the app 'pizzas', so the folder structure is: pizzeria/pizzas/static/pizzas/. Inside this folder I have a javascript 'hack.js': //hack.js <script> document.getElementById("home page").innerHTML="Hacked!" </script> Now I want to include this script in my Django template (pizzeria/pizzas/templates/pizzas/base.html), however the following setup does not work (the innerHTML does not change on button click): {% load static %} <p> <a href="{% url 'pizzas:index' %}" id="home page">Home page</a> <a href="{% url 'pizzas:pizzas' %}">Our pizzas</a> <button onclick="{% static 'pizzas/hack.js' %}">Hack!</button> </p> {% block content %} {% endblock content %} What am I doing wrong? -
Django: how can I save objects to the database using FormView and ajax?
I am building an application using google maps api where users can add and save markers on the map. I am using ajax to send the form containing marker attributes to the backend. I am using django's heleper FormView: ajax.js: $(document).on('submit', '.add_marker_form', function(event){ event.preventDefault(); // parse form attributes: // (irrelevent code here) $.ajax({ method: 'POST', // or 'type' url: '/map/saveMarker/', data: data // the four attributes success: function(data){ console.log("marker saved"); }, error: function(data){ console.log("marker not saved"); } }); }) // document forms.py from django.forms import ModelForm from .models import myModel class SaveMarkerForm(ModelForm): class Meta: model = myModel fields = ['title', 'url', 'latitude', 'longitude'] mixin.py from django.http import JsonResponse class AjaxFormMixin(object): def form_invalid(self, form): response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): form.save() response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): data = { 'message': "Successfully submitted data." } return JsonResponse(data) else: return response views.py import requests from django.views.generic.edit import FormView from .forms import SaveMarkerForm from .mixin import AjaxFormMixin class SaveMarkerView(AjaxFormMixin, FormView): form_class = SaveMarkerForm template_name = 'map.html' success_url = '/' But after submitting the form, the objects are not saved in the database. As you can see I added form.save() to form_valid method as suggested … -
django post_save signals on model with two FKs
I have the three models provided by django-organizations: (clearly in pseudo-code) Organization: id #(PK) name OrganizationUser: id #(PK) user_id #(FK to the User model) org_id #(FK to the Organization Model) OrganizationOwner: id #(PK) org_id #(FK to the Organization Model) org_user_id #(FK to the OrganizationUser Model) When a user registers to my app, I want them to pass the name of the Organization they would like to create. For that I combine two forms into a single view (the UserCreationForm and my own OrgForm which is just a ModelForm derived from the Organziation Model (aka just a char field) <form action="" method="post">{% csrf_token %} <table> {{ org_form }} {{ user_form }} </table> <input type="submit" /> </form> With this I have successfully populated both the User and the Organization models. However I would like to grab the post_save signals and automatically populate the OrganizationUser and subsequently the OrganizationOwner models. For now, I'm focusing on the former. The issue arises from the fact that OrganizationUser depends on two FKs (user_id and org_id), so the save method for that model raises an error if any of the two is missing. @receiver(post_save, sender=User) @receiver(post_save, sender=Organization) def create_user_org_profile(sender, instance, created, **kwargs): if created: org = OrganizationUser() … -
how do I create an encrypted read only view of one of the pages of my website?
My users want to create a read only view of one of the pages of the website and send it to their clients. What is the best way to do this? I thought I would encrypt the link (example, http://ap.com/ut/dec/3/st/view_st.html) and display it in another page for them to cut and paste and view. When it is viewed, the encryption should be removed. Would this work? How would I do this? Does anybody have a better idea? -
Django subscription system
I have a some system with react on frontend and Django - as a backend (Django Rest Framework). Now I don't know exactly what the way to choose for subscription billing system. I read about stripe also, read about other subscriptions, but don't understand finally what the right way. Peoples may pay with card or paypal. Also, subscription have a some recurring (one month, one year). Tell me please, what the more best way to do it? Thanks a lot. -
Django Custom Template Tag convert JSON for template usage
I have a string JSON from model. {'street': 'xxxxx', 'unit': 'xxxxx'} May I know how should I do to render in template with @simple_tag? {% json_convert location as data %} so i can access, {{ data.street }} -
its possible order columns like this template in reportlab?
i'm trying to create a report like this image, but doest look like that, cause i dont know to much about reportlab, maybe i need to declare a third frame, to reply the third column : from reportlab.platypus import BaseDocTemplate, Frame,FrameBreak, Paragraph, PageBreak, PageTemplate #TwoColumns title frame_right = Frame(document.leftMargin, document.bottomMargin, document.width/2-6, document.height, id='col1') frame_left = Frame(document.leftMargin+document.width/2+6, document.bottomMargin, document.width/2-6, document.height, id='col2') #maybe declare a new frame #Append paragrah and breack frame 1 story.append(Paragraph("Documento subido {}".format(analysis.suspect_filename), styles["Title"])) story.append(FrameBreak()) #Append paragrah and breack frame 2 story.append(Paragraph("Índice de plagio <font color ='red'> {}</font>".format(suspect_percentage), styles["Title"])) document.addPageTemplates([PageTemplate(id='TitleCol',frames=[frame_right,frame_left]), ]) story.append(FrameBreak()) -
Django -- User' object has no attribute 'backend' When Registering New User
Working on a sign up form, and when all inputs are submitted, the user is correctly populated in database, but the web page is generating the following error: AttributeError at /accounts/sign_up/ 'User' object has no attribute 'backend' i've searched for the last hour but can't figure what this issue might be i don't see any backend declared in settings, but i thought that this was automatically set with built in Django Auth? Anyways here is my stack trace: Traceback: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\accounts\views.py" in sign_up 55. login(request, user) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\__init__.py" in login 112. request.session[BACKEND_SESSION_KEY] = user.backend File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py" in inner 205. return func(self._wrapped, *args) Exception Type: AttributeError at /accounts/sign_up/ Exception Value: 'User' object has no attribute 'backend' which appears to be pointing back to my sign_up view here: def sign_up(request): form = forms.UserCreateForm() if request.method == 'POST': form = forms.UserCreateForm(data=request.POST) if form.is_valid(): form.save() user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email = form.cleaned_data['email'] ) login(request, user) messages.success( request, "You're now a user! You've been signed in, too." ) return HttpResponseRedirect(reverse('home')) # TODO: go to profile return render(request, 'accounts/sign_up.html', {'form': form}) and here is my custom … -
Email Accounts and PythonAnywhere
I have my domain name through Enom and my web app on PythonAnywhere. How do set up email accounts using my domain name? Please provide explicit instructions for using Google, or Enom, or a hosting company. I am not sure how to go about it. Thanks in advance. -
django redirect causes a redirect to next page, but then returns to original?
My redirect function is causing some issues. I call a url from a view using reverse with the parameters required for the view. There is not errors and in the browser of the url it corerctly displays theses parameters. However it seems like it redirects to the new url, but immediately after requesting the new view for the new url the page returns to the original view with the new url still displayed in the browser. Can anyone tell me if I am using the redirect function correctly or maybe i am using the reverse incorrectly? P.S. I chopped out a lot of code bc stackoverflow won't let me post all of it. home/urls.py from django.conf.urls import url from home import views app_name = 'home' urlpatterns = [ url('^$', views.index, name='index'), url('^patient_summary/patientid=(?P<patient_id>\d+)&clinicid=(?P<clinic_id>\d+)/', views.patient_summary, name='patient_summary'), url('^patient_summary/patientid=(?P<patient_id>\d+)&clinicid=(?P<clinic_id>\d+)/careplanid=(?P<careplan_id>\d+)/', views.care_plan, name='care_plan'), ] home/views.py def patient_summary(request, token, patient_id, clinic_id): user = get_user(token) if request.method == "POST": if ('careplanselected' in request.POST): props = request.POST.get('careplan') props = props.split("@") CPID = props[0] cpname = props[1] my_dict = {'token': token, 'patient_id': patient_id, 'clinic_id': clinic_id, 'careplan_id': CPID} return redirect(reverse('home:care_plan', kwargs=my_dict)) return render(request, 'home/patient_summary.html') def care_plan(request, token, patient_id, clinic_id, careplan_id): user = get_user(token) care_plan = [] cpname = '' return render(request, … -
heroku django.db.utils.ProgrammingError: column foo.foo_id does not exist after migrations
trying to understand the db behavior of an app I've deployed to heroku. no errs on deployment. make sure I'm starting with a clean db: $ heroku pg:reset $ heroku .. manage.py makemigrations -a fooapp the db will makemigrations, but indicates: You are trying to add a non-nullable field 'foo' to bar without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py I've been selecting '1' giving it a default value, and then makemigrations runs and completes and I see the new migrations applied. then I migrate, and migrate appears to run successfully (each migraiton for each table is "OK"). but then I see in logs, app throws err The above exception was the direct cause of the following exception: Mar 02 08:21:28 fooapp app/worker.1: Traceback (most recent call last): Mar 02 08:21:28 fooapp app/worker.1: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner Mar 02 08:21:28 fooapp app/worker.1: response = get_response(request) Mar 02 08:21:28 fooapp app/worker.1: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response Mar … -
set a parameter with default value to route url in django
Hy all! I'm new to python / django and I came across a problem that I can not solve. I have a route configured for the site's home (1) and a route configured for categories (2): 1) url(r'^/(?P<c=vinhos>\w+)/$', IndexView().home, name='home') 2) url(r'^categoria/(?P<path>.*)/$', IndexView().by_category, name='by_category') I need to set my home url to open a category by default, something like www.mysite.com/c=defaul_category I tried in some ways, including: url (r '^ / (? P \ w +) / $', IndexView (). Home, name = 'home'). But I know it's incorrect. So... I have no idea how to do this. Could someone help me? Thank you -
How to use Bootstrap 4 and Bootstrap 2 on the same page
I have a Django application which is written in Bootstrap 4. On one page I am using a control which is written in Bootstrap 2, So if I use Bootstrap 2 on that page then controls works but other controls gets broke. If I use Bootstrap 4 then other control works except for the one which is written in Bootstrap 2 as Bootstrap 4 is not backward compatible. Basically, I am trying to use Bootstrap Tags Input written in bootstrap v2.3.2. Is there any way to tackle this issue, any guidance would be highly appreciated. -
Django with non org backends
Can someone give basic example (urls.py, models.py, views.py) on how to use Django with abstract non ORM backend? What to extended and override? Unfortunately all examples on Django still assume ORM use. In my case, I try to make it work against Google BigTable using Python API -
Django generic ListView two models
In django template i need to iterate over two models with two different information but doing nested loops for inside for think that is wrong. In addition this code in template does not work. I created two views that references to the same template. template Inside each module should be it's own childs. {% if all_modules %} {% for module in all_modules %} <li><a class="scrollto" href="">{{ module.name }}</a> <ul class="nav doc-sub-menu v"> {% for child in all_childs %} <li><a class="scrollto" href="#step1">{{ child.name }}</a></li> {% endfor%} </ul> </li> {% endfor %} {% else %} <li><a class="scrollto" href="">None</a></li> {% endif %} In views class BackendModulesListView(generic.ListView): template_name = 'backend_modules.html' model = BackendModules context_object_name = 'all_modules' class ChildsListView(generic.ListView): template_name = 'backend_modules.html' model = Child context_object_name = 'all_childs' queryset = Child.objects.filter(backend_modules_id=1) In models class Child(models.Model): name = models.CharField(max_length=255) backend_modules = models.ForeignKey(BackendModules, null=True, blank=True, related_name='backend') frontend_components = models.ForeignKey(FrontendComponents, null=True, blank=True, related_name='frontend') Please help me to find solution and optimize code. I know i write bad code :( -
The cloud panel doesn't into directory in django
I write cloud panel write python/django. My problem is, urls.py doesn't access next forward directory. I use apache. when it is go to next forward, this page is showing: https://postimg.org/image/b1t9s26b9/ my urls.py inside: from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic.base import TemplateView admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$','explorer.views.home',name='home'), url(r'^servers/$','explorer.views.servers'), url(r'^addserver/$','explorer.views.addserver'), url(r'^removeserver/$','explorer.views.removeserver'), url(r'^manage/(?P<server>[\w]+)/(?P<path>[\w]+)/$','manager.views.filemanager'), url(r'^navback/(?P<server>[\w]+)/(?P<path>[\*\w]+)/$','manager.views.navbackward'), url(r'^naviforward(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<dir>[\w]+)/$','manager.views.navforward'), url(r'^edit/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.editdata'), url(r'^saveandsend/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.senddata'), url(r'^upload/(?P<server>[\w]+)/(?P<path>[\*\w]+)/$','manager.views.uploadfile'), url(r'^delete/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.deletefile'), ] my views.py inside: https://postimg.org/image/s2c60qr2d/ views.py inside for ssh connection and sftp connection : https://postimg.org/image/635rdjhxx/ my routing to html file inside: <div class="col-md-4"> {% if path != orginalpath %} <a href="http://127.0.0.1:8000/navback/{{ server }}/{{ modpath }}/"><span class="glyphicon glyphicon-arrow-left" style="color: #ac2925;height: 30px"></span></a> {% endif %} {% for d in dirs %} <ul> <li> <span class="glyphicon glyphicon-folder-close" style="color: #eea236"></span> <a href="http://127.0.0.1:8000/naviforward/{{ server }}/{{ modpath }}{{ d }}/">{{ d }}</a> </li> </ul> {% endfor %} </div> if you're access to project and image you can be look in link: https://postimg.org/gallery/3iakj1t7a/ https://gitlab.com/rection/Cloud-Panel-Django.git How to be solution my problem? -
access user's information using token
I am using Djoser for authentication in django. I have a model class called wallet which looks like following: from django.db import models class Wallet(models.Model): account_address = models.CharField(max_length=100) user = models.OneToOneField('auth.User', related_name='account_no', on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Wallet, self).save(*args, **kwargs) and then i have serializer class for this model which looks like following. from rest_framework import serializers from wallet.models import Wallet class WalletSerializer(serializers.ModelSerializer): class Meta: model = Wallet fields = ('url', 'account_address', 'user') I want to write an api_view for this model class with get method that returns the wallet address for a particular user. Can anybody tell me how to do this? -
No Such Table: 'Auth User' Error with Django Sign Up Form
Trying to register a user on my site, and getting this error when submitting. OperationalError: no such table: auth_user i've run makemigrations and migrate as suggested in other posts but it hasn't helped. if i go to the accounts/sign_up page (which calls the sign_in view), enter the username and password, i get the aforementioned error. Note that in my settings file, i am also bypassing auth_user model like so: AUTH_USER_MODEL = "accounts.User" this is the traceback: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 323. return Database.Cursor.execute(self, query, params) The above exception (no such table: auth_user) was the direct cause of the following exception: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\accounts\views.py" in sign_up 46. if form.is_valid(): File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\forms.py" in is_valid 161. return self.is_bound and not self.errors File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\forms.py" in errors 153. self.full_clean() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\forms.py" in full_clean 364. self._post_clean() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py" in _post_clean 402. self.validate_unique() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py" in validate_unique 411. self.instance.validate_unique(exclude=exclude) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in validate_unique 930. errors = self._perform_unique_checks(unique_checks) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in _perform_unique_checks 1025. if qs.exists(): File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in exists 651. return self.query.has_results(using=self.db) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py" in has_results 501. return compiler.has_results() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in … -
Django mptt: Get all descendants of a category
I would like my categories to show all items in that category including descendant categories, so the parent category contains all items for subcategories. I have tried adding this method to my Category class in models.py def get_all_products(self): # To display all items from all subcategories return Product.objects.filter(category__in=Category.objects.get_descendants(include_self=True)) And added this to my template.html, but it does't work. What am I doing wrong? {% for product in instance.get_all_products %} <li>{{ product.product_name }}</li> {% empty %} <li>No items</li> {% endfor %} -
Excel table to django model
I am trying to move from excel based form submissions to a web form, but having a problem to figuring out how to store a summary table (from excel) to a database. Excel table, which is submitted quarterly looks like this: |total|at x|at y|other x|other y| ----+-----+----+----+-------+-------+ LD1 | | | | | | LD2 | | | | | | CD1 | | | | | | CD2 | | | | | | ----+-----+----+----+-------+-------+ and I have a problem converting it into a model. I am thinking to create a choice type (LD1, LD2..) for the first column, iterate over those choices and create 4 forms with the choice already filled. My first question - is it the way to go or is there a better way to store this kind of information? Second - how to create those 4 forms, that have first field as a non input (read-only) field? -
Are there any stable opensource rich text editor packages that are compatible with django-2?
I have tried tinymce. But, it has dependency of communicating to tinymce site for checking plugins. Is there any other completely opensource text editor to be used in django 2? Quill seems not stable for django 2. I need to make changes at serveral places, but still couldn't make it work. -
Having a group admin in django
I am trying to create a django app with a user model and a team model...There is a team admin who can add or remove a user in a group...what permission should the admin be given and how is this made possible?