Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using css files in wagtail (django based framework)
I stuck on REALLY simple thing. But I can't spot what I am doing wrong - I just want to write some CSS for my template. Here's my "gallery" app tree (both of css files contain body{background-color: #000;} to just test if it work): gallery -blah blah -static -css -wagtail_gallery.css -wagtail_gallery0.css -blah blah When I opened source, to see what is going on, i saw this link in head section: <link rel="stylesheet" type="text/css" href="/static/css/wagtail_gallery.css">. When I open it its blank (independly on existance of wagtail_gallery.css). When I go to http://localhost:8000/static/css/wagtail_galery0.css in browser it shows me excepted content. Now, my questions are - How can I use wagtail_gallery.css in template, and how can I import custom css (like wagtail_gallery0.css) file to wagtail template? Sorry if I missed something obvious in this issue, but I am new in wagtail CMS. Also, sorry if I missed some "l" in "gallery" somewhere. -
Unable to run Django Celery after following documentation
I'm attempting to implement celery into a current ongoing django 2 project. I'm using django 2.13 and celery 4.3. Here the code in the init.py: import os from celery import Celery CONFIG_SETTING = 'lp.settings.development_test' # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', CONFIG_SETTING) app = Celery('myproject') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('hello world') Here is the code in the base settings: CELERY_BROKER_URL = 'amqp://guest:guest@localhost//' #: Only add pickle to this list if your broker is secured #: from unwanted access (see userguide/security.html) CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_CACHE_BACKEND = 'django-cache' INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... 'django.contrib.auth', 'django.contrib.admin', 'django_celery_results', ] When I run celery -A proj worker -l info I get the error: 019-05-01 16:08:50,424: CRITICAL/MainProcess] Unrecoverable error: TypeError("argument of type 'NoneType' is not iterable") Traceback (most recent call last): Any idea as to what I'm doing wrong? RabbitMQ is running as a service. Thank You! -
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.8000api', port=80): Max retries exceeded with url:
I am trying to communicate between Django and Python file but I am getting below error errorrequests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.8000api', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed')) I have create a Python file name test.py In a Django app and trying to communicate between them. My Python file contains below code:- import requests BASE_URL='http://127.0.0.8000' ENDPOINT='api/' def get_resource(): resp=requests.get(BASE_URL+ENDPOINT) print(resp.status_code) print(resp.json()) get_resource() My views.py contains:- from django.shortcuts import render from django.views.generic import View from testapp.models import Employee import json from django.http import HttpResponse class EmployeeDetailCBV(View): def get(self,request,*args,**kwargs): emp = Employee.objects.get(id=1) emp_data = {'eno' = emp.eno , 'ename'=emp.ename , 'esal'=emp.esal , 'eaddr'=emp.eaddr} json_data=json.dumps(emp_data) return HttpResponse(json_data , content_type='application/json') urls.py file contains:- from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('admin/', admin.site.urls), path('api/', views.EmployeeDetailCBV.as_view()), ] Getting error like, requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.8000api', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed')) Please help me. Thank you techies.... -
DJANGO WEBSITE: html code cannot locate the jpg location to display within my page
I have made a Django website and pulled a template from w3. I am trying to replace the jpg for the header that they used with my own picture but the webpage cannot find the src for my image. My folder directory is as follows: - Website -websiteFirst -blog -migrations -static (files inside) -templates (files inside) -init -admin -apps - rest of usual scripts for django -WebsiteFirst -init -settings -urls -wsgi I have tried as many variations as possible of the different folders within my project folder. This is the error code with a few different attempts: [06/May/2019 16:51:04] "GET /backgroundwebsite.jpg HTTP/1.1" 404 2113 [06/May/2019 16:51:04] "GET /blog/ HTTP/1.1" 200 7780 Not Found: /websiteFirst/blog/backgroundwebsite.jpg [06/May/2019 16:51:04] "GET /websiteFirst/blog/backgroundwebsite.jpg HTTP/1.1" 404 2167 Not Found: /backgroundwebsite.jpg [06/May/2019 16:51:04] "GET /backgroundwebsite.jpg HTTP/1.1" 404 2113 <div class="w3-padding-large" id="main"> <!-- Header/Home --> <header class="w3-container w3-padding-32 w3-center w3-black" id="home"> <h1 class="w3-jumbo"><span class="w3-hide-small"></span> Garrett Young.</h1> <p>Recent University Of British Columbia Graduate, Prospective Data Scientist, and DJ.</p> <img src="/backgroundwebsite.jpg" alt="boy" class="w3-image" width="992" height="1108"> </header> the image was displayed from a website in the template however I am trying to source it from my personal computer for now. -
Why ajax does not work the first time with JsonResponse Django/Ajax
I adding my products in the cart, use button with product.id. Trying adding in the cart without refresh page and this code working but not work the first time, need refresh, after refreshing it's work good. <a href="javascript:void(0);" class="add_to_cart" data-id="{{ product.id }}"><button>Add in the cart</button></a> it's my url url(r'^cart/create/$', views.cart_create, name='cart_create'), my method return JsonResponse, length of cart and total price def cart_create(request): cart = Cart(request) product_id = request.GET.get('product_id') product = Product.objects.get(id=product_id) cart.add(product=product) return JsonResponse({'cart_length':cart.get_length(), 'cart_total':cart.get_total_price()}) Ajax working, but not the first time (need refresh page) after adding the first product, it works well without refreshing $(document).ready(function(){ $(".add_to_cart").click(function(){ product_id = $(this).attr("data-id") data = { product_id: product_id, }, $.ajax({ type: "GET", url: '{% url "cart:cart_create" %}', data: data, success: function(data){ $(".cart_count").html(data.cart_length + " товаров " + data.cart_total + " &#8381;") console.log('c') }, }); }); }); header {% if cart|length > 0 %} Our cart: <a href="{% url 'cart:cart_show' %}" class="cart_count"> {{ cart.get_length }} products {{ cart.get_total_price }} </a> {% else %} <a href="{% url 'cart:cart_show' %}">Cart empty</a> {% endif %} Server return "GET /cart/create/?product_id=1 HTTP/1.1" 200 And it's work, but not displayed the first time in the header. Please, help me -
Find sibling records that have differences in M2M items
I need to find objects that have differences in Tags among two children (sibling models). Example setup: class Parent(models.Model): pass class Tag(models.Model): name = models.CharField(max_length=256, unique=True) class Child_OLD(models.Models): parent = models.OneToOneField(Parent, ...) tags = models.Many2ManyField(Tag) class Child_NEW(models.Models): parent = models.ForiegnKey(Parent, ...) tags = models.Many2ManyField(Tag) I want to make sure all Tags records on Child_OLD are represented on the Child_NEW record. Specifically, I'd like to find any parent where Child_OLD has tags that Child_NEW does not have, using a faster method than checking each one individually. Here is a loop that accomplishes a similar thing (im only interested in finding parents where the child_old has a tag that child_new does not): diffs = [] for parent in parents: cn_tags = Tag.objects.filter(child_new__parent=parent) qs_diff = parent.child_old.tags.all().difference(cn_tags) if qs.exists(): diffs.append(parent.pk) Again, I'm looking to do this with a queryset, in a more optimized fashion as iterating through each parent is very slow (there are 100mil+ records). -
Cleanly overide pip package for development
I have a django project I am working on that requires a fairly simple pip package. I have found a bug in that pip package. I want to pull the source locally, write some fixes myself, and temporarily have my django project reference the local changes instead of the pip package. What is the cleanest way to do this? Ideally, I would be able to accomplish this with an environment change or a small django configuration change, so that when my patch gets pulled into a release I can easily revert back to using the pip package. -
Django not recognizing app name on import (No module named 'X)
Full disclosure: Django new user here. I worked my way through the tutorials and then started building my own little app. This means that I'm now smart enough to create trouble and not smart enough to solve it :) Everything has been fine so far- I've created models, set up the admin and can run shell to verify it's all working. I started a new script this morning to eat a CSV and create DB records based off of the data. But before I'm even off the starting line I ran into an error when importing my models into the script. Here's the directory structure: [ Here's the script: from msdashboard.models import VRGame, VRGameReview import csv combinedCSVLoc = "csv/2019-04-30_COMBINED_PSVR.csv" print("Starting import of combined PSVR Game Data") with open(combinedCSVLoc,newline = '') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in reader: print(', '.join(row)) Here's the error: ModuleNotFoundError: No module named 'msdashboard' I've checked the settings to make sure it's installed: INSTALLED_APPS = [ 'msdashboard.apps.MsdashboardConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] What silly thing am I missing? I've also tried just importing ".models" which yields ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package -
Llamar a index.html que se encuentra fuera del proyecto
Es la primera web que desarrollo en Django 2 y me ha surgido un problema al intentar subir mi aplicación a un Hosting. Mi index.html debe estar fuera del proyecto justo debajo de public_html y no encuentro la manera de llamarlo desde dentro del proyecto, he probado con ../ a distintos niveles pero nada. Muchas gracias de antemano. -
Use a different form based on variable
I have a "product" field that I want to use to determine which form to display. I am trying to do this in the view but wondering if I should do it in the template instead. I have tried the following but "form" does not get assigned by my if statements. What am I doing wrong? @login_required def update_message(request, pk): message = get_object_or_404(Submission, pk=pk) author = message.author date_posted = message.date_posted product = message.product message_obj = Submission.objects.get(pk=pk) program_type = message.program_type if author == request.user: if request.method == 'POST': if product == 'Apple': form = AppleForm(request.user, request.POST, instance=message) if product == 'Orange': form = OrangeForm(request.user, request.POST, instance=message) if form.is_valid(): message_sub = form.save(commit=False) message_sub.author = request.user message_sub.date_posted = timezone.now() message_sub.save() form.save_m2m() messages.success(request, 'Message updated') return redirect('submission-list') else: if product == 'Apple': form = AppleForm(request.user, instance=message) if product == 'Orange': form = OrangeForm(request.user, instance=message) else: messages.warning(request, 'You can't do that.') return redirect('message-submission-list') return render(request, 'programs/submission_create_form.html', {'product':product,'form': form, 'message_obj': message_obj,'program_type':program_type}) -
How to fix a broken migrate on Django?
The context is the following. My codebase has been written by someone who is not working in my current company anymore. I'm trying to add new features I've created new model that I would like to run. When I'm running python manage.py makemigrations , the script for my model is been generated correctly. However, when I'm running python manage.py migrate, there are many errors like this KeyError: ('mailing', 'questionanswer') or this django.db.utils.ProgrammingError: column "http_request_lang" of relation "cms_dynamicsettings" does not exist Or even this! delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' I'm trying to clean all the mess in the database but I'm not sure how and as you have guessed, I cannot run my model. Would a command like python manage.py squashmigrations <app name> <script number> help? Any clues are welcomed as I'm starting to lose my sanity. Thanks. -
How to save many-to-many data using form.instance?
I am writing an application on Django. How can I save data (provider.category) from form using form.instance. models class RequestProvider(models.Model): category = models.ManyToManyField(Category, related_name="provider_request") forms class ProviderForm(forms.ModelForm): class Meta: model = RequestProvider fields = ('category',) widgets = { 'category': forms.SelectMultiple( attrs={ 'class': 'select2', 'style': 'width: 246px;' } ), } views class ProviderCreateView(CreateView): form_class = ProviderForm template_name = 'provider_create.html' def form_valid(self, form): print(form.cleaned_data.get('category')) #<MP_NodeQuerySet [<Category: Sport>, <Category: Food>, <Category: Car>]> print(self.request.POST) #<QueryDict: {u'category': [u'5', u'1', u'4']}> form.instance.category = form.cleaned_data.get('category') return super(ProviderCreateView,self).form_valid(form) -
How to debug Django custom management command using VS Code
I am trying to debug a custom management command using Visual Studio Code. For this I have gone through the official VS Code tutorials for working with Python and Django, and I have managed to get debugging to work while following these tutorials. VS Code Python tutorial / VS Code Django tutorial The problem is that for a Python script (no Django), the debugger works because I run a specific file (by pressing f5) while the file's tab is open. Django debugging works because VS Code knows when a browser request causes my Django app to hit a break-point I entered in VS Code. But a custom management command is run differently. For this I type the following in the console: python manage.py name_of_management_command How do I debug this in VS Code? -
Static css and js not loading in django pycharm
My settings.py is STATIC_URL = '/some_location/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') My base .html with the directory structure is, My directory root from image above -project directory -->appname -->static ---->css ------>master.css ---->js ----->master.js I use pycharm IDE. The error message I get is "GET /some_location/static/js/master.js HTTP/1.1" 404 1736 "GET /some_location/static/css/master.css HTTP/1.1" 404 1742 When I use the above location /some_location/static/js/master.js in the browser I get to see the file content. What I do to correctly load the .css and .js on the development server in Pycharm? -
How to convert an existing PHP application to adapt to Python Django?
I have been handed over a web application that has been coded using PHP and have been asked to makes changes and add new features to the application. I'm a Python developer who primarily uses Django for all my development. Would it be possible to use the existing PHP code to work along with Django for time being or will I have to convert the application to work with Django? Extremely grateful for any help! Had a look at the python package django-php-bridge 0.1.1 (https://pypi.org/project/django-php-bridge/) it'd be great if someone has any insight on this. -
django retrieve csrf token
In my web application I need to retrieve csrf token for sending some data through xmlhttprequest but I'm getting an error at the server as " django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' ". This is my code //views.py from django.shortcuts import render from django.shortcuts import render_to_response from django.template.context_processors import csrf def interfacePage(request): return render(request, "interfacePage.html", {}) def interfacePageSubmit(request): if request.method == 'POST': datarecvd = request.POST['data'] return render(request, "interfacePageSubmit.html", {}) else: print("in def interfacePageSubmit") csrf1 = str(csrf(request)['csrf_token']) return csrf1 //interfacePage.html function sumbit() { var xhr = new XMLHttpRequest(); var url = {% url 'interfacePageSubmit' %}; xhr.open("GET", url, false); xhr.withCredentials = false; xhr.setRequestHeader("x-csrf-token", "fetch"); xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); var data = null; xhr.send(data); console.log(xhr.readyState); console.log(xhr.status); if (xhr.readyState === 4 && xhr.status === 200) { var csrfToken = xhr.getResponseHeader('x-csrf-token'); url = {% url 'interfacePageSubmit' %}; xhr.open("POST", url, true); xhr.withCredentials = false; xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); xhr.setRequestHeader('x-csrf-token', csrfToken); } **/ further code goes here Pls note my "interfacePage.html only contains a button without any form tag -
Django class based view pagination not working
I am trying to use a pagination to paginate one of my pages. I have tried a few different methods I have found online but for some reason, when I use paginate_by = 3, it doesn't actually paginate anything, yet still shows the html for the pagination at the bottom of the page. View: class SearchListView(ListView): model = Post template_name = "public/search.html" paginate_by = 3 HTML: {% if is_paginated %} <ul class="pagination"> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} So on the page, 3 items should be showing, and pagination should take me to the the next set of 3. The html is showing, and when I click the links it is taking me 2 page 2. The problem is the fact that 6 items are showing, and not 3, and when I go to page 2, there … -
How can I handle POST request and print output on the same page?
I serve a page which has a button and on a button click Django executes script (Ansible playbook) and prints stdout to the same page. It's kind of a very simplistic web-interface for Ansible. Ansible is located on the same machine where Django is. Right now Django view renders this page(HTML template) on HTTP GET, and when button is clicked HTTP POST is invoked which does all Ansible stuff, grabs stdout and renders the same template with additional context. The only problem I have at the moment is manually refreshing after clicking that button. If you hit the button and after that refresh your browser, POST is invoked again including all the consequences (Ansible playbook etc.) What options do I have to solve this problem ? I really need stdout printed on the same page so redirecting to a different page is not an option. Looks very similar to this https://en.wikipedia.org/wiki/Post/Redirect/Get <form action="" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="{% if status == 1 %}Shut Down{% else %}Bring Up{% endif %}" id="submit01"/> -
'Quotes' object has no attribute 'get'
I'm building a quotes app in Django and encounter an error I've tried following the part where it's time to create the quotes app on the book 'Build Your First Website with Python & Django' and editing the parts needed to be synced to Django 2.2.1 Environment: Django Request Method: GET Request URL: http://127.0.0.1:8000/quotes/ Django Version: 2.2.1 Python Version: 3.7.3 Installed Applications: [... 'projects', 'blog', 'home.apps.HomeConfig', 'quotes.apps.QuotesConfig'] Traceback: File "/Users/path/to/env/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/path/to/env/lib/python3.7/site-packages/django/utils/deprecation.py" in __call__ 96. response = self.process_response(request, response) File "/Users/path/to/env/lib/python3.7/site-packages/django/middleware/clickjacking.py" in process_response 26. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /quotes/ Exception Value: 'Quotes' object has no attribute 'get' This should show the quotes page -
Delete group by its creator Django
quick question I have an app, where users can create groups for their friends, after adding some, I would like to keep functions such as delete or update only to the user, who created the group. Can anybody may help? My solution so far is hardcoded, if I add a specific id of a person, only this user can delete the group, but I'd like to have more universal solution. class TripDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Trip success_url = '/' template_name = 'tripplanner/delete_trip_confirm.html' def test_func(self): detailView = self.get_object() # Correct, not hardcode if self.request.user == detailView.profile.get(pk=2): return True return False -
Catch DoesNotExist exception in a generic way
#sample code try: Model_1.objects.get(id=1) Model_2.objects.get(id=1) Model_3.objects.get(id=1) Model_4.objects.get(id=1) except (Model_1.DoesNotExist, Model_2.DoesNotExist, Model_3.DoesNotExist, Model_4.DoesNotExist): ... # do something I'm not sure whether this is a right way to catch the N model exceptions. Is there any other method that I could replace the DoesNotExist exception? -
Limit_choices_to via Q
I am trying to get a list of data from my foreign key related field but it doesn't work with limit_choices_to my model def limit_choices_segment(): return Q(role=Place.CITY) & Q(role=Place.VILLAGE) & Q(role=Place.TOWN) class Segment(CoreModel): start_point = models.ForeignKey(Place, on_delete=models.CASCADE, limit_choices_to=limit_choices_segment, related_name='departing_point') end_point = models.ForeignKey(Place, on_delete=models.CASCADE, limit_choices_to=limit_choices_segment, related_name='arriving_point') routes = models.ForeignKey(Routes, on_delete=models.CASCADE) def __str__(self): return '{}-{}'.format(self.start_point, self.end_point) when i tried it only with single Q(role=Place.CITY) or another it works perfect -
Pycharm development server is running continuously
When I type py manage.py runserver , pycharm is restarting the server over and over again , without giving me a chance to click on the link and open the browser. It s like an infinite loop. How do I stop this. Please help -
Django - UpdateView with multi model forms - one submit
I'm developing the web site where users can register and edit their information. I would like to use multi form in the single page. I can develop register form using CreateView. But when I use UpdateVIew, I don't know how to add initial value in multi form. My code(view.py) is below. I can add form data as initial value, but not form2. Please tell me how to add form2 data as initial value. ▪️view.py class UserUpdate(OnlyYouMixin, generic.UpdateView): model = Profile form_class = ProfileForm second_form_class = ProfileNearStationForm template_name = 'accounts/user_form.html' def get_context_data(self, **kwargs): context = super(UserUpdate, self).get_context_data(**kwargs) if 'form' not in context: context['form'] = self.form_class(self.request.GET, instance=self.request.user) if 'form2' not in context: context['form2'] = self.second_form_class(self.request.GET, instance=self.request.user) return context def get(self, request, *args, **kwargs): super(UserUpdate, self).get(request, *args, **kwargs) form = self.form_class form2 = self.second_form_class return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.form_class(request.POST, instance=self.request.user) form2 = self.second_form_class(request.POST, instance=self.request.user) if form.is_valid() and form2.is_valid(): profile = form.save(commit=False) profile.save() station = form2.save(commit=False) station.user = user station.save() messages.success(self.request, 'Settings saved successfully') return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response( self.get_context_data(form=form, form2=form2)) def get_success_url(self): return resolve_url('accounts:user_form', pk=self.kwargs['pk']) -
How can I test my custom exception class using pytest?
This might be super obvious but I just want to make sure I am testing my exception class correctly. CustomException(APIException): ... I just want to make sure that if I allow a custom message, it does get set correctly, etc.. In my test, should I just raised the exception, catch it and do my asserts there?