Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - perform a prefetch on a select related?
Is it possible to perform a prefetch on a select related query? in my view as an example below, I have a mapping table where I get all the circuits related to a site and then prefetch circuit fields. however I would also like to get circuit maintenances... the circuitmaintenance model has a foreign key to circuits only so I need something like select related circuit, then prefetch circuit maintenance in circuit, I tried just doing .prefetch_related('circuit_maintenance') \ but this gave an error due to model inheritance this is my current view: site_circuits = SiteCircuits.objects.filter(site_id=site_id) \ .exclude(circuit__decommissioned=True) \ .select_related('site') \ .select_related('circuit') \ .prefetch_related('circuit__circuit_type') \ .prefetch_related('circuit__circuitfiles') \ .prefetch_related('circuit__circuitnotes') \ .prefetch_related('circuit__provider') \ .prefetch_related('circuit__service_contacts') \ .prefetch_related('circuit__circuit_type') \ -
maximum recursion depth exceeded - Pycharm, Django, Python3
im quite new to python and im currently writing myself a blog application but i got stuck a some point. currently im facing the following error: ':'.join(parents + (url.namespace,)) for url in url_patterns RecursionError: maximum recursion depth exceeded i got two urls.py files. one at /mysite and the next one at /mysite/myapp /mysite/urls.py: from django.conf.urls import url from quickblog import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), ] /mysite/myapp/urls.py: from django.conf.urls import include from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('quickblog.urls')), ] mysite/myapp/models.py: from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title /mysite/myapp/admin.py: from django.contrib import admin from .models import Post admin.site.register(Post) I guess i'm simply doing something wrong here. Any hint would be nice :D Thank you guys -
PDF output using Weasyprint not showing images (Django)
I am trying to output PDF on Django using the Weasyprint library, but the images don't appear on the generated PDF. I have tried both relative and static URLs for the images, but even the static URL doesn't show the image. When opening the HTML itself on chrome, the images do show. Here is my pdf generation view in the views.py file: def pdf_generation(request, some_slug) stud = Student.objects.get(some_slug=some_slug) studid = stud.some_slug context = {'studid':studid} html_string = render_to_string('templates/pdf_gen.html', context) html = HTML(string=html_string) pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/detail_pdf_gen.css')]); response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="mypdf.pdf"' return response Here is the part of the HTML of the image: <DIV id="p1dimg1"> <IMG src="{% static 'img/wells.jpg' %}" alt=""> </DIV> And the CSS: #page_1 #p1dimg1 {position:absolute;top:0px;left:0px;z- index:-1;width:792px;height:1111px;} #page_1 #p1dimg1 #p1img1 {width:792px;height:1111px;} Thank you very much -
What to do when django cannot start?
I am trying to deploy django with nginx and uwsgi. Nothing works on socket. I tried to change privileges but fruitless. Err_connection_refused. In error.log nothing. How can I solve this problem? -
Development using different version of Python
I'm developing a website using a server with Debian 8.10 (Jessie) as its OS and Python 3.4.2 (the supported Python version for Debian Jessie) while my notebook is using Ubuntu 16.04 and Python 3.5.2 (I think it's also the default version for Ubuntu 16.04). I was planning to build my website using Django 1.11 which both Python versions (3.4 and 3.5) support. Is there any compatibility issues when I develop it using my Python 3.5.2 and deploy it to a Python 3.4.2 server? If any, how much the trouble it will be? I know I can install any version of Python by adding someone's repository, but it seems unofficial so I avoid doing it. And there is a workaround that come to my mind: intall a specific version of Python by download its tarball file from the official website Which will you recommend most? Upgrade my server's Python version to 3.5.2 by adding someone's repo Download Python 3.4.2's tarball and install it to my local machine Upgrade my server's OS to Debian 9 Stretch which its default Python version is 3.5.3 Or any other better idea? Or perhaps you have a way to install specific Python version? *I have some … -
ho to go in depth of data base using django rest framework
i want to build api for company like API/companies_list/ API/companies_list/{id of particular company}/ API/companies_list/{id of particular company}/departments_list/ . . . API/companies_list/{id of particular company}/departments_list/{id_of particular department}/employees_list/{employee id} can any one suggest what approach to use, i came across detail router and list router but the explanation seems not satisfying. my model has employee is child of department, department is child of company. in my present api model i have used viewsets for department, employee, company, but i am having the urls like API/companies_list/ API/companies_list/{id of particular company}/ API/departments_list/ API/departments_list/{id} API/employee_list/ API/employee_list/{id} due to this structure grouping is difficult. Thank you in advance. -
TypeError at postStream↵'bool' object is not iterable↵↵Request Method: POST↵Request
I have below code that is expected to return top 1 record where id > jquery posted value. def postStream(request): post = PostEntry.objects.filter(id > request.POST['maxpostid'])[:1] response_text = serializers.serialize('json', [post,]) return HttpResponse(request.POST['maxpostid'], content_type='application/json') Due to some reason, it gives below error. TypeError at postStream↵'bool' object is not iterable↵↵Request Method: POST↵Request I can confirm that request.POST['maxpostid'] is giving expected value. Am I doing anything wrong? -
Constantly need to reset django local settings module
I have made two settings files, one for local testing and one for production (heroku). Every time I pull and start working locally I need to run the following two commands for it to work: export DJANGO_SETTINGS_MODULE= DJANGO_SETTINGS_MODULE=projectName.settings_local Without doing so I get the error that the local settings module cannot be found. This error appeared after I tried to have both settings files in a settings folder, which I did not get to work so I put them back in the original place. Does anyone have an idea how I can fix this? -
Get vimeo video info (Python) --- Different responses on Developers API and POSTMAN
When I make authorized call to Developer API to get video info for a specific video then I get response: { ... "files": [ ... ... { "quality": "hd", "type": "video/mp4", "width": 1280, "height": 720, "link": "LINK", "created_time": "Time", "fps": value, "size": size, "md5": "value", "link_secure": "link_source" }, ... ... ], "download": [ ... ... { "quality": "source", "type": "source", "width": 1920, "height": 1080, "expires": "time", "link": "link", "created_time": "time", "fps": value, "size": size, "md5": "value" }, ... ... ] } I am using Pyvimeo==0.3.2 and Pyvimeo==1.0.0 for Vimeo. But when I hit "https://api.vimeo.com/videos/{vimeo_id}" (with Client_id and Authorization) from my server or from POSTMAN then I get only: { ... "download": [ ... { "quality": "source", "type": "source", "width": 1920, "height": 1080, "expires": "time", "link": "link", "created_time": "time", "fps": value, "size": size, "md5": "value" }, ... ] ... } There is not key "files" in API response. Why I am not getting "files" key in video response ? There is no any such update in API docs. -
run python script for xml validation in admin.py
Please help, how to run python script in admin.py in django I have xml validation script to validation xml and xsd file, and I want to run the script in admin.py with action in admin.py -
django.db.utils.ProgrammingError: (1146, "Table 'customer.theapp_post' doesn't exist")
I used two databases:one is default sqlite3 and another mysql. I just created a model Post under models.py under app named 'theapp'. I just also created routers.py under the app. This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'customer': { 'NAME': 'customer', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': 'haha', } } This is my routers.py in app called 'theapp' class CustomerRouter: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'theapp': return 'customer' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'theapp': return 'customer' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth app is involved. """ if obj1._meta.app_label == 'theapp' or \ obj2._meta.app_label == 'theapp': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if app_label == 'theapp': return db == 'customer' return None This is my models.py under the app named 'theapps' from django.db import models from … -
Django redux form customisation
how can I add placeholder to django redux form? I have no app in my project, only using redux authentication.I want to remove all the labels and instructions and just palceholder I want -
ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': cannot import name 'flatatt'
I create a project use django, and the upload it to heroku. It can run successfully in local environment, and functions can also work well. I upload successfully without any problems, but when I visit it in heroku(https://APP_NAME.herokuapp.com/), it have some issues like this: InvalidTemplateLibrary at / Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': cannot import name 'flatatt' Request Method: GET Request URL: https://mighty-harbor-16554.herokuapp.com/ Django Version: 2.0.2 Exception Type: InvalidTemplateLibrary Exception Value: Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': cannot import name 'flatatt' Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py in get_package_libraries, line 125 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.4 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Sun, 25 Feb 2018 02:19:09 +0000 I tried to use django-bootstrap4, but it also have deployment problems with django-bootstrap3. How can I do? Thanks a lot. -
Django: can I omit ".save(commit=False)" in this case?
Here's the snippet from a view function for ModelForm in Django: if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() Would substituting this code with the following one have the same effect?: if form.is_valid(): form.topic = topic form.save() If so, what is the use of creating new_entry object like in the first example? -
Django call url from another application in same project
Sorry for my english. I have app call_from_this and app i_use_this in same project. I need in application i_use_this form view call url from application call_from_this. For example: simple example structure project: -call_from_this --urls --views --.... -i_use_this --urls --views --... in my app i_use_this Views: class TestCall(generics.GenericAPIView): def get(self, request): url = 'http://' + request.get_host() '/test_call/' response = requests.get(url=url) return HttpResponse(response, content_type='application/json') in my app call_from_this urls urlpatterns = [ re_path('test_call/', cache_page(CACHE_TIME_UPDATE(views.BalanceReport.as_view())), ] its work, but i have problem: I use cache, and if i call same url from my app i_use_this Views and then from app call_from_this Views create two chache, not one. -
Unexpected chars in the html side
My html is like this. <div style="display:none" maxpostid="{{maxpostid}}" maxcommentid="{{maxcommentid}}"></div> and passing the context like below. context = {'maxpostid':postid, 'maxcommentid': commentid} return render(request, 'sample.html', context) It shows output like below. <div style="display:none" maxpostid="{u&#39;id__max&#39;: 14}" maxcommentid="{u&#39;id__max&#39;: 42}"></div> There are some unwanted chars coming, Am I doing anything wrong? -
404 when redirected to redirect_uri with a state and code
I am trying to build a django application that will use the YouTube Data API v3. Part of code in views.py YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope=YOUTUBE_READONLY_SCOPE) FLOW.redirect_uri = "http://127.0.0.1:8000/accounts/google/login/callback/" @login_required def index(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: I am being redirected to this. After logging in. It redirects me to - I am following this link from google. I have all the values set in Google Cloud Platform as well. Any sample code will be helpful. -
Delete objects with checkboxes
I want to delete objects in a list which are marked with checkboxes. I have read through other post and tried to understand it, but I seem to be missing something. views.py def phase1(request, id): ... if request.POST.get('delete'): Descriptor.objects.filter(id__in=request.POST.getlist('item')).delete() return render(request, 'szenario/phase1.html', context) template phase1.html <ul> {% for Descriptor in projectdescriptors %} <li> <tr class="item"> <input type="checkbox" name="item" value="{{Descriptor.name}}"> </tr> {{Descriptor.name}} </li> {% endfor %} <form method="post"> {% csrf_token %} <h1><input type="submit" name="delete" value="Delete selected descriptors" /></h1> </form> </ul Pressing the button reloads the page, but the selected entries are still there. What am i doing wrong? Any help is appreciated. Note: I aim on using AJAX and signals as soon as i understand how to use them, but for now i just wanted to make a simple solution to focus on other tasks. -
how to add markers and center map in signup form django-map-widget
using django-map-widget to render a google map so that user can pick his location on the map. it works fine, but... I would like to trigger the map in two ways (dynamically via javascript): 1. trigger to re-center map on x,y 2. trigger to add a marker to map on x,y I tried so many ways, but i can't solve this. Here are just a few of my attempts: var locationRio = {lat: -22.915, lng: -43.197}; var marker = new google.maps.Marker({ position: locationRio, title: 'Hello World!' }); marker.setMap($("#location-map-elem").map); and var locationRio = {lat: -22.915, lng: -43.197}; var marker = new google.maps.Marker({ position: locationRio, map: $("#location-map-elem").map, title: 'Hello World!' }); You can see and play with the form here Thanks in advance :) -
Maintain git with different settings.py for development and production
I have a Bitbucket repo which interacts with my remote server to push production code for my live Django website. However I want to interact with my Bitbucket repo from my local desktop repo - where I want to test development code before pushing to my Bitbucket which is my production. The only file I don't want to push from my local repo is settings.py as it's different for production and development. I can't add it to .gitignore as I still need it to be pushed from my bitbucket repo to my remote server. Any idea what I should do? -
importing the csv file to database in django
I am trying to update my model using the CSV file. In my model I am having one field Foreign key I have to update only that i got few errors like value error How should I update my Foreign key using CSV import Thanks -
How to filter for my requirement?
I have a requirement: in my filter, I want to filter like bellow: messages = Message.objects.filter(to_user=user or from_user=user).all() I mean if the to_user==user or from_user==user all be queried out. I found the bellow related post: How to use OR filter condition in queryset? But this is one params, you see this is different between my requirement scenario. -
How to properly submit only one form in table of ModelForms in Django?
I need to create a table of forms for creating and updating users based on my custom User model. It must look something like this: Form is presented as particular row in table. Save button saves submits form, Delete removes form and the model instance from database, Add button appends new blank form to end of <tbody> but to save new form we need to click Save button. Now I'm stuck and don't know how to properly implement logic above. I need each form to be updated and submitted independently. I looked up for solutions based on ModelFormSet but it submits all forms and does not allow to update only one particular row of data. How we can create prepopulated ModelFormSet where each row of form data can be submitted regardless of other forms in table? Like this: <form action="" method="post"> <tr> <td>1</td> <td> <input type="text" name="username" value="admin" maxlength="255" class="login-input" id="id_username" /></td> <td> <input type="text" name="password" value="" maxlength="128" class="password-input" id="id_password" /></td> <td> <input type="text" name="email" maxlength="255" class="email-input" id="id_email" /></td> <td> <input type="checkbox" name="active" class="checkbox-input" id="id_active" checked /></td> <td> <input type="checkbox" name="staff" class="checkbox-input" id="id_staff" checked /></td> <td> <input type="checkbox" name="reboot_field" class="checkbox-input" id="id_reboot_field" checked /></td> <td><button type="submit" form="form1">Save</button></td> <td><button form="form1" >Delete</button></td> <tr> … -
Calling Zapier trigger from Django Code
Is there any way I can call the "Zapier trigger" from my Django Code, Basically, I am having a Django form where the user will enter several email-id and when the user clicks on send button then I want to send this form data to Zapier in order to do the next action like writing in google spreadsheet or sending email to everyone. -
Django bulk_create not working
I am trying to pass a dict to bulk_create, but it is not working. If someone has used this prior, I would appreciate advice. Django Model: class Servers(models.Model): name = models.CharField(('name'), max_length=128) location = models.OneToOneField('locations.Location', on_delete=models.CASCADE) ip_address = models.CharField(('ip_address'), max_length=128) date = models.DateField(auto_now=True) A print of my dict: { 'Florida': { 'name' : 'server-a', 'location':'Miami', 'ip_address':'172.16.16.1', }, 'Colorado': { 'name' : 'server-b', 'location':'Denver', 'ip_address':'172.16.24.1', }, My function: def add_to_db(data_dict): Servers.objects.bulk_create(Servers(**d) for d in data_dict.values()) My error: ValueError: Cannot assign "'Florida'": "Server.location" must be a "Location" instance.