Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can a Django Model inherit other Models selectively
Is it possible to dynamically built a model from other models? I want to make an inventory app for different types of tools. i.e ( Screws , Cutters and drill bits), all of these items share common tributes, and some are more specific to them self's(they all share a diameter, length, material it's made from) but a cutter can have other tributes like ( number of flutes and some other tributes that are unique to cutters and the same goes for all the tools I wan to add to the inventory). would this be the best way to go about this? If not can you point me in the right direction please -
Django, Celery: my tasks are shown as unregistered on prod
So I do have my config with Celery tasks which works fine for dev machine. But then I switched to prod machines, and I cannot see task as registered in Celery. My mysite/init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app import pymysql pymysql.install_as_MySQLdb() __all__ = ['celery_app'] celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('stats') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from mysite.celery import app @app.task def collectOnline(): transaction.set_autocommit(False) updateOnline(logoutChars()) updateOnline(getOnline()) transaction.commit() transaction.set_autocommit(True) Tree: mysite β βββ mysite β βββ __init__.py β βββ settings.py β βββ celery.py β βββ stats β βββ tasks.py β βββ manage.py βββ __init__.py Do you have any idea how I could solve it? -
How to use Vue.js inside Django?
Given this model in Django 2, class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') and in my view def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) How can I access the context inside index.html so that Vue.js can consume that data? -
Selenium webdriver crashing Firefox during unittests
How do you determine why Firefox is crashing when run from inside some Django unittests via Selenium? My testcase is: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from pyvirtualdisplay import Display from selenium import webdriver class Tests(StaticLiveServerTestCase): def setUp(self): super(Tests, self).setUp() self.vdisplay = Display(visible=0, size=(1920, 1080), backend='xvfb') self.vdisplay.start() profile = webdriver.FirefoxProfile() log_path = '/tmp/tests.log' self.driver = webdriver.Firefox(profile, log_path=log_path) def test_abc(self): blah When I run this on a headless server with: python manage.py test functional_tests --nomigrations --failfast it almost immediately errors with: ERROR: test_abc (myproject.functional_tests.tests.Tests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/myproject/src/buildbot/worker3/myproject_runtests/build/src/myproject/functional_tests/tests.py", line 15, in setUp self.driver = webdriver.Firefox(profile, log_path=log_path) File "/usr/local/myproject/src/buildbot/worker3/myproject_runtests/build/.env/local/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 158, in __init__ keep_alive=True) File "/usr/local/myproject/src/buildbot/worker3/myproject_runtests/build/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/usr/local/myproject/src/buildbot/worker3/myproject_runtests/build/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/myproject/src/buildbot/worker3/myproject_runtests/build/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/usr/local/myproject/src/buildbot/worker3/myproject_runtests/build/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 237, in check_response raise exception_class(message, screen, stacktrace) WebDriverException: Message: Process unexpectedly closed with status: 1 So webdriver is having trouble initializing a Firefox instance. However, the log file only shows: 1528498122788 geckodriver INFO geckodriver 0.19.0 1528498122799 geckodriver INFO Listening on 127.0.0.1:39255 1528498123950 mozrunner::runner INFO Running command: "/usr/bin/firefox" "-marionette" "-profile" "/tmp/rust_mozprofile.LrTWF7H6fk2y" My versions are: Ubuntu Version is 16.04 Selenium Version is 3.8.1 Geckodriver Version is 0.19.0 Firefox Version is β¦ -
How can I connect my Django project to Alexa Web Information Service (AWIS)
So, I've researched about how to use AWIS in Python and found this Github repository to use AWIS in Python environment. They also provided code snippet for usage. But, I'm confused about where I should put the code snippet in. I've tried putting it in settings.py, but it throws an error saying NameError: name 'AwisApi' is not defined. Is there anyone who has used AWIS in Python? import awis api = AwisApi(ACCESS_ID, SECRET_ACCESS_KEY) tree = api.url_info("www.domain.com", "Rank", "LinksInCount") elem = tree.find("//{%s}StatusCode" % api.NS_PREFIXES["alexa"]) assert elem.text == "Success" -
python django - cookie array elements obtained in server side and client side are different in order
In a python django project I am using this jQuery cookie plugin in client side. In client side I use the code cookie_value_client_side=Cookies.getJSON('name'); to get the cookie value in an array namely cookie_value_client_side. In server side, I use the following code defaultVal = "" valFound = request.COOKIES.get('ids_all', defaultVal) if (valFound != ""): result = urllib.parse.unquote(valFound) cookie_value_server_side= json.loads(result) to get the cookie value in an array namely cookie_value_server_side; cookie_value_client_side and cookie_value_client_side are the same array except that elements in the 2 arrays differ in order. How can I get the two arrays preserve the same ordering regarding theirs elements ? -
Data not saved when using CreateView and ListView on same url
I have the following view.py. The goal is to show CreateView form on each ListView item on same url. Now the textarea is showing, but submitting the form does not save the data. I'd really appreciate any help. view.py: class CreatePost(CreateView): class PostForm(ModelForm): class Meta: model = Post fields = ['post'] widgets = { 'post': forms.Textarea() } class TheList(ListView): model = Item template_name='item/items.html' def get_context_data(self, **kwargs): context = super(TheList, self).get_context_data(**kwargs) context['form'] = CreatePost.PostForm return context -
Django ForeignKey field contains an id which does not correspond to a row, even though ON DELETE CASCADE is set?
I'm working on a Django project which contains the model Family, which inherits from BaseFamily defined similar to from django.db import models from django.contrib.auth.models import User from django.db.models.signals import pre_save from .timestamped_model import TimeStampedModel class BaseFamily(TimeStampedModel): package = models.ForeignKey('lucy_web.Package', models.SET_NULL, blank=True, null=True) lucy_guide = models.ForeignKey( User, blank=True, null=True, related_name='lucy_guide_%(class)s', limit_choices_to={'is_staff': True}) @receiver(pre_save) def link_lucy_guide(sender, instance, **kwargs): """Assign company LucyGuide to family if not explicitly assigned.""" if not issubclass(sender, BaseFamily): return if instance.company and not instance.lucy_guide: instance.lucy_guide = instance.company.lucy_guide We are working in Django version 1.11.9; as I understand it, if on_delete is not specified, it defaults to models.CASCADE (cf. the documentation). Yet in my current database, I have an instance of a family (with employee_first_name='Mark' and employee_last_name='Flores') with a lucy_guide_id of 687: but there is no corresponding auth_user: My question is: how did the database end up in this state? If cascade delete is active, should the family not have been deleted together with its lucy_guide? -
Django: Add optional parameters to a request in the view
In my Django app's views.py I'm passing in a GET request to a function definition. How do I check for an optional parameter in that request (like &optional='All') and if that optional parameter is missing, add it. This is all before the request is sent to the template to be rendered. This is what I have so far: def my_function(request): #get all the optional parameters optional_params_list = request.GET.keys() #see if filter_myfilter is NOT an optional param if 'filter_myfilter' not in optional_params_list: #add filter_myfilter as a parameter and set it equal to All request.filter_myfilter = 'All' return render(request, 'quasar.html') -
Django "TemplateView" and "media" url conflict
I am writing an SPA with Django 1.11 (switching to 2.0 is no an option), as backend, getting all the data from Django Rest Framework API and I route my app via React routing. Here is my my main urls.py : urlpatterns = [ url(r'^api/', include('text_cms.urls')), url(r'^api/', include('photos_admin.urls')), url(r'^admin/', admin.site.urls), url('', TemplateView.as_view(template_name='index.html'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And here is my settings.py file: MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media-files/' The issue is, that the particular url setting url('', TemplateView.as_view(template_name='index.html'), is messing up media url, and files uploaded by user cannot be reached by url link, even though they are saved to folder. When I comment my "Template as view" url or just delete it - everything works fine again. I've tried to serve the template from the other app and registering it in the main urls.py file, but it did not work too urlpatterns = [ url(r'^', views.IndexView), ] views.py def IndexView(request): return render(request, 'main/index.html', {}) -
Why does safari say my website is insecure when a user is entering a password - Django
And to add to the question, how do I make it secure. So the situation is, is that I have a website that I have deployed and I have a sign up form. Whenever I click on sign up and start typing in my information and i get to writing my password, safari warns me that my website is insecure. Why is this? And how do I fix it? EDIT: By the way, I am including {% csrf_token %} in all my POST forms -
Recursion error when using post_save signal with Wagtail admin
I have an Order model and an OrderItem model with an override of save() on Order and a post_save signal for OrderItem so that the Order total and status will be automatically updated upon saving an OrderItem. I have set up a wagtailhooks.py file in which I've set up ModelAdmin for the Order model. Note in the following model definitions that ClusterableModel and ParentalKey have to be used to cause OrderItems to display properly under an Order in the Wagtail admin: class Order(BaseModel, ClusterableModel): ... def save(self, *args, **kwargs): self.calculate_costs() self.set_status() super(Order, self).save(*args, **kwargs) panels = [ MultiFieldPanel([ FieldPanel('number'), ..., ]), InlinePanel('order_items', label="Order Items") ] class OrderItem(BaseModel, Orderable): order = ParentalKey('Order', null=True, on_delete=models.PROTECT, related_name='order_items') product = ParentalKey('Product', null=True, on_delete=models.PROTECT) ... panels = [ ... ] # SIGNALS @receiver(post_save, sender=OrderItem) def update_order(sender, instance, **kwargs): instance.order.save() THE PROBLEM: An order with it's associated order items will display fine when I try to edit it from the Wagtail admin, but when I try to SAVE from the Wagtail admin, I get a maximum recursion depth exceeded error. However, when I save the same order from the DJANGO admin, it saves fine. If I disconnect the post_save signal on OrderItem, the Order then saves β¦ -
Django scaling and saving forms with inheritance
I am quite new to Django. I am currently using ModelForm to save user input data to model. However, I would like to save data to other child models which inherits from parent model. However, my code saves data to the parent model. I guess that save() function should be overwritten to save data to child model, but I have no idea how to do it. Also, how should I scale my template or forms.py to include more forms with different submit button names(or any other method so that submitted forms could be distinguished and database populated accordingly)? Any insights highly appreciated. Please find my code below. forms.py from django import forms from django.forms import modelformset_factory, ModelForm from .models import Assumptions, Scenario1_Assumptions, Scenario2_Assumptions, Scenario3_Assumptions, Scenario4_Assumptions ... Scenario_N_Assumptions class AssumptionsForm(ModelForm): class Meta: model = Assumptions fields = ['Worst_Case', 'Grey_Case', 'Red_Case', 'Blue_Case', 'Green_Case', 'Best_Case'] exclude = () AssumptionsFormSet = modelformset_factory(Assumptions, form=AssumptionsForm, extra = 5) views.py from django.shortcuts import render from .forms import AssumptionsFormSet, modelformset_factory from .models import Scenario1_Assumptions, Assumptions def get_assumptions(request): if request.method == 'POST': formset = AssumptionsFormSet(request.POST) if formset.is_valid(): if 'scenario1' in request.POST: for form in formset: Scenario1_Assumptions = form.save() #THIS DOESN'T WORK if 'scenario2' in request.POST: for form in formset: β¦ -
Ajax redirect me to a blank django template
I have an ajax and when I send the data to my view I return an HttpResponse('') but Insstead of staying in the same page It's redirec me o another page what's it's wrong ? and this is my ajax $("#modificarValor").click(function(e) { e.preventDefault(); $.ajax({ type: "POST",url: "/inicio/update/autor/", data: { id_autor: $(this).val(), nombreautor1 : $('#nombreautor1').val(), segundoautor1 : $('#segundoautor1').val(), apellidoPautor1 : $('#apellidoPautor1').val(), apellidoMautor1 : $('#apellidoMautor1').val(), nombreautor2 : $('#nombreautor2') if (nombreautor2.length){ nombreautor2 : $('#nombreautor2').val() segundoautor2 : $('#segundoautor2').val(), apellidoPautor2 : $('#apellidoPautor2').val(), apellidoMautor2 : $('#apellidoMautor2').val(), } csrfmiddlewaretoken: ("input[name='csrfmiddlewaretoken']").val(), }, success: function(result) { alert('ok'); }, error: function(result) { alert('error'); } }); }); It was working okay, before I added the if (nombreautor2.length), after it it's retun me a black page -
How I can generate a `dict`, maybe `dict` inside `dict` of Django Model?
Hello Awesome People! I'm using to run background tasks, I can't have access to Model in celery tasks, I want to convert these model instances to dict, so I can use them in template as Django has a perfect lookup way with dict like it was a model instance. Such a simple question, for instance class ModelA(models.Model): name = CharField(max_length=123) the_future = ForeignKey('Country',on_delete=models.CASCADE) Class Country(models.Model): name = CharField(max_length=123) img = FileField(upload_to='bathroom/') I expect a dict like: { 'model_name':'ModelA', 'id':1, 'name':'Can you Dab?' 'the_future':{ 'model_name':'Country', 'id':'3', 'name':'Despacito', 'img':'/media/batchroom/teethbrush.jpg', }, } -
How to know level of every child relative to main parent in django-mptt?
I use django-mptt application in my project. Let me try to explain the problem. views.py: user_profile = Profile.objects.get(user=self.request.user) referrals = user_profile.get_descendants().filter(level__lte=profile.level + 3) With the help of next code I show descendants of current user (only 3 level) and want to know level of every child relative to parent. In fact in database that user can have child with level more than 3. In template user A has next tree with 3 level user A user B (level 1) user C (level 2) user D (level 3) In fact in dababase user A has tree more than 3 level as you see. In my case it's 5. user A user B (level 1) user C (level 2) user D (level 3) user E (level 4) user F (level 5) Now when user D open his page in template he see his own descendants: user D user E user F I want to know level of user E and F relative to user D. How to make it? I tried in views.py: for referral in referrals: print(referral.level) This code return me level 4 for user E and level 5 for to user F. -
need help defining foreign keys in django model
this is my models.py file: from django.db import models class Bus(models.Model): """bus details""" number_plate = models.CharField(max_length=9) def __str__(self): return self.number_plate class BusStaff(models.Model): """details of the staff on each bus""" first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) phone_number = models.CharField(max_length=10) bus = models.ForeignKey(Bus, on_delete=models.CASCADE, null=True) def __str__(self): return self.first_name, self.last_name class Guardian(models.Model): """a model to hold the details of the child's guardian """ first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone_number = models.CharField(max_length=10) email = models.EmailField() def __str__(self): return self.first_name, self.last_name, self.phone_number class Note(models.Model): """a model for holding the notes that Guardians and Staff can add notes (about delays) to the system. """ title = models.CharField(max_length=100) description = models.TextField() # defined options for delays as a tuple reason_choices = ( ('mech', "Bus mechanical failure"), ('delay_home', "Delayed at home(morning)"), ('delay_school', "Delayed at school(evening)"), ('traffic', "Road traffic jam"), ('emergency', "Emergency"), ) # pick a reason from the tuple list defined above reason = models.CharField(choices=reason_choices, default='traffic', max_length=200) created_at = models.DateTimeField(auto_now_add=True) created_by_staff = models.ForeignKey(BusStaff, on_delete=models.CASCADE, null=True, blank=True) created_by_guardian = models.ForeignKey(Guardian, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title, self.reason class Student(models.Model): """holds the student details """ first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) school = models.CharField(max_length=50, help_text='Enter the name of the school') guardian = models.ForeignKey(Guardian, on_delete=models.CASCADE, null=True) def __str__(self): β¦ -
How can I make real time checking input sections in Django forms
I don't know how to call it exactly, but what I wanna make is when I input something in website attribute in the model below, I want the input section to notify me if it already exists or not. It must check the existence every time I input a character by a character because it's a waste of time to notify me about existence after filling in all the input sections other than the website attribute. Does Django forms or something already support this feature? If not, can anyone guide me an efficient way to implement this feature? class Store(models.Model): ... website = models.CharField(max_length=100) ... -
Accessing uploaded files from Django
I am designing a web application that allows the user to upload a .xls file. On upload, the file should be saved, converted to a .csv file, then the data contained in the file will be imported via a python import script. All of the functions for importing and converting the data are fully functional from within the shell, however when testing via a localhost, the file is converted to .csv and saved but none of the scripts run on the new file. It is as if Django is preventing the newly created .csv file from being opened and read from. Any tips on solving this issue would be greatly appreciated! -
AJAX not opening attachment
I have a view that returns an HttpResponse: file_name = 'rel_acao_{}.xlsx'.format(dt.now().strftime("%Y%m%d")) response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename={}'.format(file_name) writer = pd.ExcelWriter(response) df_1.to_excel(writer, sheet_name='Sheet1') df_2.to_excel(writer, sheet_name='Sheet2') writer.save() return response These view is called with the following button: <div> <button id="btn_Export" type="button" onclick="sendReport()"> Export to Excel </button> </div> which in turn, calls the following function: // Dispatch function sendReport(){ $.ajax({ url: "{% url 'report_action:report_action_csv' %}", type: 'POST', data: { 'followup': JSON.stringify(followup), 'report': JSON.stringify(report) } }); } as seeing here, there is a file somewhere in this data limbo: Why am I not able to download the file? What am I doing wrong? -
Issues using path() in urls.py in django 2.0.5
I am following a tutorial which I'm trying to write in Django 2.0.5, but I got road block in the urls.py and I've been searching for a week, but still giving me Page not found (404) error message. Can someone give a clearer picture of path() as it seems to be not supporting regex. Here is my code: `` views.py from django.shortcuts import render #from django.http import HttpResponse from .models import Board Create your views here. ` from django.shortcuts import render #from django.http import HttpResponse from .models import Board ` templates/topics.html ` {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{board.name}}</title> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}">> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> <li class="breadcrumb-item">Boards</li> <li class="breadcrumb-item active">{{board.name}}</li> </ol> </div> </body> </html> ` urls.py ` from django.contrib import admin from django.urls import path from boards import views urlpatterns = [ path('', views.home, name='home'), path('<int:pk>/', views.board_topics, name='board_topics'), path('admin/', admin.site.urls) ] ` models.py ` from django.db import models from django.contrib.auth.models import User # Create your models here. class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.name class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, on_delete=models.CASCADE) starter = models.ForeignKey(User, on_delete=models.CASCADE) # def __str__(self): β¦ -
How do I patch a python method for a test case to run?
A project I'm working on uses django for basically everything. When writing a model, I found it necessary to override the save() method to spin off a task to be run by a worker: class MyModel(models.Model) def _start_processing(self): my_task.apply_async(args=['arg1', ..., 'argn']) def save(self, *args, **kwargs): """Saves the model object to the database""" # do some stuff self._start_processing() # do some more stuff super(MyModel, self).save(*args, **kwargs) In my tester, I want to test the parts of the save override that are designated by # do some stuff and # do some more stuff, but don't want to run the task. To do this, I believe I should be using mocking (which I'm very new to). In my test class, I've set it up to skip the task invocation: class MyModelTests(TestCase): def setUp(self): # Mock the _start_processing() method. Ha! @patch('my_app.models.MyModel._start_processing') def start_processing(self, mock_start_processing): print('This is when the task would normally be run, but this is a test!') # Create a model to test with self.test_object = MyModelFactory() Since the factory creates an saves an instance of the model, I need to have overwritten the _start_processing() method before that is called. The above doesn't seem to be working (and the task runs and β¦ -
NoReverseMatch: Reverse for 'complete' with arguments '(1,)' not found. 1 pattern(s) tried: ['complete/<todo_id>']
urls.py from django.conf.urls import url from . import views urlpatterns = [ url('', views.index, name= 'index'), url('add', views.addTodo, name ='add'), url('complete/<todo_id>', views.completeTodo, name='complete'), url('deletecomplete', views.deleteCompleted, name='deletecomplete'), url('deleteall', views.deleteAll, name='deleteall') ] views.py( portion of a program) def completeTodo(request, todo_id): todo = Todo.objects.get(pk=todo_id) todo.complete = True todo.save() return redirect('index') index.html(portion of program) I guess this is where the problem is coming. <ul class="list-group t20"> {% for todo in todo_list %} {% if todo.complete %} <li class="list-group-item todo-completed">{{ todo.text }}</li> {% else %} <a href="{% url 'complete' todo.id %}"><li class="list-group-item">{{ todo.text }}</li></a> {% endif %} {% endfor %} </ul> -
Showing CreateView form on ListView url
I have ListView class pointing to an url. I'd like to have a CreateView form on the same url, on top of each item of the list. So far no form is showing (only the button shows). How can I do this? Right now I have these classes, both pointing at the same url on urls.py: view.py: class TheList(ListView): model = Item template_name='item/post_create.html' class CreatePost(CreateView): model = Post fields = [ 'post' ] template_name_suffix='_create' -
Django isn't creating object
I'm a newbie in Django and I have this problem: When I try to create a new Object, Django enter to the exception. This is my model: class Archivo(models.Model): ramo = models.ForeignKey(Ramo, on_delete=models.CASCADE) activo = models.BooleanField(default="False") anyo = models.PositiveIntegerField() semestre = models.PositiveIntegerField() tipo = models.CharField(max_length=20, null=True) extension = models.CharField(max_length=5) archivo = models.FileField(upload_to='archivo/', null=True, storage=gd_storage) class Meta: ordering = ['-anyo'] def __str__(self): return '%s %s %s %s %s %s' % (self.ramo, self.activo, self.anyo, self.semestre, self.tipo, self.extension) And in my views.py, I'm creating the object by this way: try: nuevo = Archivo.objects.create(ramo=ramo_id, activo=activo, anyo=anyo, semestre=semester, tipo=tipo, extension=extension, archivo=file) nuevo.save() except: ... Also, I've printed ramo_id, activo, anyo, semester, tipo, extension, and archivo and It looks like this: ramo_id: 3 activo: False anyo: 2017 semester: 1 tipo: Solemne 2 extension: pdf archivo: archivo.pdf I don't know why Django is entering into the exception, it should work, all the parameters of the model are fine. Can anyone help me? Thanks!